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 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 // Limit the number of alias checks. The limit is chosen so that
172 // it has no negative effect on the llvm benchmarks.
173 static const unsigned AliasedCheckLimit = 10;
174 
175 // Another limit for the alias checks: The maximum distance between load/store
176 // instructions where alias checks are done.
177 // This limit is useful for very large basic blocks.
178 static const unsigned MaxMemDepDistance = 160;
179 
180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
181 /// regions to be handled.
182 static const int MinScheduleRegionSize = 16;
183 
184 /// Predicate for the element types that the SLP vectorizer supports.
185 ///
186 /// The most important thing to filter here are types which are invalid in LLVM
187 /// vectors. We also filter target specific types which have absolutely no
188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
189 /// avoids spending time checking the cost model and realizing that they will
190 /// be inevitably scalarized.
191 static bool isValidElementType(Type *Ty) {
192   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
193          !Ty->isPPC_FP128Ty();
194 }
195 
196 /// \returns True if the value is a constant (but not globals/constant
197 /// expressions).
198 static bool isConstant(Value *V) {
199   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
200 }
201 
202 /// Checks if \p V is one of vector-like instructions, i.e. undef,
203 /// insertelement/extractelement with constant indices for fixed vector type or
204 /// extractvalue instruction.
205 static bool isVectorLikeInstWithConstOps(Value *V) {
206   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
207       !isa<ExtractValueInst, UndefValue>(V))
208     return false;
209   auto *I = dyn_cast<Instruction>(V);
210   if (!I || isa<ExtractValueInst>(I))
211     return true;
212   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
213     return false;
214   if (isa<ExtractElementInst>(I))
215     return isConstant(I->getOperand(1));
216   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
217   return isConstant(I->getOperand(2));
218 }
219 
220 /// \returns true if all of the instructions in \p VL are in the same block or
221 /// false otherwise.
222 static bool allSameBlock(ArrayRef<Value *> VL) {
223   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
224   if (!I0)
225     return false;
226   if (all_of(VL, isVectorLikeInstWithConstOps))
227     return true;
228 
229   BasicBlock *BB = I0->getParent();
230   for (int I = 1, E = VL.size(); I < E; I++) {
231     auto *II = dyn_cast<Instruction>(VL[I]);
232     if (!II)
233       return false;
234 
235     if (BB != II->getParent())
236       return false;
237   }
238   return true;
239 }
240 
241 /// \returns True if all of the values in \p VL are constants (but not
242 /// globals/constant expressions).
243 static bool allConstant(ArrayRef<Value *> VL) {
244   // Constant expressions and globals can't be vectorized like normal integer/FP
245   // constants.
246   return all_of(VL, isConstant);
247 }
248 
249 /// \returns True if all of the values in \p VL are identical or some of them
250 /// are UndefValue.
251 static bool isSplat(ArrayRef<Value *> VL) {
252   Value *FirstNonUndef = nullptr;
253   for (Value *V : VL) {
254     if (isa<UndefValue>(V))
255       continue;
256     if (!FirstNonUndef) {
257       FirstNonUndef = V;
258       continue;
259     }
260     if (V != FirstNonUndef)
261       return false;
262   }
263   return FirstNonUndef != nullptr;
264 }
265 
266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
267 static bool isCommutative(Instruction *I) {
268   if (auto *Cmp = dyn_cast<CmpInst>(I))
269     return Cmp->isCommutative();
270   if (auto *BO = dyn_cast<BinaryOperator>(I))
271     return BO->isCommutative();
272   // TODO: This should check for generic Instruction::isCommutative(), but
273   //       we need to confirm that the caller code correctly handles Intrinsics
274   //       for example (does not have 2 operands).
275   return false;
276 }
277 
278 /// Checks if the given value is actually an undefined constant vector.
279 static bool isUndefVector(const Value *V) {
280   if (isa<UndefValue>(V))
281     return true;
282   auto *C = dyn_cast<Constant>(V);
283   if (!C)
284     return false;
285   if (!C->containsUndefOrPoisonElement())
286     return false;
287   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
288   if (!VecTy)
289     return false;
290   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
291     if (Constant *Elem = C->getAggregateElement(I))
292       if (!isa<UndefValue>(Elem))
293         return false;
294   }
295   return true;
296 }
297 
298 /// Checks if the vector of instructions can be represented as a shuffle, like:
299 /// %x0 = extractelement <4 x i8> %x, i32 0
300 /// %x3 = extractelement <4 x i8> %x, i32 3
301 /// %y1 = extractelement <4 x i8> %y, i32 1
302 /// %y2 = extractelement <4 x i8> %y, i32 2
303 /// %x0x0 = mul i8 %x0, %x0
304 /// %x3x3 = mul i8 %x3, %x3
305 /// %y1y1 = mul i8 %y1, %y1
306 /// %y2y2 = mul i8 %y2, %y2
307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
311 /// ret <4 x i8> %ins4
312 /// can be transformed into:
313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
314 ///                                                         i32 6>
315 /// %2 = mul <4 x i8> %1, %1
316 /// ret <4 x i8> %2
317 /// We convert this initially to something like:
318 /// %x0 = extractelement <4 x i8> %x, i32 0
319 /// %x3 = extractelement <4 x i8> %x, i32 3
320 /// %y1 = extractelement <4 x i8> %y, i32 1
321 /// %y2 = extractelement <4 x i8> %y, i32 2
322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
326 /// %5 = mul <4 x i8> %4, %4
327 /// %6 = extractelement <4 x i8> %5, i32 0
328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
329 /// %7 = extractelement <4 x i8> %5, i32 1
330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
331 /// %8 = extractelement <4 x i8> %5, i32 2
332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
333 /// %9 = extractelement <4 x i8> %5, i32 3
334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
335 /// ret <4 x i8> %ins4
336 /// InstCombiner transforms this into a shuffle and vector mul
337 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
338 /// TODO: Can we split off and reuse the shuffle mask detection from
339 /// TargetTransformInfo::getInstructionThroughput?
340 static Optional<TargetTransformInfo::ShuffleKind>
341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
342   const auto *It =
343       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
344   if (It == VL.end())
345     return None;
346   auto *EI0 = cast<ExtractElementInst>(*It);
347   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
348     return None;
349   unsigned Size =
350       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
351   Value *Vec1 = nullptr;
352   Value *Vec2 = nullptr;
353   enum ShuffleMode { Unknown, Select, Permute };
354   ShuffleMode CommonShuffleMode = Unknown;
355   Mask.assign(VL.size(), UndefMaskElem);
356   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
357     // Undef can be represented as an undef element in a vector.
358     if (isa<UndefValue>(VL[I]))
359       continue;
360     auto *EI = cast<ExtractElementInst>(VL[I]);
361     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
362       return None;
363     auto *Vec = EI->getVectorOperand();
364     // We can extractelement from undef or poison vector.
365     if (isUndefVector(Vec))
366       continue;
367     // All vector operands must have the same number of vector elements.
368     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
369       return None;
370     if (isa<UndefValue>(EI->getIndexOperand()))
371       continue;
372     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
373     if (!Idx)
374       return None;
375     // Undefined behavior if Idx is negative or >= Size.
376     if (Idx->getValue().uge(Size))
377       continue;
378     unsigned IntIdx = Idx->getValue().getZExtValue();
379     Mask[I] = IntIdx;
380     // For correct shuffling we have to have at most 2 different vector operands
381     // in all extractelement instructions.
382     if (!Vec1 || Vec1 == Vec) {
383       Vec1 = Vec;
384     } else if (!Vec2 || Vec2 == Vec) {
385       Vec2 = Vec;
386       Mask[I] += Size;
387     } else {
388       return None;
389     }
390     if (CommonShuffleMode == Permute)
391       continue;
392     // If the extract index is not the same as the operation number, it is a
393     // permutation.
394     if (IntIdx != I) {
395       CommonShuffleMode = Permute;
396       continue;
397     }
398     CommonShuffleMode = Select;
399   }
400   // If we're not crossing lanes in different vectors, consider it as blending.
401   if (CommonShuffleMode == Select && Vec2)
402     return TargetTransformInfo::SK_Select;
403   // If Vec2 was never used, we have a permutation of a single vector, otherwise
404   // we have permutation of 2 vectors.
405   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
406               : TargetTransformInfo::SK_PermuteSingleSrc;
407 }
408 
409 namespace {
410 
411 /// Main data required for vectorization of instructions.
412 struct InstructionsState {
413   /// The very first instruction in the list with the main opcode.
414   Value *OpValue = nullptr;
415 
416   /// The main/alternate instruction.
417   Instruction *MainOp = nullptr;
418   Instruction *AltOp = nullptr;
419 
420   /// The main/alternate opcodes for the list of instructions.
421   unsigned getOpcode() const {
422     return MainOp ? MainOp->getOpcode() : 0;
423   }
424 
425   unsigned getAltOpcode() const {
426     return AltOp ? AltOp->getOpcode() : 0;
427   }
428 
429   /// Some of the instructions in the list have alternate opcodes.
430   bool isAltShuffle() const { return AltOp != MainOp; }
431 
432   bool isOpcodeOrAlt(Instruction *I) const {
433     unsigned CheckedOpcode = I->getOpcode();
434     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
435   }
436 
437   InstructionsState() = delete;
438   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
439       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
440 };
441 
442 } // end anonymous namespace
443 
444 /// Chooses the correct key for scheduling data. If \p Op has the same (or
445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
446 /// OpValue.
447 static Value *isOneOf(const InstructionsState &S, Value *Op) {
448   auto *I = dyn_cast<Instruction>(Op);
449   if (I && S.isOpcodeOrAlt(I))
450     return Op;
451   return S.OpValue;
452 }
453 
454 /// \returns true if \p Opcode is allowed as part of of the main/alternate
455 /// instruction for SLP vectorization.
456 ///
457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
458 /// "shuffled out" lane would result in division by zero.
459 static bool isValidForAlternation(unsigned Opcode) {
460   if (Instruction::isIntDivRem(Opcode))
461     return false;
462 
463   return true;
464 }
465 
466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
467                                        unsigned BaseIndex = 0);
468 
469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
470 /// compatible instructions or constants, or just some other regular values.
471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
472                                 Value *Op1) {
473   return (isConstant(BaseOp0) && isConstant(Op0)) ||
474          (isConstant(BaseOp1) && isConstant(Op1)) ||
475          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
476           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
477          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
478          getSameOpcode({BaseOp1, Op1}).getOpcode();
479 }
480 
481 /// \returns analysis of the Instructions in \p VL described in
482 /// InstructionsState, the Opcode that we suppose the whole list
483 /// could be vectorized even if its structure is diverse.
484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
485                                        unsigned BaseIndex) {
486   // Make sure these are all Instructions.
487   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
488     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
489 
490   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
491   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
492   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
493   CmpInst::Predicate BasePred =
494       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
495               : CmpInst::BAD_ICMP_PREDICATE;
496   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
497   unsigned AltOpcode = Opcode;
498   unsigned AltIndex = BaseIndex;
499 
500   // Check for one alternate opcode from another BinaryOperator.
501   // TODO - generalize to support all operators (types, calls etc.).
502   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
503     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
504     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
505       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
506         continue;
507       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
508           isValidForAlternation(Opcode)) {
509         AltOpcode = InstOpcode;
510         AltIndex = Cnt;
511         continue;
512       }
513     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
514       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
515       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
516       if (Ty0 == Ty1) {
517         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518           continue;
519         if (Opcode == AltOpcode) {
520           assert(isValidForAlternation(Opcode) &&
521                  isValidForAlternation(InstOpcode) &&
522                  "Cast isn't safe for alternation, logic needs to be updated!");
523           AltOpcode = InstOpcode;
524           AltIndex = Cnt;
525           continue;
526         }
527       }
528     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
529       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
530       auto *Inst = cast<Instruction>(VL[Cnt]);
531       Type *Ty0 = BaseInst->getOperand(0)->getType();
532       Type *Ty1 = Inst->getOperand(0)->getType();
533       if (Ty0 == Ty1) {
534         Value *BaseOp0 = BaseInst->getOperand(0);
535         Value *BaseOp1 = BaseInst->getOperand(1);
536         Value *Op0 = Inst->getOperand(0);
537         Value *Op1 = Inst->getOperand(1);
538         CmpInst::Predicate CurrentPred =
539             cast<CmpInst>(VL[Cnt])->getPredicate();
540         CmpInst::Predicate SwappedCurrentPred =
541             CmpInst::getSwappedPredicate(CurrentPred);
542         // Check for compatible operands. If the corresponding operands are not
543         // compatible - need to perform alternate vectorization.
544         if (InstOpcode == Opcode) {
545           if (BasePred == CurrentPred &&
546               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
547             continue;
548           if (BasePred == SwappedCurrentPred &&
549               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
550             continue;
551           if (E == 2 &&
552               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
553             continue;
554           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
555           CmpInst::Predicate AltPred = AltInst->getPredicate();
556           Value *AltOp0 = AltInst->getOperand(0);
557           Value *AltOp1 = AltInst->getOperand(1);
558           // Check if operands are compatible with alternate operands.
559           if (AltPred == CurrentPred &&
560               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
561             continue;
562           if (AltPred == SwappedCurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
564             continue;
565         }
566         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
567           assert(isValidForAlternation(Opcode) &&
568                  isValidForAlternation(InstOpcode) &&
569                  "Cast isn't safe for alternation, logic needs to be updated!");
570           AltIndex = Cnt;
571           continue;
572         }
573         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
574         CmpInst::Predicate AltPred = AltInst->getPredicate();
575         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
576             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
577           continue;
578       }
579     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
580       continue;
581     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
582   }
583 
584   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
585                            cast<Instruction>(VL[AltIndex]));
586 }
587 
588 /// \returns true if all of the values in \p VL have the same type or false
589 /// otherwise.
590 static bool allSameType(ArrayRef<Value *> VL) {
591   Type *Ty = VL[0]->getType();
592   for (int i = 1, e = VL.size(); i < e; i++)
593     if (VL[i]->getType() != Ty)
594       return false;
595 
596   return true;
597 }
598 
599 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
600 static Optional<unsigned> getExtractIndex(Instruction *E) {
601   unsigned Opcode = E->getOpcode();
602   assert((Opcode == Instruction::ExtractElement ||
603           Opcode == Instruction::ExtractValue) &&
604          "Expected extractelement or extractvalue instruction.");
605   if (Opcode == Instruction::ExtractElement) {
606     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
607     if (!CI)
608       return None;
609     return CI->getZExtValue();
610   }
611   ExtractValueInst *EI = cast<ExtractValueInst>(E);
612   if (EI->getNumIndices() != 1)
613     return None;
614   return *EI->idx_begin();
615 }
616 
617 /// \returns True if in-tree use also needs extract. This refers to
618 /// possible scalar operand in vectorized instruction.
619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
620                                     TargetLibraryInfo *TLI) {
621   unsigned Opcode = UserInst->getOpcode();
622   switch (Opcode) {
623   case Instruction::Load: {
624     LoadInst *LI = cast<LoadInst>(UserInst);
625     return (LI->getPointerOperand() == Scalar);
626   }
627   case Instruction::Store: {
628     StoreInst *SI = cast<StoreInst>(UserInst);
629     return (SI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Call: {
632     CallInst *CI = cast<CallInst>(UserInst);
633     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
634     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
635       if (hasVectorInstrinsicScalarOpd(ID, i))
636         return (CI->getArgOperand(i) == Scalar);
637     }
638     LLVM_FALLTHROUGH;
639   }
640   default:
641     return false;
642   }
643 }
644 
645 /// \returns the AA location that is being access by the instruction.
646 static MemoryLocation getLocation(Instruction *I) {
647   if (StoreInst *SI = dyn_cast<StoreInst>(I))
648     return MemoryLocation::get(SI);
649   if (LoadInst *LI = dyn_cast<LoadInst>(I))
650     return MemoryLocation::get(LI);
651   return MemoryLocation();
652 }
653 
654 /// \returns True if the instruction is not a volatile or atomic load/store.
655 static bool isSimple(Instruction *I) {
656   if (LoadInst *LI = dyn_cast<LoadInst>(I))
657     return LI->isSimple();
658   if (StoreInst *SI = dyn_cast<StoreInst>(I))
659     return SI->isSimple();
660   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
661     return !MI->isVolatile();
662   return true;
663 }
664 
665 /// Shuffles \p Mask in accordance with the given \p SubMask.
666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
667   if (SubMask.empty())
668     return;
669   if (Mask.empty()) {
670     Mask.append(SubMask.begin(), SubMask.end());
671     return;
672   }
673   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
674   int TermValue = std::min(Mask.size(), SubMask.size());
675   for (int I = 0, E = SubMask.size(); I < E; ++I) {
676     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
677         Mask[SubMask[I]] >= TermValue)
678       continue;
679     NewMask[I] = Mask[SubMask[I]];
680   }
681   Mask.swap(NewMask);
682 }
683 
684 /// Order may have elements assigned special value (size) which is out of
685 /// bounds. Such indices only appear on places which correspond to undef values
686 /// (see canReuseExtract for details) and used in order to avoid undef values
687 /// have effect on operands ordering.
688 /// The first loop below simply finds all unused indices and then the next loop
689 /// nest assigns these indices for undef values positions.
690 /// As an example below Order has two undef positions and they have assigned
691 /// values 3 and 7 respectively:
692 /// before:  6 9 5 4 9 2 1 0
693 /// after:   6 3 5 4 7 2 1 0
694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
695   const unsigned Sz = Order.size();
696   SmallBitVector UnusedIndices(Sz, /*t=*/true);
697   SmallBitVector MaskedIndices(Sz);
698   for (unsigned I = 0; I < Sz; ++I) {
699     if (Order[I] < Sz)
700       UnusedIndices.reset(Order[I]);
701     else
702       MaskedIndices.set(I);
703   }
704   if (MaskedIndices.none())
705     return;
706   assert(UnusedIndices.count() == MaskedIndices.count() &&
707          "Non-synced masked/available indices.");
708   int Idx = UnusedIndices.find_first();
709   int MIdx = MaskedIndices.find_first();
710   while (MIdx >= 0) {
711     assert(Idx >= 0 && "Indices must be synced.");
712     Order[MIdx] = Idx;
713     Idx = UnusedIndices.find_next(Idx);
714     MIdx = MaskedIndices.find_next(MIdx);
715   }
716 }
717 
718 namespace llvm {
719 
720 static void inversePermutation(ArrayRef<unsigned> Indices,
721                                SmallVectorImpl<int> &Mask) {
722   Mask.clear();
723   const unsigned E = Indices.size();
724   Mask.resize(E, UndefMaskElem);
725   for (unsigned I = 0; I < E; ++I)
726     Mask[Indices[I]] = I;
727 }
728 
729 /// \returns inserting index of InsertElement or InsertValue instruction,
730 /// using Offset as base offset for index.
731 static Optional<unsigned> getInsertIndex(Value *InsertInst,
732                                          unsigned Offset = 0) {
733   int Index = Offset;
734   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
735     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
736       auto *VT = cast<FixedVectorType>(IE->getType());
737       if (CI->getValue().uge(VT->getNumElements()))
738         return None;
739       Index *= VT->getNumElements();
740       Index += CI->getZExtValue();
741       return Index;
742     }
743     return None;
744   }
745 
746   auto *IV = cast<InsertValueInst>(InsertInst);
747   Type *CurrentType = IV->getType();
748   for (unsigned I : IV->indices()) {
749     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
750       Index *= ST->getNumElements();
751       CurrentType = ST->getElementType(I);
752     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
753       Index *= AT->getNumElements();
754       CurrentType = AT->getElementType();
755     } else {
756       return None;
757     }
758     Index += I;
759   }
760   return Index;
761 }
762 
763 /// Reorders the list of scalars in accordance with the given \p Mask.
764 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
765                            ArrayRef<int> Mask) {
766   assert(!Mask.empty() && "Expected non-empty mask.");
767   SmallVector<Value *> Prev(Scalars.size(),
768                             UndefValue::get(Scalars.front()->getType()));
769   Prev.swap(Scalars);
770   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
771     if (Mask[I] != UndefMaskElem)
772       Scalars[Mask[I]] = Prev[I];
773 }
774 
775 /// Checks if the provided value does not require scheduling. It does not
776 /// require scheduling if this is not an instruction or it is an instruction
777 /// that does not read/write memory and all operands are either not instructions
778 /// or phi nodes or instructions from different blocks.
779 static bool areAllOperandsNonInsts(Value *V) {
780   auto *I = dyn_cast<Instruction>(V);
781   if (!I)
782     return true;
783   return !mayHaveNonDefUseDependency(*I) &&
784     all_of(I->operands(), [I](Value *V) {
785       auto *IO = dyn_cast<Instruction>(V);
786       if (!IO)
787         return true;
788       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
789     });
790 }
791 
792 /// Checks if the provided value does not require scheduling. It does not
793 /// require scheduling if this is not an instruction or it is an instruction
794 /// that does not read/write memory and all users are phi nodes or instructions
795 /// from the different blocks.
796 static bool isUsedOutsideBlock(Value *V) {
797   auto *I = dyn_cast<Instruction>(V);
798   if (!I)
799     return true;
800   // Limits the number of uses to save compile time.
801   constexpr int UsesLimit = 8;
802   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
803          all_of(I->users(), [I](User *U) {
804            auto *IU = dyn_cast<Instruction>(U);
805            if (!IU)
806              return true;
807            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
808          });
809 }
810 
811 /// Checks if the specified value does not require scheduling. It does not
812 /// require scheduling if all operands and all users do not need to be scheduled
813 /// in the current basic block.
814 static bool doesNotNeedToBeScheduled(Value *V) {
815   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
816 }
817 
818 /// Checks if the specified array of instructions does not require scheduling.
819 /// It is so if all either instructions have operands that do not require
820 /// scheduling or their users do not require scheduling since they are phis or
821 /// in other basic blocks.
822 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
823   return !VL.empty() &&
824          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
825 }
826 
827 namespace slpvectorizer {
828 
829 /// Bottom Up SLP Vectorizer.
830 class BoUpSLP {
831   struct TreeEntry;
832   struct ScheduleData;
833 
834 public:
835   using ValueList = SmallVector<Value *, 8>;
836   using InstrList = SmallVector<Instruction *, 16>;
837   using ValueSet = SmallPtrSet<Value *, 16>;
838   using StoreList = SmallVector<StoreInst *, 8>;
839   using ExtraValueToDebugLocsMap =
840       MapVector<Value *, SmallVector<Instruction *, 2>>;
841   using OrdersType = SmallVector<unsigned, 4>;
842 
843   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
844           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
845           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
846           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
847       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
848         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
849     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
850     // Use the vector register size specified by the target unless overridden
851     // by a command-line option.
852     // TODO: It would be better to limit the vectorization factor based on
853     //       data type rather than just register size. For example, x86 AVX has
854     //       256-bit registers, but it does not support integer operations
855     //       at that width (that requires AVX2).
856     if (MaxVectorRegSizeOption.getNumOccurrences())
857       MaxVecRegSize = MaxVectorRegSizeOption;
858     else
859       MaxVecRegSize =
860           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
861               .getFixedSize();
862 
863     if (MinVectorRegSizeOption.getNumOccurrences())
864       MinVecRegSize = MinVectorRegSizeOption;
865     else
866       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
867   }
868 
869   /// Vectorize the tree that starts with the elements in \p VL.
870   /// Returns the vectorized root.
871   Value *vectorizeTree();
872 
873   /// Vectorize the tree but with the list of externally used values \p
874   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
875   /// generated extractvalue instructions.
876   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
877 
878   /// \returns the cost incurred by unwanted spills and fills, caused by
879   /// holding live values over call sites.
880   InstructionCost getSpillCost() const;
881 
882   /// \returns the vectorization cost of the subtree that starts at \p VL.
883   /// A negative number means that this is profitable.
884   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
885 
886   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
887   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
888   void buildTree(ArrayRef<Value *> Roots,
889                  ArrayRef<Value *> UserIgnoreLst = None);
890 
891   /// Builds external uses of the vectorized scalars, i.e. the list of
892   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
893   /// ExternallyUsedValues contains additional list of external uses to handle
894   /// vectorization of reductions.
895   void
896   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
897 
898   /// Clear the internal data structures that are created by 'buildTree'.
899   void deleteTree() {
900     VectorizableTree.clear();
901     ScalarToTreeEntry.clear();
902     MustGather.clear();
903     ExternalUses.clear();
904     for (auto &Iter : BlocksSchedules) {
905       BlockScheduling *BS = Iter.second.get();
906       BS->clear();
907     }
908     MinBWs.clear();
909     InstrElementSize.clear();
910   }
911 
912   unsigned getTreeSize() const { return VectorizableTree.size(); }
913 
914   /// Perform LICM and CSE on the newly generated gather sequences.
915   void optimizeGatherSequence();
916 
917   /// Checks if the specified gather tree entry \p TE can be represented as a
918   /// shuffled vector entry + (possibly) permutation with other gathers. It
919   /// implements the checks only for possibly ordered scalars (Loads,
920   /// ExtractElement, ExtractValue), which can be part of the graph.
921   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
922 
923   /// Gets reordering data for the given tree entry. If the entry is vectorized
924   /// - just return ReorderIndices, otherwise check if the scalars can be
925   /// reordered and return the most optimal order.
926   /// \param TopToBottom If true, include the order of vectorized stores and
927   /// insertelement nodes, otherwise skip them.
928   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
929 
930   /// Reorders the current graph to the most profitable order starting from the
931   /// root node to the leaf nodes. The best order is chosen only from the nodes
932   /// of the same size (vectorization factor). Smaller nodes are considered
933   /// parts of subgraph with smaller VF and they are reordered independently. We
934   /// can make it because we still need to extend smaller nodes to the wider VF
935   /// and we can merge reordering shuffles with the widening shuffles.
936   void reorderTopToBottom();
937 
938   /// Reorders the current graph to the most profitable order starting from
939   /// leaves to the root. It allows to rotate small subgraphs and reduce the
940   /// number of reshuffles if the leaf nodes use the same order. In this case we
941   /// can merge the orders and just shuffle user node instead of shuffling its
942   /// operands. Plus, even the leaf nodes have different orders, it allows to
943   /// sink reordering in the graph closer to the root node and merge it later
944   /// during analysis.
945   void reorderBottomToTop(bool IgnoreReorder = false);
946 
947   /// \return The vector element size in bits to use when vectorizing the
948   /// expression tree ending at \p V. If V is a store, the size is the width of
949   /// the stored value. Otherwise, the size is the width of the largest loaded
950   /// value reaching V. This method is used by the vectorizer to calculate
951   /// vectorization factors.
952   unsigned getVectorElementSize(Value *V);
953 
954   /// Compute the minimum type sizes required to represent the entries in a
955   /// vectorizable tree.
956   void computeMinimumValueSizes();
957 
958   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
959   unsigned getMaxVecRegSize() const {
960     return MaxVecRegSize;
961   }
962 
963   // \returns minimum vector register size as set by cl::opt.
964   unsigned getMinVecRegSize() const {
965     return MinVecRegSize;
966   }
967 
968   unsigned getMinVF(unsigned Sz) const {
969     return std::max(2U, getMinVecRegSize() / Sz);
970   }
971 
972   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
973     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
974       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
975     return MaxVF ? MaxVF : UINT_MAX;
976   }
977 
978   /// Check if homogeneous aggregate is isomorphic to some VectorType.
979   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
980   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
981   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
982   ///
983   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
984   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
985 
986   /// \returns True if the VectorizableTree is both tiny and not fully
987   /// vectorizable. We do not vectorize such trees.
988   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
989 
990   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
991   /// can be load combined in the backend. Load combining may not be allowed in
992   /// the IR optimizer, so we do not want to alter the pattern. For example,
993   /// partially transforming a scalar bswap() pattern into vector code is
994   /// effectively impossible for the backend to undo.
995   /// TODO: If load combining is allowed in the IR optimizer, this analysis
996   ///       may not be necessary.
997   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
998 
999   /// Assume that a vector of stores of bitwise-or/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 isLoadCombineCandidate() const;
1007 
1008   OptimizationRemarkEmitter *getORE() { return ORE; }
1009 
1010   /// This structure holds any data we need about the edges being traversed
1011   /// during buildTree_rec(). We keep track of:
1012   /// (i) the user TreeEntry index, and
1013   /// (ii) the index of the edge.
1014   struct EdgeInfo {
1015     EdgeInfo() = default;
1016     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1017         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1018     /// The user TreeEntry.
1019     TreeEntry *UserTE = nullptr;
1020     /// The operand index of the use.
1021     unsigned EdgeIdx = UINT_MAX;
1022 #ifndef NDEBUG
1023     friend inline raw_ostream &operator<<(raw_ostream &OS,
1024                                           const BoUpSLP::EdgeInfo &EI) {
1025       EI.dump(OS);
1026       return OS;
1027     }
1028     /// Debug print.
1029     void dump(raw_ostream &OS) const {
1030       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1031          << " EdgeIdx:" << EdgeIdx << "}";
1032     }
1033     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1034 #endif
1035   };
1036 
1037   /// A helper data structure to hold the operands of a vector of instructions.
1038   /// This supports a fixed vector length for all operand vectors.
1039   class VLOperands {
1040     /// For each operand we need (i) the value, and (ii) the opcode that it
1041     /// would be attached to if the expression was in a left-linearized form.
1042     /// This is required to avoid illegal operand reordering.
1043     /// For example:
1044     /// \verbatim
1045     ///                         0 Op1
1046     ///                         |/
1047     /// Op1 Op2   Linearized    + Op2
1048     ///   \ /     ---------->   |/
1049     ///    -                    -
1050     ///
1051     /// Op1 - Op2            (0 + Op1) - Op2
1052     /// \endverbatim
1053     ///
1054     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1055     ///
1056     /// Another way to think of this is to track all the operations across the
1057     /// path from the operand all the way to the root of the tree and to
1058     /// calculate the operation that corresponds to this path. For example, the
1059     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1060     /// corresponding operation is a '-' (which matches the one in the
1061     /// linearized tree, as shown above).
1062     ///
1063     /// For lack of a better term, we refer to this operation as Accumulated
1064     /// Path Operation (APO).
1065     struct OperandData {
1066       OperandData() = default;
1067       OperandData(Value *V, bool APO, bool IsUsed)
1068           : V(V), APO(APO), IsUsed(IsUsed) {}
1069       /// The operand value.
1070       Value *V = nullptr;
1071       /// TreeEntries only allow a single opcode, or an alternate sequence of
1072       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1073       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1074       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1075       /// (e.g., Add/Mul)
1076       bool APO = false;
1077       /// Helper data for the reordering function.
1078       bool IsUsed = false;
1079     };
1080 
1081     /// During operand reordering, we are trying to select the operand at lane
1082     /// that matches best with the operand at the neighboring lane. Our
1083     /// selection is based on the type of value we are looking for. For example,
1084     /// if the neighboring lane has a load, we need to look for a load that is
1085     /// accessing a consecutive address. These strategies are summarized in the
1086     /// 'ReorderingMode' enumerator.
1087     enum class ReorderingMode {
1088       Load,     ///< Matching loads to consecutive memory addresses
1089       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1090       Constant, ///< Matching constants
1091       Splat,    ///< Matching the same instruction multiple times (broadcast)
1092       Failed,   ///< We failed to create a vectorizable group
1093     };
1094 
1095     using OperandDataVec = SmallVector<OperandData, 2>;
1096 
1097     /// A vector of operand vectors.
1098     SmallVector<OperandDataVec, 4> OpsVec;
1099 
1100     const DataLayout &DL;
1101     ScalarEvolution &SE;
1102     const BoUpSLP &R;
1103 
1104     /// \returns the operand data at \p OpIdx and \p Lane.
1105     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1106       return OpsVec[OpIdx][Lane];
1107     }
1108 
1109     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1110     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1111       return OpsVec[OpIdx][Lane];
1112     }
1113 
1114     /// Clears the used flag for all entries.
1115     void clearUsed() {
1116       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1117            OpIdx != NumOperands; ++OpIdx)
1118         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1119              ++Lane)
1120           OpsVec[OpIdx][Lane].IsUsed = false;
1121     }
1122 
1123     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1124     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1125       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1126     }
1127 
1128     // The hard-coded scores listed here are not very important, though it shall
1129     // be higher for better matches to improve the resulting cost. When
1130     // computing the scores of matching one sub-tree with another, we are
1131     // basically counting the number of values that are matching. So even if all
1132     // scores are set to 1, we would still get a decent matching result.
1133     // However, sometimes we have to break ties. For example we may have to
1134     // choose between matching loads vs matching opcodes. This is what these
1135     // scores are helping us with: they provide the order of preference. Also,
1136     // this is important if the scalar is externally used or used in another
1137     // tree entry node in the different lane.
1138 
1139     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1140     static const int ScoreConsecutiveLoads = 4;
1141     /// The same load multiple times. This should have a better score than
1142     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1143     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1144     /// a vector load and 1.0 for a broadcast.
1145     static const int ScoreSplatLoads = 3;
1146     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1147     static const int ScoreReversedLoads = 3;
1148     /// ExtractElementInst from same vector and consecutive indexes.
1149     static const int ScoreConsecutiveExtracts = 4;
1150     /// ExtractElementInst from same vector and reversed indices.
1151     static const int ScoreReversedExtracts = 3;
1152     /// Constants.
1153     static const int ScoreConstants = 2;
1154     /// Instructions with the same opcode.
1155     static const int ScoreSameOpcode = 2;
1156     /// Instructions with alt opcodes (e.g, add + sub).
1157     static const int ScoreAltOpcodes = 1;
1158     /// Identical instructions (a.k.a. splat or broadcast).
1159     static const int ScoreSplat = 1;
1160     /// Matching with an undef is preferable to failing.
1161     static const int ScoreUndef = 1;
1162     /// Score for failing to find a decent match.
1163     static const int ScoreFail = 0;
1164     /// Score if all users are vectorized.
1165     static const int ScoreAllUserVectorized = 1;
1166 
1167     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1168     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1169     /// MainAltOps.
1170     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1171                         const DataLayout &DL, ScalarEvolution &SE, int NumLanes,
1172                         ArrayRef<Value *> MainAltOps) {
1173       if (V1 == V2) {
1174         if (isa<LoadInst>(V1)) {
1175           // Retruns true if the users of V1 and V2 won't need to be extracted.
1176           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1177             // Bail out if we have too many uses to save compilation time.
1178             static constexpr unsigned Limit = 8;
1179             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1180               return false;
1181 
1182             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1183               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1184                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1185               });
1186             };
1187             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1188           };
1189           // A broadcast of a load can be cheaper on some targets.
1190           if (R.TTI->isLegalBroadcastLoad(V1->getType(), NumLanes) &&
1191               ((int)V1->getNumUses() == NumLanes ||
1192                AllUsersAreInternal(V1, V2)))
1193             return VLOperands::ScoreSplatLoads;
1194         }
1195         return VLOperands::ScoreSplat;
1196       }
1197 
1198       auto *LI1 = dyn_cast<LoadInst>(V1);
1199       auto *LI2 = dyn_cast<LoadInst>(V2);
1200       if (LI1 && LI2) {
1201         if (LI1->getParent() != LI2->getParent())
1202           return VLOperands::ScoreFail;
1203 
1204         Optional<int> Dist = getPointersDiff(
1205             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1206             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1207         if (!Dist || *Dist == 0)
1208           return VLOperands::ScoreFail;
1209         // The distance is too large - still may be profitable to use masked
1210         // loads/gathers.
1211         if (std::abs(*Dist) > NumLanes / 2)
1212           return VLOperands::ScoreAltOpcodes;
1213         // This still will detect consecutive loads, but we might have "holes"
1214         // in some cases. It is ok for non-power-2 vectorization and may produce
1215         // better results. It should not affect current vectorization.
1216         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1217                            : VLOperands::ScoreReversedLoads;
1218       }
1219 
1220       auto *C1 = dyn_cast<Constant>(V1);
1221       auto *C2 = dyn_cast<Constant>(V2);
1222       if (C1 && C2)
1223         return VLOperands::ScoreConstants;
1224 
1225       // Extracts from consecutive indexes of the same vector better score as
1226       // the extracts could be optimized away.
1227       Value *EV1;
1228       ConstantInt *Ex1Idx;
1229       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1230         // Undefs are always profitable for extractelements.
1231         if (isa<UndefValue>(V2))
1232           return VLOperands::ScoreConsecutiveExtracts;
1233         Value *EV2 = nullptr;
1234         ConstantInt *Ex2Idx = nullptr;
1235         if (match(V2,
1236                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1237                                                          m_Undef())))) {
1238           // Undefs are always profitable for extractelements.
1239           if (!Ex2Idx)
1240             return VLOperands::ScoreConsecutiveExtracts;
1241           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1242             return VLOperands::ScoreConsecutiveExtracts;
1243           if (EV2 == EV1) {
1244             int Idx1 = Ex1Idx->getZExtValue();
1245             int Idx2 = Ex2Idx->getZExtValue();
1246             int Dist = Idx2 - Idx1;
1247             // The distance is too large - still may be profitable to use
1248             // shuffles.
1249             if (std::abs(Dist) == 0)
1250               return VLOperands::ScoreSplat;
1251             if (std::abs(Dist) > NumLanes / 2)
1252               return VLOperands::ScoreSameOpcode;
1253             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1254                               : VLOperands::ScoreReversedExtracts;
1255           }
1256           return VLOperands::ScoreAltOpcodes;
1257         }
1258         return VLOperands::ScoreFail;
1259       }
1260 
1261       auto *I1 = dyn_cast<Instruction>(V1);
1262       auto *I2 = dyn_cast<Instruction>(V2);
1263       if (I1 && I2) {
1264         if (I1->getParent() != I2->getParent())
1265           return VLOperands::ScoreFail;
1266         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1267         Ops.push_back(I1);
1268         Ops.push_back(I2);
1269         InstructionsState S = getSameOpcode(Ops);
1270         // Note: Only consider instructions with <= 2 operands to avoid
1271         // complexity explosion.
1272         if (S.getOpcode() &&
1273             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1274              !S.isAltShuffle()) &&
1275             all_of(Ops, [&S](Value *V) {
1276               return cast<Instruction>(V)->getNumOperands() ==
1277                      S.MainOp->getNumOperands();
1278             }))
1279           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1280                                   : VLOperands::ScoreSameOpcode;
1281       }
1282 
1283       if (isa<UndefValue>(V2))
1284         return VLOperands::ScoreUndef;
1285 
1286       return VLOperands::ScoreFail;
1287     }
1288 
1289     /// \param Lane lane of the operands under analysis.
1290     /// \param OpIdx operand index in \p Lane lane we're looking the best
1291     /// candidate for.
1292     /// \param Idx operand index of the current candidate value.
1293     /// \returns The additional score due to possible broadcasting of the
1294     /// elements in the lane. It is more profitable to have power-of-2 unique
1295     /// elements in the lane, it will be vectorized with higher probability
1296     /// after removing duplicates. Currently the SLP vectorizer supports only
1297     /// vectorization of the power-of-2 number of unique scalars.
1298     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1299       Value *IdxLaneV = getData(Idx, Lane).V;
1300       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1301         return 0;
1302       SmallPtrSet<Value *, 4> Uniques;
1303       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1304         if (Ln == Lane)
1305           continue;
1306         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1307         if (!isa<Instruction>(OpIdxLnV))
1308           return 0;
1309         Uniques.insert(OpIdxLnV);
1310       }
1311       int UniquesCount = Uniques.size();
1312       int UniquesCntWithIdxLaneV =
1313           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1314       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1315       int UniquesCntWithOpIdxLaneV =
1316           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1317       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1318         return 0;
1319       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1320               UniquesCntWithOpIdxLaneV) -
1321              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1322     }
1323 
1324     /// \param Lane lane of the operands under analysis.
1325     /// \param OpIdx operand index in \p Lane lane we're looking the best
1326     /// candidate for.
1327     /// \param Idx operand index of the current candidate value.
1328     /// \returns The additional score for the scalar which users are all
1329     /// vectorized.
1330     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1331       Value *IdxLaneV = getData(Idx, Lane).V;
1332       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1333       // Do not care about number of uses for vector-like instructions
1334       // (extractelement/extractvalue with constant indices), they are extracts
1335       // themselves and already externally used. Vectorization of such
1336       // instructions does not add extra extractelement instruction, just may
1337       // remove it.
1338       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1339           isVectorLikeInstWithConstOps(OpIdxLaneV))
1340         return VLOperands::ScoreAllUserVectorized;
1341       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1342       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1343         return 0;
1344       return R.areAllUsersVectorized(IdxLaneI, None)
1345                  ? VLOperands::ScoreAllUserVectorized
1346                  : 0;
1347     }
1348 
1349     /// Go through the operands of \p LHS and \p RHS recursively until \p
1350     /// MaxLevel, and return the cummulative score. For example:
1351     /// \verbatim
1352     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1353     ///     \ /         \ /         \ /        \ /
1354     ///      +           +           +          +
1355     ///     G1          G2          G3         G4
1356     /// \endverbatim
1357     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1358     /// each level recursively, accumulating the score. It starts from matching
1359     /// the additions at level 0, then moves on to the loads (level 1). The
1360     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1361     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1362     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1363     /// Please note that the order of the operands does not matter, as we
1364     /// evaluate the score of all profitable combinations of operands. In
1365     /// other words the score of G1 and G4 is the same as G1 and G2. This
1366     /// heuristic is based on ideas described in:
1367     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1368     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1369     ///   Luís F. W. Góes
1370     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1371                            Instruction *U2, int CurrLevel, int MaxLevel,
1372                            ArrayRef<Value *> MainAltOps) {
1373 
1374       // Get the shallow score of V1 and V2.
1375       int ShallowScoreAtThisLevel =
1376           getShallowScore(LHS, RHS, U1, U2, DL, SE, getNumLanes(), MainAltOps);
1377 
1378       // If reached MaxLevel,
1379       //  or if V1 and V2 are not instructions,
1380       //  or if they are SPLAT,
1381       //  or if they are not consecutive,
1382       //  or if profitable to vectorize loads or extractelements, early return
1383       //  the current cost.
1384       auto *I1 = dyn_cast<Instruction>(LHS);
1385       auto *I2 = dyn_cast<Instruction>(RHS);
1386       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1387           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1388           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1389             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1390             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1391            ShallowScoreAtThisLevel))
1392         return ShallowScoreAtThisLevel;
1393       assert(I1 && I2 && "Should have early exited.");
1394 
1395       // Contains the I2 operand indexes that got matched with I1 operands.
1396       SmallSet<unsigned, 4> Op2Used;
1397 
1398       // Recursion towards the operands of I1 and I2. We are trying all possible
1399       // operand pairs, and keeping track of the best score.
1400       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1401            OpIdx1 != NumOperands1; ++OpIdx1) {
1402         // Try to pair op1I with the best operand of I2.
1403         int MaxTmpScore = 0;
1404         unsigned MaxOpIdx2 = 0;
1405         bool FoundBest = false;
1406         // If I2 is commutative try all combinations.
1407         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1408         unsigned ToIdx = isCommutative(I2)
1409                              ? I2->getNumOperands()
1410                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1411         assert(FromIdx <= ToIdx && "Bad index");
1412         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1413           // Skip operands already paired with OpIdx1.
1414           if (Op2Used.count(OpIdx2))
1415             continue;
1416           // Recursively calculate the cost at each level
1417           int TmpScore =
1418               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1419                                  I1, I2, CurrLevel + 1, MaxLevel, None);
1420           // Look for the best score.
1421           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1422             MaxTmpScore = TmpScore;
1423             MaxOpIdx2 = OpIdx2;
1424             FoundBest = true;
1425           }
1426         }
1427         if (FoundBest) {
1428           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1429           Op2Used.insert(MaxOpIdx2);
1430           ShallowScoreAtThisLevel += MaxTmpScore;
1431         }
1432       }
1433       return ShallowScoreAtThisLevel;
1434     }
1435 
1436     /// Score scaling factor for fully compatible instructions but with
1437     /// different number of external uses. Allows better selection of the
1438     /// instructions with less external uses.
1439     static const int ScoreScaleFactor = 10;
1440 
1441     /// \Returns the look-ahead score, which tells us how much the sub-trees
1442     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1443     /// score. This helps break ties in an informed way when we cannot decide on
1444     /// the order of the operands by just considering the immediate
1445     /// predecessors.
1446     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1447                           int Lane, unsigned OpIdx, unsigned Idx,
1448                           bool &IsUsed) {
1449       // Keep track of the instruction stack as we recurse into the operands
1450       // during the look-ahead score exploration.
1451       int Score = getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1452                                      1, LookAheadMaxDepth, MainAltOps);
1453       if (Score) {
1454         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1455         if (Score <= -SplatScore) {
1456           // Set the minimum score for splat-like sequence to avoid setting
1457           // failed state.
1458           Score = 1;
1459         } else {
1460           Score += SplatScore;
1461           // Scale score to see the difference between different operands
1462           // and similar operands but all vectorized/not all vectorized
1463           // uses. It does not affect actual selection of the best
1464           // compatible operand in general, just allows to select the
1465           // operand with all vectorized uses.
1466           Score *= ScoreScaleFactor;
1467           Score += getExternalUseScore(Lane, OpIdx, Idx);
1468           IsUsed = true;
1469         }
1470       }
1471       return Score;
1472     }
1473 
1474     /// Best defined scores per lanes between the passes. Used to choose the
1475     /// best operand (with the highest score) between the passes.
1476     /// The key - {Operand Index, Lane}.
1477     /// The value - the best score between the passes for the lane and the
1478     /// operand.
1479     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1480         BestScoresPerLanes;
1481 
1482     // Search all operands in Ops[*][Lane] for the one that matches best
1483     // Ops[OpIdx][LastLane] and return its opreand index.
1484     // If no good match can be found, return None.
1485     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1486                                       ArrayRef<ReorderingMode> ReorderingModes,
1487                                       ArrayRef<Value *> MainAltOps) {
1488       unsigned NumOperands = getNumOperands();
1489 
1490       // The operand of the previous lane at OpIdx.
1491       Value *OpLastLane = getData(OpIdx, LastLane).V;
1492 
1493       // Our strategy mode for OpIdx.
1494       ReorderingMode RMode = ReorderingModes[OpIdx];
1495       if (RMode == ReorderingMode::Failed)
1496         return None;
1497 
1498       // The linearized opcode of the operand at OpIdx, Lane.
1499       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1500 
1501       // The best operand index and its score.
1502       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1503       // are using the score to differentiate between the two.
1504       struct BestOpData {
1505         Optional<unsigned> Idx = None;
1506         unsigned Score = 0;
1507       } BestOp;
1508       BestOp.Score =
1509           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1510               .first->second;
1511 
1512       // Track if the operand must be marked as used. If the operand is set to
1513       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1514       // want to reestimate the operands again on the following iterations).
1515       bool IsUsed =
1516           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1517       // Iterate through all unused operands and look for the best.
1518       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1519         // Get the operand at Idx and Lane.
1520         OperandData &OpData = getData(Idx, Lane);
1521         Value *Op = OpData.V;
1522         bool OpAPO = OpData.APO;
1523 
1524         // Skip already selected operands.
1525         if (OpData.IsUsed)
1526           continue;
1527 
1528         // Skip if we are trying to move the operand to a position with a
1529         // different opcode in the linearized tree form. This would break the
1530         // semantics.
1531         if (OpAPO != OpIdxAPO)
1532           continue;
1533 
1534         // Look for an operand that matches the current mode.
1535         switch (RMode) {
1536         case ReorderingMode::Load:
1537         case ReorderingMode::Constant:
1538         case ReorderingMode::Opcode: {
1539           bool LeftToRight = Lane > LastLane;
1540           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1541           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1542           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1543                                         OpIdx, Idx, IsUsed);
1544           if (Score > static_cast<int>(BestOp.Score)) {
1545             BestOp.Idx = Idx;
1546             BestOp.Score = Score;
1547             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1548           }
1549           break;
1550         }
1551         case ReorderingMode::Splat:
1552           if (Op == OpLastLane)
1553             BestOp.Idx = Idx;
1554           break;
1555         case ReorderingMode::Failed:
1556           llvm_unreachable("Not expected Failed reordering mode.");
1557         }
1558       }
1559 
1560       if (BestOp.Idx) {
1561         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1562         return BestOp.Idx;
1563       }
1564       // If we could not find a good match return None.
1565       return None;
1566     }
1567 
1568     /// Helper for reorderOperandVecs.
1569     /// \returns the lane that we should start reordering from. This is the one
1570     /// which has the least number of operands that can freely move about or
1571     /// less profitable because it already has the most optimal set of operands.
1572     unsigned getBestLaneToStartReordering() const {
1573       unsigned Min = UINT_MAX;
1574       unsigned SameOpNumber = 0;
1575       // std::pair<unsigned, unsigned> is used to implement a simple voting
1576       // algorithm and choose the lane with the least number of operands that
1577       // can freely move about or less profitable because it already has the
1578       // most optimal set of operands. The first unsigned is a counter for
1579       // voting, the second unsigned is the counter of lanes with instructions
1580       // with same/alternate opcodes and same parent basic block.
1581       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1582       // Try to be closer to the original results, if we have multiple lanes
1583       // with same cost. If 2 lanes have the same cost, use the one with the
1584       // lowest index.
1585       for (int I = getNumLanes(); I > 0; --I) {
1586         unsigned Lane = I - 1;
1587         OperandsOrderData NumFreeOpsHash =
1588             getMaxNumOperandsThatCanBeReordered(Lane);
1589         // Compare the number of operands that can move and choose the one with
1590         // the least number.
1591         if (NumFreeOpsHash.NumOfAPOs < Min) {
1592           Min = NumFreeOpsHash.NumOfAPOs;
1593           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1594           HashMap.clear();
1595           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1596         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1597                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1598           // Select the most optimal lane in terms of number of operands that
1599           // should be moved around.
1600           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1601           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1602         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1603                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1604           auto It = HashMap.find(NumFreeOpsHash.Hash);
1605           if (It == HashMap.end())
1606             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1607           else
1608             ++It->second.first;
1609         }
1610       }
1611       // Select the lane with the minimum counter.
1612       unsigned BestLane = 0;
1613       unsigned CntMin = UINT_MAX;
1614       for (const auto &Data : reverse(HashMap)) {
1615         if (Data.second.first < CntMin) {
1616           CntMin = Data.second.first;
1617           BestLane = Data.second.second;
1618         }
1619       }
1620       return BestLane;
1621     }
1622 
1623     /// Data structure that helps to reorder operands.
1624     struct OperandsOrderData {
1625       /// The best number of operands with the same APOs, which can be
1626       /// reordered.
1627       unsigned NumOfAPOs = UINT_MAX;
1628       /// Number of operands with the same/alternate instruction opcode and
1629       /// parent.
1630       unsigned NumOpsWithSameOpcodeParent = 0;
1631       /// Hash for the actual operands ordering.
1632       /// Used to count operands, actually their position id and opcode
1633       /// value. It is used in the voting mechanism to find the lane with the
1634       /// least number of operands that can freely move about or less profitable
1635       /// because it already has the most optimal set of operands. Can be
1636       /// replaced with SmallVector<unsigned> instead but hash code is faster
1637       /// and requires less memory.
1638       unsigned Hash = 0;
1639     };
1640     /// \returns the maximum number of operands that are allowed to be reordered
1641     /// for \p Lane and the number of compatible instructions(with the same
1642     /// parent/opcode). This is used as a heuristic for selecting the first lane
1643     /// to start operand reordering.
1644     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1645       unsigned CntTrue = 0;
1646       unsigned NumOperands = getNumOperands();
1647       // Operands with the same APO can be reordered. We therefore need to count
1648       // how many of them we have for each APO, like this: Cnt[APO] = x.
1649       // Since we only have two APOs, namely true and false, we can avoid using
1650       // a map. Instead we can simply count the number of operands that
1651       // correspond to one of them (in this case the 'true' APO), and calculate
1652       // the other by subtracting it from the total number of operands.
1653       // Operands with the same instruction opcode and parent are more
1654       // profitable since we don't need to move them in many cases, with a high
1655       // probability such lane already can be vectorized effectively.
1656       bool AllUndefs = true;
1657       unsigned NumOpsWithSameOpcodeParent = 0;
1658       Instruction *OpcodeI = nullptr;
1659       BasicBlock *Parent = nullptr;
1660       unsigned Hash = 0;
1661       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1662         const OperandData &OpData = getData(OpIdx, Lane);
1663         if (OpData.APO)
1664           ++CntTrue;
1665         // Use Boyer-Moore majority voting for finding the majority opcode and
1666         // the number of times it occurs.
1667         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1668           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1669               I->getParent() != Parent) {
1670             if (NumOpsWithSameOpcodeParent == 0) {
1671               NumOpsWithSameOpcodeParent = 1;
1672               OpcodeI = I;
1673               Parent = I->getParent();
1674             } else {
1675               --NumOpsWithSameOpcodeParent;
1676             }
1677           } else {
1678             ++NumOpsWithSameOpcodeParent;
1679           }
1680         }
1681         Hash = hash_combine(
1682             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1683         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1684       }
1685       if (AllUndefs)
1686         return {};
1687       OperandsOrderData Data;
1688       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1689       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1690       Data.Hash = Hash;
1691       return Data;
1692     }
1693 
1694     /// Go through the instructions in VL and append their operands.
1695     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1696       assert(!VL.empty() && "Bad VL");
1697       assert((empty() || VL.size() == getNumLanes()) &&
1698              "Expected same number of lanes");
1699       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1700       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1701       OpsVec.resize(NumOperands);
1702       unsigned NumLanes = VL.size();
1703       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1704         OpsVec[OpIdx].resize(NumLanes);
1705         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1706           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1707           // Our tree has just 3 nodes: the root and two operands.
1708           // It is therefore trivial to get the APO. We only need to check the
1709           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1710           // RHS operand. The LHS operand of both add and sub is never attached
1711           // to an inversese operation in the linearized form, therefore its APO
1712           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1713 
1714           // Since operand reordering is performed on groups of commutative
1715           // operations or alternating sequences (e.g., +, -), we can safely
1716           // tell the inverse operations by checking commutativity.
1717           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1718           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1719           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1720                                  APO, false};
1721         }
1722       }
1723     }
1724 
1725     /// \returns the number of operands.
1726     unsigned getNumOperands() const { return OpsVec.size(); }
1727 
1728     /// \returns the number of lanes.
1729     unsigned getNumLanes() const { return OpsVec[0].size(); }
1730 
1731     /// \returns the operand value at \p OpIdx and \p Lane.
1732     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1733       return getData(OpIdx, Lane).V;
1734     }
1735 
1736     /// \returns true if the data structure is empty.
1737     bool empty() const { return OpsVec.empty(); }
1738 
1739     /// Clears the data.
1740     void clear() { OpsVec.clear(); }
1741 
1742     /// \Returns true if there are enough operands identical to \p Op to fill
1743     /// the whole vector.
1744     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1745     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1746       bool OpAPO = getData(OpIdx, Lane).APO;
1747       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1748         if (Ln == Lane)
1749           continue;
1750         // This is set to true if we found a candidate for broadcast at Lane.
1751         bool FoundCandidate = false;
1752         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1753           OperandData &Data = getData(OpI, Ln);
1754           if (Data.APO != OpAPO || Data.IsUsed)
1755             continue;
1756           if (Data.V == Op) {
1757             FoundCandidate = true;
1758             Data.IsUsed = true;
1759             break;
1760           }
1761         }
1762         if (!FoundCandidate)
1763           return false;
1764       }
1765       return true;
1766     }
1767 
1768   public:
1769     /// Initialize with all the operands of the instruction vector \p RootVL.
1770     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1771                ScalarEvolution &SE, const BoUpSLP &R)
1772         : DL(DL), SE(SE), R(R) {
1773       // Append all the operands of RootVL.
1774       appendOperandsOfVL(RootVL);
1775     }
1776 
1777     /// \Returns a value vector with the operands across all lanes for the
1778     /// opearnd at \p OpIdx.
1779     ValueList getVL(unsigned OpIdx) const {
1780       ValueList OpVL(OpsVec[OpIdx].size());
1781       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1782              "Expected same num of lanes across all operands");
1783       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1784         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1785       return OpVL;
1786     }
1787 
1788     // Performs operand reordering for 2 or more operands.
1789     // The original operands are in OrigOps[OpIdx][Lane].
1790     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1791     void reorder() {
1792       unsigned NumOperands = getNumOperands();
1793       unsigned NumLanes = getNumLanes();
1794       // Each operand has its own mode. We are using this mode to help us select
1795       // the instructions for each lane, so that they match best with the ones
1796       // we have selected so far.
1797       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1798 
1799       // This is a greedy single-pass algorithm. We are going over each lane
1800       // once and deciding on the best order right away with no back-tracking.
1801       // However, in order to increase its effectiveness, we start with the lane
1802       // that has operands that can move the least. For example, given the
1803       // following lanes:
1804       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1805       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1806       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1807       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1808       // we will start at Lane 1, since the operands of the subtraction cannot
1809       // be reordered. Then we will visit the rest of the lanes in a circular
1810       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1811 
1812       // Find the first lane that we will start our search from.
1813       unsigned FirstLane = getBestLaneToStartReordering();
1814 
1815       // Initialize the modes.
1816       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1817         Value *OpLane0 = getValue(OpIdx, FirstLane);
1818         // Keep track if we have instructions with all the same opcode on one
1819         // side.
1820         if (isa<LoadInst>(OpLane0))
1821           ReorderingModes[OpIdx] = ReorderingMode::Load;
1822         else if (isa<Instruction>(OpLane0)) {
1823           // Check if OpLane0 should be broadcast.
1824           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1825             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1826           else
1827             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1828         }
1829         else if (isa<Constant>(OpLane0))
1830           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1831         else if (isa<Argument>(OpLane0))
1832           // Our best hope is a Splat. It may save some cost in some cases.
1833           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1834         else
1835           // NOTE: This should be unreachable.
1836           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1837       }
1838 
1839       // Check that we don't have same operands. No need to reorder if operands
1840       // are just perfect diamond or shuffled diamond match. Do not do it only
1841       // for possible broadcasts or non-power of 2 number of scalars (just for
1842       // now).
1843       auto &&SkipReordering = [this]() {
1844         SmallPtrSet<Value *, 4> UniqueValues;
1845         ArrayRef<OperandData> Op0 = OpsVec.front();
1846         for (const OperandData &Data : Op0)
1847           UniqueValues.insert(Data.V);
1848         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1849           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1850                 return !UniqueValues.contains(Data.V);
1851               }))
1852             return false;
1853         }
1854         // TODO: Check if we can remove a check for non-power-2 number of
1855         // scalars after full support of non-power-2 vectorization.
1856         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1857       };
1858 
1859       // If the initial strategy fails for any of the operand indexes, then we
1860       // perform reordering again in a second pass. This helps avoid assigning
1861       // high priority to the failed strategy, and should improve reordering for
1862       // the non-failed operand indexes.
1863       for (int Pass = 0; Pass != 2; ++Pass) {
1864         // Check if no need to reorder operands since they're are perfect or
1865         // shuffled diamond match.
1866         // Need to to do it to avoid extra external use cost counting for
1867         // shuffled matches, which may cause regressions.
1868         if (SkipReordering())
1869           break;
1870         // Skip the second pass if the first pass did not fail.
1871         bool StrategyFailed = false;
1872         // Mark all operand data as free to use.
1873         clearUsed();
1874         // We keep the original operand order for the FirstLane, so reorder the
1875         // rest of the lanes. We are visiting the nodes in a circular fashion,
1876         // using FirstLane as the center point and increasing the radius
1877         // distance.
1878         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1879         for (unsigned I = 0; I < NumOperands; ++I)
1880           MainAltOps[I].push_back(getData(I, FirstLane).V);
1881 
1882         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1883           // Visit the lane on the right and then the lane on the left.
1884           for (int Direction : {+1, -1}) {
1885             int Lane = FirstLane + Direction * Distance;
1886             if (Lane < 0 || Lane >= (int)NumLanes)
1887               continue;
1888             int LastLane = Lane - Direction;
1889             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1890                    "Out of bounds");
1891             // Look for a good match for each operand.
1892             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1893               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1894               Optional<unsigned> BestIdx = getBestOperand(
1895                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1896               // By not selecting a value, we allow the operands that follow to
1897               // select a better matching value. We will get a non-null value in
1898               // the next run of getBestOperand().
1899               if (BestIdx) {
1900                 // Swap the current operand with the one returned by
1901                 // getBestOperand().
1902                 swap(OpIdx, BestIdx.getValue(), Lane);
1903               } else {
1904                 // We failed to find a best operand, set mode to 'Failed'.
1905                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1906                 // Enable the second pass.
1907                 StrategyFailed = true;
1908               }
1909               // Try to get the alternate opcode and follow it during analysis.
1910               if (MainAltOps[OpIdx].size() != 2) {
1911                 OperandData &AltOp = getData(OpIdx, Lane);
1912                 InstructionsState OpS =
1913                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1914                 if (OpS.getOpcode() && OpS.isAltShuffle())
1915                   MainAltOps[OpIdx].push_back(AltOp.V);
1916               }
1917             }
1918           }
1919         }
1920         // Skip second pass if the strategy did not fail.
1921         if (!StrategyFailed)
1922           break;
1923       }
1924     }
1925 
1926 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1927     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1928       switch (RMode) {
1929       case ReorderingMode::Load:
1930         return "Load";
1931       case ReorderingMode::Opcode:
1932         return "Opcode";
1933       case ReorderingMode::Constant:
1934         return "Constant";
1935       case ReorderingMode::Splat:
1936         return "Splat";
1937       case ReorderingMode::Failed:
1938         return "Failed";
1939       }
1940       llvm_unreachable("Unimplemented Reordering Type");
1941     }
1942 
1943     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1944                                                    raw_ostream &OS) {
1945       return OS << getModeStr(RMode);
1946     }
1947 
1948     /// Debug print.
1949     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1950       printMode(RMode, dbgs());
1951     }
1952 
1953     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1954       return printMode(RMode, OS);
1955     }
1956 
1957     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1958       const unsigned Indent = 2;
1959       unsigned Cnt = 0;
1960       for (const OperandDataVec &OpDataVec : OpsVec) {
1961         OS << "Operand " << Cnt++ << "\n";
1962         for (const OperandData &OpData : OpDataVec) {
1963           OS.indent(Indent) << "{";
1964           if (Value *V = OpData.V)
1965             OS << *V;
1966           else
1967             OS << "null";
1968           OS << ", APO:" << OpData.APO << "}\n";
1969         }
1970         OS << "\n";
1971       }
1972       return OS;
1973     }
1974 
1975     /// Debug print.
1976     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1977 #endif
1978   };
1979 
1980   /// Checks if the instruction is marked for deletion.
1981   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1982 
1983   /// Removes an instruction from its block and eventually deletes it.
1984   /// It's like Instruction::eraseFromParent() except that the actual deletion
1985   /// is delayed until BoUpSLP is destructed.
1986   void eraseInstruction(Instruction *I) {
1987     DeletedInstructions.insert(I);
1988   }
1989 
1990   ~BoUpSLP();
1991 
1992 private:
1993   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1994   /// reordering (i.e. the operands can be reordered because they have only one
1995   /// user and reordarable).
1996   /// \param ReorderableGathers List of all gather nodes that require reordering
1997   /// (e.g., gather of extractlements or partially vectorizable loads).
1998   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1999   /// reordering, subset of \p NonVectorized.
2000   bool
2001   canReorderOperands(TreeEntry *UserTE,
2002                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2003                      ArrayRef<TreeEntry *> ReorderableGathers,
2004                      SmallVectorImpl<TreeEntry *> &GatherOps);
2005 
2006   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2007   /// if any. If it is not vectorized (gather node), returns nullptr.
2008   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2009     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2010     TreeEntry *TE = nullptr;
2011     const auto *It = find_if(VL, [this, &TE](Value *V) {
2012       TE = getTreeEntry(V);
2013       return TE;
2014     });
2015     if (It != VL.end() && TE->isSame(VL))
2016       return TE;
2017     return nullptr;
2018   }
2019 
2020   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2021   /// if any. If it is not vectorized (gather node), returns nullptr.
2022   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2023                                         unsigned OpIdx) const {
2024     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2025         const_cast<TreeEntry *>(UserTE), OpIdx);
2026   }
2027 
2028   /// Checks if all users of \p I are the part of the vectorization tree.
2029   bool areAllUsersVectorized(Instruction *I,
2030                              ArrayRef<Value *> VectorizedVals) const;
2031 
2032   /// \returns the cost of the vectorizable entry.
2033   InstructionCost getEntryCost(const TreeEntry *E,
2034                                ArrayRef<Value *> VectorizedVals);
2035 
2036   /// This is the recursive part of buildTree.
2037   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2038                      const EdgeInfo &EI);
2039 
2040   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2041   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2042   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2043   /// returns false, setting \p CurrentOrder to either an empty vector or a
2044   /// non-identity permutation that allows to reuse extract instructions.
2045   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2046                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2047 
2048   /// Vectorize a single entry in the tree.
2049   Value *vectorizeTree(TreeEntry *E);
2050 
2051   /// Vectorize a single entry in the tree, starting in \p VL.
2052   Value *vectorizeTree(ArrayRef<Value *> VL);
2053 
2054   /// Create a new vector from a list of scalar values.  Produces a sequence
2055   /// which exploits values reused across lanes, and arranges the inserts
2056   /// for ease of later optimization.
2057   Value *createBuildVector(ArrayRef<Value *> VL);
2058 
2059   /// \returns the scalarization cost for this type. Scalarization in this
2060   /// context means the creation of vectors from a group of scalars. If \p
2061   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2062   /// vector elements.
2063   InstructionCost getGatherCost(FixedVectorType *Ty,
2064                                 const APInt &ShuffledIndices,
2065                                 bool NeedToShuffle) const;
2066 
2067   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2068   /// tree entries.
2069   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2070   /// previous tree entries. \p Mask is filled with the shuffle mask.
2071   Optional<TargetTransformInfo::ShuffleKind>
2072   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2073                         SmallVectorImpl<const TreeEntry *> &Entries);
2074 
2075   /// \returns the scalarization cost for this list of values. Assuming that
2076   /// this subtree gets vectorized, we may need to extract the values from the
2077   /// roots. This method calculates the cost of extracting the values.
2078   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2079 
2080   /// Set the Builder insert point to one after the last instruction in
2081   /// the bundle
2082   void setInsertPointAfterBundle(const TreeEntry *E);
2083 
2084   /// \returns a vector from a collection of scalars in \p VL.
2085   Value *gather(ArrayRef<Value *> VL);
2086 
2087   /// \returns whether the VectorizableTree is fully vectorizable and will
2088   /// be beneficial even the tree height is tiny.
2089   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2090 
2091   /// Reorder commutative or alt operands to get better probability of
2092   /// generating vectorized code.
2093   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2094                                              SmallVectorImpl<Value *> &Left,
2095                                              SmallVectorImpl<Value *> &Right,
2096                                              const DataLayout &DL,
2097                                              ScalarEvolution &SE,
2098                                              const BoUpSLP &R);
2099   struct TreeEntry {
2100     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2101     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2102 
2103     /// \returns true if the scalars in VL are equal to this entry.
2104     bool isSame(ArrayRef<Value *> VL) const {
2105       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2106         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2107           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2108         return VL.size() == Mask.size() &&
2109                std::equal(VL.begin(), VL.end(), Mask.begin(),
2110                           [Scalars](Value *V, int Idx) {
2111                             return (isa<UndefValue>(V) &&
2112                                     Idx == UndefMaskElem) ||
2113                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2114                           });
2115       };
2116       if (!ReorderIndices.empty()) {
2117         // TODO: implement matching if the nodes are just reordered, still can
2118         // treat the vector as the same if the list of scalars matches VL
2119         // directly, without reordering.
2120         SmallVector<int> Mask;
2121         inversePermutation(ReorderIndices, Mask);
2122         if (VL.size() == Scalars.size())
2123           return IsSame(Scalars, Mask);
2124         if (VL.size() == ReuseShuffleIndices.size()) {
2125           ::addMask(Mask, ReuseShuffleIndices);
2126           return IsSame(Scalars, Mask);
2127         }
2128         return false;
2129       }
2130       return IsSame(Scalars, ReuseShuffleIndices);
2131     }
2132 
2133     /// \returns true if current entry has same operands as \p TE.
2134     bool hasEqualOperands(const TreeEntry &TE) const {
2135       if (TE.getNumOperands() != getNumOperands())
2136         return false;
2137       SmallBitVector Used(getNumOperands());
2138       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2139         unsigned PrevCount = Used.count();
2140         for (unsigned K = 0; K < E; ++K) {
2141           if (Used.test(K))
2142             continue;
2143           if (getOperand(K) == TE.getOperand(I)) {
2144             Used.set(K);
2145             break;
2146           }
2147         }
2148         // Check if we actually found the matching operand.
2149         if (PrevCount == Used.count())
2150           return false;
2151       }
2152       return true;
2153     }
2154 
2155     /// \return Final vectorization factor for the node. Defined by the total
2156     /// number of vectorized scalars, including those, used several times in the
2157     /// entry and counted in the \a ReuseShuffleIndices, if any.
2158     unsigned getVectorFactor() const {
2159       if (!ReuseShuffleIndices.empty())
2160         return ReuseShuffleIndices.size();
2161       return Scalars.size();
2162     };
2163 
2164     /// A vector of scalars.
2165     ValueList Scalars;
2166 
2167     /// The Scalars are vectorized into this value. It is initialized to Null.
2168     Value *VectorizedValue = nullptr;
2169 
2170     /// Do we need to gather this sequence or vectorize it
2171     /// (either with vector instruction or with scatter/gather
2172     /// intrinsics for store/load)?
2173     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2174     EntryState State;
2175 
2176     /// Does this sequence require some shuffling?
2177     SmallVector<int, 4> ReuseShuffleIndices;
2178 
2179     /// Does this entry require reordering?
2180     SmallVector<unsigned, 4> ReorderIndices;
2181 
2182     /// Points back to the VectorizableTree.
2183     ///
2184     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2185     /// to be a pointer and needs to be able to initialize the child iterator.
2186     /// Thus we need a reference back to the container to translate the indices
2187     /// to entries.
2188     VecTreeTy &Container;
2189 
2190     /// The TreeEntry index containing the user of this entry.  We can actually
2191     /// have multiple users so the data structure is not truly a tree.
2192     SmallVector<EdgeInfo, 1> UserTreeIndices;
2193 
2194     /// The index of this treeEntry in VectorizableTree.
2195     int Idx = -1;
2196 
2197   private:
2198     /// The operands of each instruction in each lane Operands[op_index][lane].
2199     /// Note: This helps avoid the replication of the code that performs the
2200     /// reordering of operands during buildTree_rec() and vectorizeTree().
2201     SmallVector<ValueList, 2> Operands;
2202 
2203     /// The main/alternate instruction.
2204     Instruction *MainOp = nullptr;
2205     Instruction *AltOp = nullptr;
2206 
2207   public:
2208     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2209     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2210       if (Operands.size() < OpIdx + 1)
2211         Operands.resize(OpIdx + 1);
2212       assert(Operands[OpIdx].empty() && "Already resized?");
2213       assert(OpVL.size() <= Scalars.size() &&
2214              "Number of operands is greater than the number of scalars.");
2215       Operands[OpIdx].resize(OpVL.size());
2216       copy(OpVL, Operands[OpIdx].begin());
2217     }
2218 
2219     /// Set the operands of this bundle in their original order.
2220     void setOperandsInOrder() {
2221       assert(Operands.empty() && "Already initialized?");
2222       auto *I0 = cast<Instruction>(Scalars[0]);
2223       Operands.resize(I0->getNumOperands());
2224       unsigned NumLanes = Scalars.size();
2225       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2226            OpIdx != NumOperands; ++OpIdx) {
2227         Operands[OpIdx].resize(NumLanes);
2228         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2229           auto *I = cast<Instruction>(Scalars[Lane]);
2230           assert(I->getNumOperands() == NumOperands &&
2231                  "Expected same number of operands");
2232           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2233         }
2234       }
2235     }
2236 
2237     /// Reorders operands of the node to the given mask \p Mask.
2238     void reorderOperands(ArrayRef<int> Mask) {
2239       for (ValueList &Operand : Operands)
2240         reorderScalars(Operand, Mask);
2241     }
2242 
2243     /// \returns the \p OpIdx operand of this TreeEntry.
2244     ValueList &getOperand(unsigned OpIdx) {
2245       assert(OpIdx < Operands.size() && "Off bounds");
2246       return Operands[OpIdx];
2247     }
2248 
2249     /// \returns the \p OpIdx operand of this TreeEntry.
2250     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2251       assert(OpIdx < Operands.size() && "Off bounds");
2252       return Operands[OpIdx];
2253     }
2254 
2255     /// \returns the number of operands.
2256     unsigned getNumOperands() const { return Operands.size(); }
2257 
2258     /// \return the single \p OpIdx operand.
2259     Value *getSingleOperand(unsigned OpIdx) const {
2260       assert(OpIdx < Operands.size() && "Off bounds");
2261       assert(!Operands[OpIdx].empty() && "No operand available");
2262       return Operands[OpIdx][0];
2263     }
2264 
2265     /// Some of the instructions in the list have alternate opcodes.
2266     bool isAltShuffle() const { return MainOp != AltOp; }
2267 
2268     bool isOpcodeOrAlt(Instruction *I) const {
2269       unsigned CheckedOpcode = I->getOpcode();
2270       return (getOpcode() == CheckedOpcode ||
2271               getAltOpcode() == CheckedOpcode);
2272     }
2273 
2274     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2275     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2276     /// \p OpValue.
2277     Value *isOneOf(Value *Op) const {
2278       auto *I = dyn_cast<Instruction>(Op);
2279       if (I && isOpcodeOrAlt(I))
2280         return Op;
2281       return MainOp;
2282     }
2283 
2284     void setOperations(const InstructionsState &S) {
2285       MainOp = S.MainOp;
2286       AltOp = S.AltOp;
2287     }
2288 
2289     Instruction *getMainOp() const {
2290       return MainOp;
2291     }
2292 
2293     Instruction *getAltOp() const {
2294       return AltOp;
2295     }
2296 
2297     /// The main/alternate opcodes for the list of instructions.
2298     unsigned getOpcode() const {
2299       return MainOp ? MainOp->getOpcode() : 0;
2300     }
2301 
2302     unsigned getAltOpcode() const {
2303       return AltOp ? AltOp->getOpcode() : 0;
2304     }
2305 
2306     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2307     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2308     int findLaneForValue(Value *V) const {
2309       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2310       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2311       if (!ReorderIndices.empty())
2312         FoundLane = ReorderIndices[FoundLane];
2313       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2314       if (!ReuseShuffleIndices.empty()) {
2315         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2316                                   find(ReuseShuffleIndices, FoundLane));
2317       }
2318       return FoundLane;
2319     }
2320 
2321 #ifndef NDEBUG
2322     /// Debug printer.
2323     LLVM_DUMP_METHOD void dump() const {
2324       dbgs() << Idx << ".\n";
2325       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2326         dbgs() << "Operand " << OpI << ":\n";
2327         for (const Value *V : Operands[OpI])
2328           dbgs().indent(2) << *V << "\n";
2329       }
2330       dbgs() << "Scalars: \n";
2331       for (Value *V : Scalars)
2332         dbgs().indent(2) << *V << "\n";
2333       dbgs() << "State: ";
2334       switch (State) {
2335       case Vectorize:
2336         dbgs() << "Vectorize\n";
2337         break;
2338       case ScatterVectorize:
2339         dbgs() << "ScatterVectorize\n";
2340         break;
2341       case NeedToGather:
2342         dbgs() << "NeedToGather\n";
2343         break;
2344       }
2345       dbgs() << "MainOp: ";
2346       if (MainOp)
2347         dbgs() << *MainOp << "\n";
2348       else
2349         dbgs() << "NULL\n";
2350       dbgs() << "AltOp: ";
2351       if (AltOp)
2352         dbgs() << *AltOp << "\n";
2353       else
2354         dbgs() << "NULL\n";
2355       dbgs() << "VectorizedValue: ";
2356       if (VectorizedValue)
2357         dbgs() << *VectorizedValue << "\n";
2358       else
2359         dbgs() << "NULL\n";
2360       dbgs() << "ReuseShuffleIndices: ";
2361       if (ReuseShuffleIndices.empty())
2362         dbgs() << "Empty";
2363       else
2364         for (int ReuseIdx : ReuseShuffleIndices)
2365           dbgs() << ReuseIdx << ", ";
2366       dbgs() << "\n";
2367       dbgs() << "ReorderIndices: ";
2368       for (unsigned ReorderIdx : ReorderIndices)
2369         dbgs() << ReorderIdx << ", ";
2370       dbgs() << "\n";
2371       dbgs() << "UserTreeIndices: ";
2372       for (const auto &EInfo : UserTreeIndices)
2373         dbgs() << EInfo << ", ";
2374       dbgs() << "\n";
2375     }
2376 #endif
2377   };
2378 
2379 #ifndef NDEBUG
2380   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2381                      InstructionCost VecCost,
2382                      InstructionCost ScalarCost) const {
2383     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2384     dbgs() << "SLP: Costs:\n";
2385     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2386     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2387     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2388     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2389                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2390   }
2391 #endif
2392 
2393   /// Create a new VectorizableTree entry.
2394   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2395                           const InstructionsState &S,
2396                           const EdgeInfo &UserTreeIdx,
2397                           ArrayRef<int> ReuseShuffleIndices = None,
2398                           ArrayRef<unsigned> ReorderIndices = None) {
2399     TreeEntry::EntryState EntryState =
2400         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2401     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2402                         ReuseShuffleIndices, ReorderIndices);
2403   }
2404 
2405   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2406                           TreeEntry::EntryState EntryState,
2407                           Optional<ScheduleData *> Bundle,
2408                           const InstructionsState &S,
2409                           const EdgeInfo &UserTreeIdx,
2410                           ArrayRef<int> ReuseShuffleIndices = None,
2411                           ArrayRef<unsigned> ReorderIndices = None) {
2412     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2413             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2414            "Need to vectorize gather entry?");
2415     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2416     TreeEntry *Last = VectorizableTree.back().get();
2417     Last->Idx = VectorizableTree.size() - 1;
2418     Last->State = EntryState;
2419     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2420                                      ReuseShuffleIndices.end());
2421     if (ReorderIndices.empty()) {
2422       Last->Scalars.assign(VL.begin(), VL.end());
2423       Last->setOperations(S);
2424     } else {
2425       // Reorder scalars and build final mask.
2426       Last->Scalars.assign(VL.size(), nullptr);
2427       transform(ReorderIndices, Last->Scalars.begin(),
2428                 [VL](unsigned Idx) -> Value * {
2429                   if (Idx >= VL.size())
2430                     return UndefValue::get(VL.front()->getType());
2431                   return VL[Idx];
2432                 });
2433       InstructionsState S = getSameOpcode(Last->Scalars);
2434       Last->setOperations(S);
2435       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2436     }
2437     if (Last->State != TreeEntry::NeedToGather) {
2438       for (Value *V : VL) {
2439         assert(!getTreeEntry(V) && "Scalar already in tree!");
2440         ScalarToTreeEntry[V] = Last;
2441       }
2442       // Update the scheduler bundle to point to this TreeEntry.
2443       ScheduleData *BundleMember = Bundle.getValue();
2444       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2445               isVectorLikeInstWithConstOps(S.MainOp) ||
2446               doesNotNeedToSchedule(VL)) &&
2447              "Bundle and VL out of sync");
2448       if (BundleMember) {
2449         for (Value *V : VL) {
2450           if (doesNotNeedToBeScheduled(V))
2451             continue;
2452           assert(BundleMember && "Unexpected end of bundle.");
2453           BundleMember->TE = Last;
2454           BundleMember = BundleMember->NextInBundle;
2455         }
2456       }
2457       assert(!BundleMember && "Bundle and VL out of sync");
2458     } else {
2459       MustGather.insert(VL.begin(), VL.end());
2460     }
2461 
2462     if (UserTreeIdx.UserTE)
2463       Last->UserTreeIndices.push_back(UserTreeIdx);
2464 
2465     return Last;
2466   }
2467 
2468   /// -- Vectorization State --
2469   /// Holds all of the tree entries.
2470   TreeEntry::VecTreeTy VectorizableTree;
2471 
2472 #ifndef NDEBUG
2473   /// Debug printer.
2474   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2475     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2476       VectorizableTree[Id]->dump();
2477       dbgs() << "\n";
2478     }
2479   }
2480 #endif
2481 
2482   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2483 
2484   const TreeEntry *getTreeEntry(Value *V) const {
2485     return ScalarToTreeEntry.lookup(V);
2486   }
2487 
2488   /// Maps a specific scalar to its tree entry.
2489   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2490 
2491   /// Maps a value to the proposed vectorizable size.
2492   SmallDenseMap<Value *, unsigned> InstrElementSize;
2493 
2494   /// A list of scalars that we found that we need to keep as scalars.
2495   ValueSet MustGather;
2496 
2497   /// This POD struct describes one external user in the vectorized tree.
2498   struct ExternalUser {
2499     ExternalUser(Value *S, llvm::User *U, int L)
2500         : Scalar(S), User(U), Lane(L) {}
2501 
2502     // Which scalar in our function.
2503     Value *Scalar;
2504 
2505     // Which user that uses the scalar.
2506     llvm::User *User;
2507 
2508     // Which lane does the scalar belong to.
2509     int Lane;
2510   };
2511   using UserList = SmallVector<ExternalUser, 16>;
2512 
2513   /// Checks if two instructions may access the same memory.
2514   ///
2515   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2516   /// is invariant in the calling loop.
2517   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2518                  Instruction *Inst2) {
2519     // First check if the result is already in the cache.
2520     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2521     Optional<bool> &result = AliasCache[key];
2522     if (result.hasValue()) {
2523       return result.getValue();
2524     }
2525     bool aliased = true;
2526     if (Loc1.Ptr && isSimple(Inst1))
2527       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2528     // Store the result in the cache.
2529     result = aliased;
2530     return aliased;
2531   }
2532 
2533   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2534 
2535   /// Cache for alias results.
2536   /// TODO: consider moving this to the AliasAnalysis itself.
2537   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2538 
2539   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2540   // globally through SLP because we don't perform any action which
2541   // invalidates capture results.
2542   BatchAAResults BatchAA;
2543 
2544   /// Temporary store for deleted instructions. Instructions will be deleted
2545   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2546   /// ensure that there are no incorrect collisions in the AliasCache, which
2547   /// can happen if a new instruction is allocated at the same address as a
2548   /// previously deleted instruction.
2549   DenseSet<Instruction *> DeletedInstructions;
2550 
2551   /// A list of values that need to extracted out of the tree.
2552   /// This list holds pairs of (Internal Scalar : External User). External User
2553   /// can be nullptr, it means that this Internal Scalar will be used later,
2554   /// after vectorization.
2555   UserList ExternalUses;
2556 
2557   /// Values used only by @llvm.assume calls.
2558   SmallPtrSet<const Value *, 32> EphValues;
2559 
2560   /// Holds all of the instructions that we gathered.
2561   SetVector<Instruction *> GatherShuffleSeq;
2562 
2563   /// A list of blocks that we are going to CSE.
2564   SetVector<BasicBlock *> CSEBlocks;
2565 
2566   /// Contains all scheduling relevant data for an instruction.
2567   /// A ScheduleData either represents a single instruction or a member of an
2568   /// instruction bundle (= a group of instructions which is combined into a
2569   /// vector instruction).
2570   struct ScheduleData {
2571     // The initial value for the dependency counters. It means that the
2572     // dependencies are not calculated yet.
2573     enum { InvalidDeps = -1 };
2574 
2575     ScheduleData() = default;
2576 
2577     void init(int BlockSchedulingRegionID, Value *OpVal) {
2578       FirstInBundle = this;
2579       NextInBundle = nullptr;
2580       NextLoadStore = nullptr;
2581       IsScheduled = false;
2582       SchedulingRegionID = BlockSchedulingRegionID;
2583       clearDependencies();
2584       OpValue = OpVal;
2585       TE = nullptr;
2586     }
2587 
2588     /// Verify basic self consistency properties
2589     void verify() {
2590       if (hasValidDependencies()) {
2591         assert(UnscheduledDeps <= Dependencies && "invariant");
2592       } else {
2593         assert(UnscheduledDeps == Dependencies && "invariant");
2594       }
2595 
2596       if (IsScheduled) {
2597         assert(isSchedulingEntity() &&
2598                 "unexpected scheduled state");
2599         for (const ScheduleData *BundleMember = this; BundleMember;
2600              BundleMember = BundleMember->NextInBundle) {
2601           assert(BundleMember->hasValidDependencies() &&
2602                  BundleMember->UnscheduledDeps == 0 &&
2603                  "unexpected scheduled state");
2604           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2605                  "only bundle is marked scheduled");
2606         }
2607       }
2608 
2609       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2610              "all bundle members must be in same basic block");
2611     }
2612 
2613     /// Returns true if the dependency information has been calculated.
2614     /// Note that depenendency validity can vary between instructions within
2615     /// a single bundle.
2616     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2617 
2618     /// Returns true for single instructions and for bundle representatives
2619     /// (= the head of a bundle).
2620     bool isSchedulingEntity() const { return FirstInBundle == this; }
2621 
2622     /// Returns true if it represents an instruction bundle and not only a
2623     /// single instruction.
2624     bool isPartOfBundle() const {
2625       return NextInBundle != nullptr || FirstInBundle != this || TE;
2626     }
2627 
2628     /// Returns true if it is ready for scheduling, i.e. it has no more
2629     /// unscheduled depending instructions/bundles.
2630     bool isReady() const {
2631       assert(isSchedulingEntity() &&
2632              "can't consider non-scheduling entity for ready list");
2633       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2634     }
2635 
2636     /// Modifies the number of unscheduled dependencies for this instruction,
2637     /// and returns the number of remaining dependencies for the containing
2638     /// bundle.
2639     int incrementUnscheduledDeps(int Incr) {
2640       assert(hasValidDependencies() &&
2641              "increment of unscheduled deps would be meaningless");
2642       UnscheduledDeps += Incr;
2643       return FirstInBundle->unscheduledDepsInBundle();
2644     }
2645 
2646     /// Sets the number of unscheduled dependencies to the number of
2647     /// dependencies.
2648     void resetUnscheduledDeps() {
2649       UnscheduledDeps = Dependencies;
2650     }
2651 
2652     /// Clears all dependency information.
2653     void clearDependencies() {
2654       Dependencies = InvalidDeps;
2655       resetUnscheduledDeps();
2656       MemoryDependencies.clear();
2657       ControlDependencies.clear();
2658     }
2659 
2660     int unscheduledDepsInBundle() const {
2661       assert(isSchedulingEntity() && "only meaningful on the bundle");
2662       int Sum = 0;
2663       for (const ScheduleData *BundleMember = this; BundleMember;
2664            BundleMember = BundleMember->NextInBundle) {
2665         if (BundleMember->UnscheduledDeps == InvalidDeps)
2666           return InvalidDeps;
2667         Sum += BundleMember->UnscheduledDeps;
2668       }
2669       return Sum;
2670     }
2671 
2672     void dump(raw_ostream &os) const {
2673       if (!isSchedulingEntity()) {
2674         os << "/ " << *Inst;
2675       } else if (NextInBundle) {
2676         os << '[' << *Inst;
2677         ScheduleData *SD = NextInBundle;
2678         while (SD) {
2679           os << ';' << *SD->Inst;
2680           SD = SD->NextInBundle;
2681         }
2682         os << ']';
2683       } else {
2684         os << *Inst;
2685       }
2686     }
2687 
2688     Instruction *Inst = nullptr;
2689 
2690     /// Opcode of the current instruction in the schedule data.
2691     Value *OpValue = nullptr;
2692 
2693     /// The TreeEntry that this instruction corresponds to.
2694     TreeEntry *TE = nullptr;
2695 
2696     /// Points to the head in an instruction bundle (and always to this for
2697     /// single instructions).
2698     ScheduleData *FirstInBundle = nullptr;
2699 
2700     /// Single linked list of all instructions in a bundle. Null if it is a
2701     /// single instruction.
2702     ScheduleData *NextInBundle = nullptr;
2703 
2704     /// Single linked list of all memory instructions (e.g. load, store, call)
2705     /// in the block - until the end of the scheduling region.
2706     ScheduleData *NextLoadStore = nullptr;
2707 
2708     /// The dependent memory instructions.
2709     /// This list is derived on demand in calculateDependencies().
2710     SmallVector<ScheduleData *, 4> MemoryDependencies;
2711 
2712     /// List of instructions which this instruction could be control dependent
2713     /// on.  Allowing such nodes to be scheduled below this one could introduce
2714     /// a runtime fault which didn't exist in the original program.
2715     /// ex: this is a load or udiv following a readonly call which inf loops
2716     SmallVector<ScheduleData *, 4> ControlDependencies;
2717 
2718     /// This ScheduleData is in the current scheduling region if this matches
2719     /// the current SchedulingRegionID of BlockScheduling.
2720     int SchedulingRegionID = 0;
2721 
2722     /// Used for getting a "good" final ordering of instructions.
2723     int SchedulingPriority = 0;
2724 
2725     /// The number of dependencies. Constitutes of the number of users of the
2726     /// instruction plus the number of dependent memory instructions (if any).
2727     /// This value is calculated on demand.
2728     /// If InvalidDeps, the number of dependencies is not calculated yet.
2729     int Dependencies = InvalidDeps;
2730 
2731     /// The number of dependencies minus the number of dependencies of scheduled
2732     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2733     /// for scheduling.
2734     /// Note that this is negative as long as Dependencies is not calculated.
2735     int UnscheduledDeps = InvalidDeps;
2736 
2737     /// True if this instruction is scheduled (or considered as scheduled in the
2738     /// dry-run).
2739     bool IsScheduled = false;
2740   };
2741 
2742 #ifndef NDEBUG
2743   friend inline raw_ostream &operator<<(raw_ostream &os,
2744                                         const BoUpSLP::ScheduleData &SD) {
2745     SD.dump(os);
2746     return os;
2747   }
2748 #endif
2749 
2750   friend struct GraphTraits<BoUpSLP *>;
2751   friend struct DOTGraphTraits<BoUpSLP *>;
2752 
2753   /// Contains all scheduling data for a basic block.
2754   /// It does not schedules instructions, which are not memory read/write
2755   /// instructions and their operands are either constants, or arguments, or
2756   /// phis, or instructions from others blocks, or their users are phis or from
2757   /// the other blocks. The resulting vector instructions can be placed at the
2758   /// beginning of the basic block without scheduling (if operands does not need
2759   /// to be scheduled) or at the end of the block (if users are outside of the
2760   /// block). It allows to save some compile time and memory used by the
2761   /// compiler.
2762   /// ScheduleData is assigned for each instruction in between the boundaries of
2763   /// the tree entry, even for those, which are not part of the graph. It is
2764   /// required to correctly follow the dependencies between the instructions and
2765   /// their correct scheduling. The ScheduleData is not allocated for the
2766   /// instructions, which do not require scheduling, like phis, nodes with
2767   /// extractelements/insertelements only or nodes with instructions, with
2768   /// uses/operands outside of the block.
2769   struct BlockScheduling {
2770     BlockScheduling(BasicBlock *BB)
2771         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2772 
2773     void clear() {
2774       ReadyInsts.clear();
2775       ScheduleStart = nullptr;
2776       ScheduleEnd = nullptr;
2777       FirstLoadStoreInRegion = nullptr;
2778       LastLoadStoreInRegion = nullptr;
2779       RegionHasStackSave = false;
2780 
2781       // Reduce the maximum schedule region size by the size of the
2782       // previous scheduling run.
2783       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2784       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2785         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2786       ScheduleRegionSize = 0;
2787 
2788       // Make a new scheduling region, i.e. all existing ScheduleData is not
2789       // in the new region yet.
2790       ++SchedulingRegionID;
2791     }
2792 
2793     ScheduleData *getScheduleData(Instruction *I) {
2794       if (BB != I->getParent())
2795         // Avoid lookup if can't possibly be in map.
2796         return nullptr;
2797       ScheduleData *SD = ScheduleDataMap.lookup(I);
2798       if (SD && isInSchedulingRegion(SD))
2799         return SD;
2800       return nullptr;
2801     }
2802 
2803     ScheduleData *getScheduleData(Value *V) {
2804       if (auto *I = dyn_cast<Instruction>(V))
2805         return getScheduleData(I);
2806       return nullptr;
2807     }
2808 
2809     ScheduleData *getScheduleData(Value *V, Value *Key) {
2810       if (V == Key)
2811         return getScheduleData(V);
2812       auto I = ExtraScheduleDataMap.find(V);
2813       if (I != ExtraScheduleDataMap.end()) {
2814         ScheduleData *SD = I->second.lookup(Key);
2815         if (SD && isInSchedulingRegion(SD))
2816           return SD;
2817       }
2818       return nullptr;
2819     }
2820 
2821     bool isInSchedulingRegion(ScheduleData *SD) const {
2822       return SD->SchedulingRegionID == SchedulingRegionID;
2823     }
2824 
2825     /// Marks an instruction as scheduled and puts all dependent ready
2826     /// instructions into the ready-list.
2827     template <typename ReadyListType>
2828     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2829       SD->IsScheduled = true;
2830       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2831 
2832       for (ScheduleData *BundleMember = SD; BundleMember;
2833            BundleMember = BundleMember->NextInBundle) {
2834         if (BundleMember->Inst != BundleMember->OpValue)
2835           continue;
2836 
2837         // Handle the def-use chain dependencies.
2838 
2839         // Decrement the unscheduled counter and insert to ready list if ready.
2840         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2841           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2842             if (OpDef && OpDef->hasValidDependencies() &&
2843                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2844               // There are no more unscheduled dependencies after
2845               // decrementing, so we can put the dependent instruction
2846               // into the ready list.
2847               ScheduleData *DepBundle = OpDef->FirstInBundle;
2848               assert(!DepBundle->IsScheduled &&
2849                      "already scheduled bundle gets ready");
2850               ReadyList.insert(DepBundle);
2851               LLVM_DEBUG(dbgs()
2852                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2853             }
2854           });
2855         };
2856 
2857         // If BundleMember is a vector bundle, its operands may have been
2858         // reordered during buildTree(). We therefore need to get its operands
2859         // through the TreeEntry.
2860         if (TreeEntry *TE = BundleMember->TE) {
2861           // Need to search for the lane since the tree entry can be reordered.
2862           int Lane = std::distance(TE->Scalars.begin(),
2863                                    find(TE->Scalars, BundleMember->Inst));
2864           assert(Lane >= 0 && "Lane not set");
2865 
2866           // Since vectorization tree is being built recursively this assertion
2867           // ensures that the tree entry has all operands set before reaching
2868           // this code. Couple of exceptions known at the moment are extracts
2869           // where their second (immediate) operand is not added. Since
2870           // immediates do not affect scheduler behavior this is considered
2871           // okay.
2872           auto *In = BundleMember->Inst;
2873           assert(In &&
2874                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2875                   In->getNumOperands() == TE->getNumOperands()) &&
2876                  "Missed TreeEntry operands?");
2877           (void)In; // fake use to avoid build failure when assertions disabled
2878 
2879           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2880                OpIdx != NumOperands; ++OpIdx)
2881             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2882               DecrUnsched(I);
2883         } else {
2884           // If BundleMember is a stand-alone instruction, no operand reordering
2885           // has taken place, so we directly access its operands.
2886           for (Use &U : BundleMember->Inst->operands())
2887             if (auto *I = dyn_cast<Instruction>(U.get()))
2888               DecrUnsched(I);
2889         }
2890         // Handle the memory dependencies.
2891         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2892           if (MemoryDepSD->hasValidDependencies() &&
2893               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2894             // There are no more unscheduled dependencies after decrementing,
2895             // so we can put the dependent instruction into the ready list.
2896             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2897             assert(!DepBundle->IsScheduled &&
2898                    "already scheduled bundle gets ready");
2899             ReadyList.insert(DepBundle);
2900             LLVM_DEBUG(dbgs()
2901                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2902           }
2903         }
2904         // Handle the control dependencies.
2905         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2906           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2907             // There are no more unscheduled dependencies after decrementing,
2908             // so we can put the dependent instruction into the ready list.
2909             ScheduleData *DepBundle = DepSD->FirstInBundle;
2910             assert(!DepBundle->IsScheduled &&
2911                    "already scheduled bundle gets ready");
2912             ReadyList.insert(DepBundle);
2913             LLVM_DEBUG(dbgs()
2914                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2915           }
2916         }
2917 
2918       }
2919     }
2920 
2921     /// Verify basic self consistency properties of the data structure.
2922     void verify() {
2923       if (!ScheduleStart)
2924         return;
2925 
2926       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2927              ScheduleStart->comesBefore(ScheduleEnd) &&
2928              "Not a valid scheduling region?");
2929 
2930       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2931         auto *SD = getScheduleData(I);
2932         if (!SD)
2933           continue;
2934         assert(isInSchedulingRegion(SD) &&
2935                "primary schedule data not in window?");
2936         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2937                "entire bundle in window!");
2938         (void)SD;
2939         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2940       }
2941 
2942       for (auto *SD : ReadyInsts) {
2943         assert(SD->isSchedulingEntity() && SD->isReady() &&
2944                "item in ready list not ready?");
2945         (void)SD;
2946       }
2947     }
2948 
2949     void doForAllOpcodes(Value *V,
2950                          function_ref<void(ScheduleData *SD)> Action) {
2951       if (ScheduleData *SD = getScheduleData(V))
2952         Action(SD);
2953       auto I = ExtraScheduleDataMap.find(V);
2954       if (I != ExtraScheduleDataMap.end())
2955         for (auto &P : I->second)
2956           if (isInSchedulingRegion(P.second))
2957             Action(P.second);
2958     }
2959 
2960     /// Put all instructions into the ReadyList which are ready for scheduling.
2961     template <typename ReadyListType>
2962     void initialFillReadyList(ReadyListType &ReadyList) {
2963       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2964         doForAllOpcodes(I, [&](ScheduleData *SD) {
2965           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
2966               SD->isReady()) {
2967             ReadyList.insert(SD);
2968             LLVM_DEBUG(dbgs()
2969                        << "SLP:    initially in ready list: " << *SD << "\n");
2970           }
2971         });
2972       }
2973     }
2974 
2975     /// Build a bundle from the ScheduleData nodes corresponding to the
2976     /// scalar instruction for each lane.
2977     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2978 
2979     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2980     /// cyclic dependencies. This is only a dry-run, no instructions are
2981     /// actually moved at this stage.
2982     /// \returns the scheduling bundle. The returned Optional value is non-None
2983     /// if \p VL is allowed to be scheduled.
2984     Optional<ScheduleData *>
2985     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2986                       const InstructionsState &S);
2987 
2988     /// Un-bundles a group of instructions.
2989     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2990 
2991     /// Allocates schedule data chunk.
2992     ScheduleData *allocateScheduleDataChunks();
2993 
2994     /// Extends the scheduling region so that V is inside the region.
2995     /// \returns true if the region size is within the limit.
2996     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2997 
2998     /// Initialize the ScheduleData structures for new instructions in the
2999     /// scheduling region.
3000     void initScheduleData(Instruction *FromI, Instruction *ToI,
3001                           ScheduleData *PrevLoadStore,
3002                           ScheduleData *NextLoadStore);
3003 
3004     /// Updates the dependency information of a bundle and of all instructions/
3005     /// bundles which depend on the original bundle.
3006     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3007                                BoUpSLP *SLP);
3008 
3009     /// Sets all instruction in the scheduling region to un-scheduled.
3010     void resetSchedule();
3011 
3012     BasicBlock *BB;
3013 
3014     /// Simple memory allocation for ScheduleData.
3015     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3016 
3017     /// The size of a ScheduleData array in ScheduleDataChunks.
3018     int ChunkSize;
3019 
3020     /// The allocator position in the current chunk, which is the last entry
3021     /// of ScheduleDataChunks.
3022     int ChunkPos;
3023 
3024     /// Attaches ScheduleData to Instruction.
3025     /// Note that the mapping survives during all vectorization iterations, i.e.
3026     /// ScheduleData structures are recycled.
3027     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3028 
3029     /// Attaches ScheduleData to Instruction with the leading key.
3030     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3031         ExtraScheduleDataMap;
3032 
3033     /// The ready-list for scheduling (only used for the dry-run).
3034     SetVector<ScheduleData *> ReadyInsts;
3035 
3036     /// The first instruction of the scheduling region.
3037     Instruction *ScheduleStart = nullptr;
3038 
3039     /// The first instruction _after_ the scheduling region.
3040     Instruction *ScheduleEnd = nullptr;
3041 
3042     /// The first memory accessing instruction in the scheduling region
3043     /// (can be null).
3044     ScheduleData *FirstLoadStoreInRegion = nullptr;
3045 
3046     /// The last memory accessing instruction in the scheduling region
3047     /// (can be null).
3048     ScheduleData *LastLoadStoreInRegion = nullptr;
3049 
3050     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3051     /// region?  Used to optimize the dependence calculation for the
3052     /// common case where there isn't.
3053     bool RegionHasStackSave = false;
3054 
3055     /// The current size of the scheduling region.
3056     int ScheduleRegionSize = 0;
3057 
3058     /// The maximum size allowed for the scheduling region.
3059     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3060 
3061     /// The ID of the scheduling region. For a new vectorization iteration this
3062     /// is incremented which "removes" all ScheduleData from the region.
3063     /// Make sure that the initial SchedulingRegionID is greater than the
3064     /// initial SchedulingRegionID in ScheduleData (which is 0).
3065     int SchedulingRegionID = 1;
3066   };
3067 
3068   /// Attaches the BlockScheduling structures to basic blocks.
3069   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3070 
3071   /// Performs the "real" scheduling. Done before vectorization is actually
3072   /// performed in a basic block.
3073   void scheduleBlock(BlockScheduling *BS);
3074 
3075   /// List of users to ignore during scheduling and that don't need extracting.
3076   ArrayRef<Value *> UserIgnoreList;
3077 
3078   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3079   /// sorted SmallVectors of unsigned.
3080   struct OrdersTypeDenseMapInfo {
3081     static OrdersType getEmptyKey() {
3082       OrdersType V;
3083       V.push_back(~1U);
3084       return V;
3085     }
3086 
3087     static OrdersType getTombstoneKey() {
3088       OrdersType V;
3089       V.push_back(~2U);
3090       return V;
3091     }
3092 
3093     static unsigned getHashValue(const OrdersType &V) {
3094       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3095     }
3096 
3097     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3098       return LHS == RHS;
3099     }
3100   };
3101 
3102   // Analysis and block reference.
3103   Function *F;
3104   ScalarEvolution *SE;
3105   TargetTransformInfo *TTI;
3106   TargetLibraryInfo *TLI;
3107   LoopInfo *LI;
3108   DominatorTree *DT;
3109   AssumptionCache *AC;
3110   DemandedBits *DB;
3111   const DataLayout *DL;
3112   OptimizationRemarkEmitter *ORE;
3113 
3114   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3115   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3116 
3117   /// Instruction builder to construct the vectorized tree.
3118   IRBuilder<> Builder;
3119 
3120   /// A map of scalar integer values to the smallest bit width with which they
3121   /// can legally be represented. The values map to (width, signed) pairs,
3122   /// where "width" indicates the minimum bit width and "signed" is True if the
3123   /// value must be signed-extended, rather than zero-extended, back to its
3124   /// original width.
3125   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3126 };
3127 
3128 } // end namespace slpvectorizer
3129 
3130 template <> struct GraphTraits<BoUpSLP *> {
3131   using TreeEntry = BoUpSLP::TreeEntry;
3132 
3133   /// NodeRef has to be a pointer per the GraphWriter.
3134   using NodeRef = TreeEntry *;
3135 
3136   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3137 
3138   /// Add the VectorizableTree to the index iterator to be able to return
3139   /// TreeEntry pointers.
3140   struct ChildIteratorType
3141       : public iterator_adaptor_base<
3142             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3143     ContainerTy &VectorizableTree;
3144 
3145     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3146                       ContainerTy &VT)
3147         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3148 
3149     NodeRef operator*() { return I->UserTE; }
3150   };
3151 
3152   static NodeRef getEntryNode(BoUpSLP &R) {
3153     return R.VectorizableTree[0].get();
3154   }
3155 
3156   static ChildIteratorType child_begin(NodeRef N) {
3157     return {N->UserTreeIndices.begin(), N->Container};
3158   }
3159 
3160   static ChildIteratorType child_end(NodeRef N) {
3161     return {N->UserTreeIndices.end(), N->Container};
3162   }
3163 
3164   /// For the node iterator we just need to turn the TreeEntry iterator into a
3165   /// TreeEntry* iterator so that it dereferences to NodeRef.
3166   class nodes_iterator {
3167     using ItTy = ContainerTy::iterator;
3168     ItTy It;
3169 
3170   public:
3171     nodes_iterator(const ItTy &It2) : It(It2) {}
3172     NodeRef operator*() { return It->get(); }
3173     nodes_iterator operator++() {
3174       ++It;
3175       return *this;
3176     }
3177     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3178   };
3179 
3180   static nodes_iterator nodes_begin(BoUpSLP *R) {
3181     return nodes_iterator(R->VectorizableTree.begin());
3182   }
3183 
3184   static nodes_iterator nodes_end(BoUpSLP *R) {
3185     return nodes_iterator(R->VectorizableTree.end());
3186   }
3187 
3188   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3189 };
3190 
3191 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3192   using TreeEntry = BoUpSLP::TreeEntry;
3193 
3194   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3195 
3196   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3197     std::string Str;
3198     raw_string_ostream OS(Str);
3199     if (isSplat(Entry->Scalars))
3200       OS << "<splat> ";
3201     for (auto V : Entry->Scalars) {
3202       OS << *V;
3203       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3204             return EU.Scalar == V;
3205           }))
3206         OS << " <extract>";
3207       OS << "\n";
3208     }
3209     return Str;
3210   }
3211 
3212   static std::string getNodeAttributes(const TreeEntry *Entry,
3213                                        const BoUpSLP *) {
3214     if (Entry->State == TreeEntry::NeedToGather)
3215       return "color=red";
3216     return "";
3217   }
3218 };
3219 
3220 } // end namespace llvm
3221 
3222 BoUpSLP::~BoUpSLP() {
3223   SmallVector<WeakTrackingVH> DeadInsts;
3224   for (auto *I : DeletedInstructions) {
3225     for (Use &U : I->operands()) {
3226       auto *Op = dyn_cast<Instruction>(U.get());
3227       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3228           wouldInstructionBeTriviallyDead(Op, TLI))
3229         DeadInsts.emplace_back(Op);
3230     }
3231     I->dropAllReferences();
3232   }
3233   for (auto *I : DeletedInstructions) {
3234     assert(I->use_empty() &&
3235            "trying to erase instruction with users.");
3236     I->eraseFromParent();
3237   }
3238 
3239   // Cleanup any dead scalar code feeding the vectorized instructions
3240   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3241 
3242 #ifdef EXPENSIVE_CHECKS
3243   // If we could guarantee that this call is not extremely slow, we could
3244   // remove the ifdef limitation (see PR47712).
3245   assert(!verifyFunction(*F, &dbgs()));
3246 #endif
3247 }
3248 
3249 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3250 /// contains original mask for the scalars reused in the node. Procedure
3251 /// transform this mask in accordance with the given \p Mask.
3252 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3253   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3254          "Expected non-empty mask.");
3255   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3256   Prev.swap(Reuses);
3257   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3258     if (Mask[I] != UndefMaskElem)
3259       Reuses[Mask[I]] = Prev[I];
3260 }
3261 
3262 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3263 /// the original order of the scalars. Procedure transforms the provided order
3264 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3265 /// identity order, \p Order is cleared.
3266 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3267   assert(!Mask.empty() && "Expected non-empty mask.");
3268   SmallVector<int> MaskOrder;
3269   if (Order.empty()) {
3270     MaskOrder.resize(Mask.size());
3271     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3272   } else {
3273     inversePermutation(Order, MaskOrder);
3274   }
3275   reorderReuses(MaskOrder, Mask);
3276   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3277     Order.clear();
3278     return;
3279   }
3280   Order.assign(Mask.size(), Mask.size());
3281   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3282     if (MaskOrder[I] != UndefMaskElem)
3283       Order[MaskOrder[I]] = I;
3284   fixupOrderingIndices(Order);
3285 }
3286 
3287 Optional<BoUpSLP::OrdersType>
3288 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3289   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3290   unsigned NumScalars = TE.Scalars.size();
3291   OrdersType CurrentOrder(NumScalars, NumScalars);
3292   SmallVector<int> Positions;
3293   SmallBitVector UsedPositions(NumScalars);
3294   const TreeEntry *STE = nullptr;
3295   // Try to find all gathered scalars that are gets vectorized in other
3296   // vectorize node. Here we can have only one single tree vector node to
3297   // correctly identify order of the gathered scalars.
3298   for (unsigned I = 0; I < NumScalars; ++I) {
3299     Value *V = TE.Scalars[I];
3300     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3301       continue;
3302     if (const auto *LocalSTE = getTreeEntry(V)) {
3303       if (!STE)
3304         STE = LocalSTE;
3305       else if (STE != LocalSTE)
3306         // Take the order only from the single vector node.
3307         return None;
3308       unsigned Lane =
3309           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3310       if (Lane >= NumScalars)
3311         return None;
3312       if (CurrentOrder[Lane] != NumScalars) {
3313         if (Lane != I)
3314           continue;
3315         UsedPositions.reset(CurrentOrder[Lane]);
3316       }
3317       // The partial identity (where only some elements of the gather node are
3318       // in the identity order) is good.
3319       CurrentOrder[Lane] = I;
3320       UsedPositions.set(I);
3321     }
3322   }
3323   // Need to keep the order if we have a vector entry and at least 2 scalars or
3324   // the vectorized entry has just 2 scalars.
3325   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3326     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3327       for (unsigned I = 0; I < NumScalars; ++I)
3328         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3329           return false;
3330       return true;
3331     };
3332     if (IsIdentityOrder(CurrentOrder)) {
3333       CurrentOrder.clear();
3334       return CurrentOrder;
3335     }
3336     auto *It = CurrentOrder.begin();
3337     for (unsigned I = 0; I < NumScalars;) {
3338       if (UsedPositions.test(I)) {
3339         ++I;
3340         continue;
3341       }
3342       if (*It == NumScalars) {
3343         *It = I;
3344         ++I;
3345       }
3346       ++It;
3347     }
3348     return CurrentOrder;
3349   }
3350   return None;
3351 }
3352 
3353 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3354                                                          bool TopToBottom) {
3355   // No need to reorder if need to shuffle reuses, still need to shuffle the
3356   // node.
3357   if (!TE.ReuseShuffleIndices.empty())
3358     return None;
3359   if (TE.State == TreeEntry::Vectorize &&
3360       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3361        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3362       !TE.isAltShuffle())
3363     return TE.ReorderIndices;
3364   if (TE.State == TreeEntry::NeedToGather) {
3365     // TODO: add analysis of other gather nodes with extractelement
3366     // instructions and other values/instructions, not only undefs.
3367     if (((TE.getOpcode() == Instruction::ExtractElement &&
3368           !TE.isAltShuffle()) ||
3369          (all_of(TE.Scalars,
3370                  [](Value *V) {
3371                    return isa<UndefValue, ExtractElementInst>(V);
3372                  }) &&
3373           any_of(TE.Scalars,
3374                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3375         all_of(TE.Scalars,
3376                [](Value *V) {
3377                  auto *EE = dyn_cast<ExtractElementInst>(V);
3378                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3379                }) &&
3380         allSameType(TE.Scalars)) {
3381       // Check that gather of extractelements can be represented as
3382       // just a shuffle of a single vector.
3383       OrdersType CurrentOrder;
3384       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3385       if (Reuse || !CurrentOrder.empty()) {
3386         if (!CurrentOrder.empty())
3387           fixupOrderingIndices(CurrentOrder);
3388         return CurrentOrder;
3389       }
3390     }
3391     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3392       return CurrentOrder;
3393   }
3394   return None;
3395 }
3396 
3397 void BoUpSLP::reorderTopToBottom() {
3398   // Maps VF to the graph nodes.
3399   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3400   // ExtractElement gather nodes which can be vectorized and need to handle
3401   // their ordering.
3402   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3403   // Find all reorderable nodes with the given VF.
3404   // Currently the are vectorized stores,loads,extracts + some gathering of
3405   // extracts.
3406   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3407                                  const std::unique_ptr<TreeEntry> &TE) {
3408     if (Optional<OrdersType> CurrentOrder =
3409             getReorderingData(*TE, /*TopToBottom=*/true)) {
3410       // Do not include ordering for nodes used in the alt opcode vectorization,
3411       // better to reorder them during bottom-to-top stage. If follow the order
3412       // here, it causes reordering of the whole graph though actually it is
3413       // profitable just to reorder the subgraph that starts from the alternate
3414       // opcode vectorization node. Such nodes already end-up with the shuffle
3415       // instruction and it is just enough to change this shuffle rather than
3416       // rotate the scalars for the whole graph.
3417       unsigned Cnt = 0;
3418       const TreeEntry *UserTE = TE.get();
3419       while (UserTE && Cnt < RecursionMaxDepth) {
3420         if (UserTE->UserTreeIndices.size() != 1)
3421           break;
3422         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3423               return EI.UserTE->State == TreeEntry::Vectorize &&
3424                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3425             }))
3426           return;
3427         if (UserTE->UserTreeIndices.empty())
3428           UserTE = nullptr;
3429         else
3430           UserTE = UserTE->UserTreeIndices.back().UserTE;
3431         ++Cnt;
3432       }
3433       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3434       if (TE->State != TreeEntry::Vectorize)
3435         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3436     }
3437   });
3438 
3439   // Reorder the graph nodes according to their vectorization factor.
3440   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3441        VF /= 2) {
3442     auto It = VFToOrderedEntries.find(VF);
3443     if (It == VFToOrderedEntries.end())
3444       continue;
3445     // Try to find the most profitable order. We just are looking for the most
3446     // used order and reorder scalar elements in the nodes according to this
3447     // mostly used order.
3448     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3449     // All operands are reordered and used only in this node - propagate the
3450     // most used order to the user node.
3451     MapVector<OrdersType, unsigned,
3452               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3453         OrdersUses;
3454     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3455     for (const TreeEntry *OpTE : OrderedEntries) {
3456       // No need to reorder this nodes, still need to extend and to use shuffle,
3457       // just need to merge reordering shuffle and the reuse shuffle.
3458       if (!OpTE->ReuseShuffleIndices.empty())
3459         continue;
3460       // Count number of orders uses.
3461       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3462         if (OpTE->State == TreeEntry::NeedToGather)
3463           return GathersToOrders.find(OpTE)->second;
3464         return OpTE->ReorderIndices;
3465       }();
3466       // Stores actually store the mask, not the order, need to invert.
3467       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3468           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3469         SmallVector<int> Mask;
3470         inversePermutation(Order, Mask);
3471         unsigned E = Order.size();
3472         OrdersType CurrentOrder(E, E);
3473         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3474           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3475         });
3476         fixupOrderingIndices(CurrentOrder);
3477         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3478       } else {
3479         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3480       }
3481     }
3482     // Set order of the user node.
3483     if (OrdersUses.empty())
3484       continue;
3485     // Choose the most used order.
3486     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3487     unsigned Cnt = OrdersUses.front().second;
3488     for (const auto &Pair : drop_begin(OrdersUses)) {
3489       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3490         BestOrder = Pair.first;
3491         Cnt = Pair.second;
3492       }
3493     }
3494     // Set order of the user node.
3495     if (BestOrder.empty())
3496       continue;
3497     SmallVector<int> Mask;
3498     inversePermutation(BestOrder, Mask);
3499     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3500     unsigned E = BestOrder.size();
3501     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3502       return I < E ? static_cast<int>(I) : UndefMaskElem;
3503     });
3504     // Do an actual reordering, if profitable.
3505     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3506       // Just do the reordering for the nodes with the given VF.
3507       if (TE->Scalars.size() != VF) {
3508         if (TE->ReuseShuffleIndices.size() == VF) {
3509           // Need to reorder the reuses masks of the operands with smaller VF to
3510           // be able to find the match between the graph nodes and scalar
3511           // operands of the given node during vectorization/cost estimation.
3512           assert(all_of(TE->UserTreeIndices,
3513                         [VF, &TE](const EdgeInfo &EI) {
3514                           return EI.UserTE->Scalars.size() == VF ||
3515                                  EI.UserTE->Scalars.size() ==
3516                                      TE->Scalars.size();
3517                         }) &&
3518                  "All users must be of VF size.");
3519           // Update ordering of the operands with the smaller VF than the given
3520           // one.
3521           reorderReuses(TE->ReuseShuffleIndices, Mask);
3522         }
3523         continue;
3524       }
3525       if (TE->State == TreeEntry::Vectorize &&
3526           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3527               InsertElementInst>(TE->getMainOp()) &&
3528           !TE->isAltShuffle()) {
3529         // Build correct orders for extract{element,value}, loads and
3530         // stores.
3531         reorderOrder(TE->ReorderIndices, Mask);
3532         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3533           TE->reorderOperands(Mask);
3534       } else {
3535         // Reorder the node and its operands.
3536         TE->reorderOperands(Mask);
3537         assert(TE->ReorderIndices.empty() &&
3538                "Expected empty reorder sequence.");
3539         reorderScalars(TE->Scalars, Mask);
3540       }
3541       if (!TE->ReuseShuffleIndices.empty()) {
3542         // Apply reversed order to keep the original ordering of the reused
3543         // elements to avoid extra reorder indices shuffling.
3544         OrdersType CurrentOrder;
3545         reorderOrder(CurrentOrder, MaskOrder);
3546         SmallVector<int> NewReuses;
3547         inversePermutation(CurrentOrder, NewReuses);
3548         addMask(NewReuses, TE->ReuseShuffleIndices);
3549         TE->ReuseShuffleIndices.swap(NewReuses);
3550       }
3551     }
3552   }
3553 }
3554 
3555 bool BoUpSLP::canReorderOperands(
3556     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3557     ArrayRef<TreeEntry *> ReorderableGathers,
3558     SmallVectorImpl<TreeEntry *> &GatherOps) {
3559   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3560     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3561           return OpData.first == I &&
3562                  OpData.second->State == TreeEntry::Vectorize;
3563         }))
3564       continue;
3565     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3566       // Do not reorder if operand node is used by many user nodes.
3567       if (any_of(TE->UserTreeIndices,
3568                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3569         return false;
3570       // Add the node to the list of the ordered nodes with the identity
3571       // order.
3572       Edges.emplace_back(I, TE);
3573       continue;
3574     }
3575     ArrayRef<Value *> VL = UserTE->getOperand(I);
3576     TreeEntry *Gather = nullptr;
3577     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3578           assert(TE->State != TreeEntry::Vectorize &&
3579                  "Only non-vectorized nodes are expected.");
3580           if (TE->isSame(VL)) {
3581             Gather = TE;
3582             return true;
3583           }
3584           return false;
3585         }) > 1)
3586       return false;
3587     if (Gather)
3588       GatherOps.push_back(Gather);
3589   }
3590   return true;
3591 }
3592 
3593 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3594   SetVector<TreeEntry *> OrderedEntries;
3595   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3596   // Find all reorderable leaf nodes with the given VF.
3597   // Currently the are vectorized loads,extracts without alternate operands +
3598   // some gathering of extracts.
3599   SmallVector<TreeEntry *> NonVectorized;
3600   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3601                               &NonVectorized](
3602                                  const std::unique_ptr<TreeEntry> &TE) {
3603     if (TE->State != TreeEntry::Vectorize)
3604       NonVectorized.push_back(TE.get());
3605     if (Optional<OrdersType> CurrentOrder =
3606             getReorderingData(*TE, /*TopToBottom=*/false)) {
3607       OrderedEntries.insert(TE.get());
3608       if (TE->State != TreeEntry::Vectorize)
3609         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3610     }
3611   });
3612 
3613   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3614   // I.e., if the node has operands, that are reordered, try to make at least
3615   // one operand order in the natural order and reorder others + reorder the
3616   // user node itself.
3617   SmallPtrSet<const TreeEntry *, 4> Visited;
3618   while (!OrderedEntries.empty()) {
3619     // 1. Filter out only reordered nodes.
3620     // 2. If the entry has multiple uses - skip it and jump to the next node.
3621     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3622     SmallVector<TreeEntry *> Filtered;
3623     for (TreeEntry *TE : OrderedEntries) {
3624       if (!(TE->State == TreeEntry::Vectorize ||
3625             (TE->State == TreeEntry::NeedToGather &&
3626              GathersToOrders.count(TE))) ||
3627           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3628           !all_of(drop_begin(TE->UserTreeIndices),
3629                   [TE](const EdgeInfo &EI) {
3630                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3631                   }) ||
3632           !Visited.insert(TE).second) {
3633         Filtered.push_back(TE);
3634         continue;
3635       }
3636       // Build a map between user nodes and their operands order to speedup
3637       // search. The graph currently does not provide this dependency directly.
3638       for (EdgeInfo &EI : TE->UserTreeIndices) {
3639         TreeEntry *UserTE = EI.UserTE;
3640         auto It = Users.find(UserTE);
3641         if (It == Users.end())
3642           It = Users.insert({UserTE, {}}).first;
3643         It->second.emplace_back(EI.EdgeIdx, TE);
3644       }
3645     }
3646     // Erase filtered entries.
3647     for_each(Filtered,
3648              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3649     for (auto &Data : Users) {
3650       // Check that operands are used only in the User node.
3651       SmallVector<TreeEntry *> GatherOps;
3652       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3653                               GatherOps)) {
3654         for_each(Data.second,
3655                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3656                    OrderedEntries.remove(Op.second);
3657                  });
3658         continue;
3659       }
3660       // All operands are reordered and used only in this node - propagate the
3661       // most used order to the user node.
3662       MapVector<OrdersType, unsigned,
3663                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3664           OrdersUses;
3665       // Do the analysis for each tree entry only once, otherwise the order of
3666       // the same node my be considered several times, though might be not
3667       // profitable.
3668       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3669       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3670       for (const auto &Op : Data.second) {
3671         TreeEntry *OpTE = Op.second;
3672         if (!VisitedOps.insert(OpTE).second)
3673           continue;
3674         if (!OpTE->ReuseShuffleIndices.empty() ||
3675             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3676           continue;
3677         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3678           if (OpTE->State == TreeEntry::NeedToGather)
3679             return GathersToOrders.find(OpTE)->second;
3680           return OpTE->ReorderIndices;
3681         }();
3682         unsigned NumOps = count_if(
3683             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3684               return P.second == OpTE;
3685             });
3686         // Stores actually store the mask, not the order, need to invert.
3687         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3688             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3689           SmallVector<int> Mask;
3690           inversePermutation(Order, Mask);
3691           unsigned E = Order.size();
3692           OrdersType CurrentOrder(E, E);
3693           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3694             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3695           });
3696           fixupOrderingIndices(CurrentOrder);
3697           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3698               NumOps;
3699         } else {
3700           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3701         }
3702         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3703         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3704                                             const TreeEntry *TE) {
3705           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3706               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3707               (IgnoreReorder && TE->Idx == 0))
3708             return true;
3709           if (TE->State == TreeEntry::NeedToGather) {
3710             auto It = GathersToOrders.find(TE);
3711             if (It != GathersToOrders.end())
3712               return !It->second.empty();
3713             return true;
3714           }
3715           return false;
3716         };
3717         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3718           TreeEntry *UserTE = EI.UserTE;
3719           if (!VisitedUsers.insert(UserTE).second)
3720             continue;
3721           // May reorder user node if it requires reordering, has reused
3722           // scalars, is an alternate op vectorize node or its op nodes require
3723           // reordering.
3724           if (AllowsReordering(UserTE))
3725             continue;
3726           // Check if users allow reordering.
3727           // Currently look up just 1 level of operands to avoid increase of
3728           // the compile time.
3729           // Profitable to reorder if definitely more operands allow
3730           // reordering rather than those with natural order.
3731           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3732           if (static_cast<unsigned>(count_if(
3733                   Ops, [UserTE, &AllowsReordering](
3734                            const std::pair<unsigned, TreeEntry *> &Op) {
3735                     return AllowsReordering(Op.second) &&
3736                            all_of(Op.second->UserTreeIndices,
3737                                   [UserTE](const EdgeInfo &EI) {
3738                                     return EI.UserTE == UserTE;
3739                                   });
3740                   })) <= Ops.size() / 2)
3741             ++Res.first->second;
3742         }
3743       }
3744       // If no orders - skip current nodes and jump to the next one, if any.
3745       if (OrdersUses.empty()) {
3746         for_each(Data.second,
3747                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3748                    OrderedEntries.remove(Op.second);
3749                  });
3750         continue;
3751       }
3752       // Choose the best order.
3753       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3754       unsigned Cnt = OrdersUses.front().second;
3755       for (const auto &Pair : drop_begin(OrdersUses)) {
3756         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3757           BestOrder = Pair.first;
3758           Cnt = Pair.second;
3759         }
3760       }
3761       // Set order of the user node (reordering of operands and user nodes).
3762       if (BestOrder.empty()) {
3763         for_each(Data.second,
3764                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3765                    OrderedEntries.remove(Op.second);
3766                  });
3767         continue;
3768       }
3769       // Erase operands from OrderedEntries list and adjust their orders.
3770       VisitedOps.clear();
3771       SmallVector<int> Mask;
3772       inversePermutation(BestOrder, Mask);
3773       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3774       unsigned E = BestOrder.size();
3775       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3776         return I < E ? static_cast<int>(I) : UndefMaskElem;
3777       });
3778       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3779         TreeEntry *TE = Op.second;
3780         OrderedEntries.remove(TE);
3781         if (!VisitedOps.insert(TE).second)
3782           continue;
3783         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3784           // Just reorder reuses indices.
3785           reorderReuses(TE->ReuseShuffleIndices, Mask);
3786           continue;
3787         }
3788         // Gathers are processed separately.
3789         if (TE->State != TreeEntry::Vectorize)
3790           continue;
3791         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3792                 TE->ReorderIndices.empty()) &&
3793                "Non-matching sizes of user/operand entries.");
3794         reorderOrder(TE->ReorderIndices, Mask);
3795       }
3796       // For gathers just need to reorder its scalars.
3797       for (TreeEntry *Gather : GatherOps) {
3798         assert(Gather->ReorderIndices.empty() &&
3799                "Unexpected reordering of gathers.");
3800         if (!Gather->ReuseShuffleIndices.empty()) {
3801           // Just reorder reuses indices.
3802           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3803           continue;
3804         }
3805         reorderScalars(Gather->Scalars, Mask);
3806         OrderedEntries.remove(Gather);
3807       }
3808       // Reorder operands of the user node and set the ordering for the user
3809       // node itself.
3810       if (Data.first->State != TreeEntry::Vectorize ||
3811           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3812               Data.first->getMainOp()) ||
3813           Data.first->isAltShuffle())
3814         Data.first->reorderOperands(Mask);
3815       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3816           Data.first->isAltShuffle()) {
3817         reorderScalars(Data.first->Scalars, Mask);
3818         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3819         if (Data.first->ReuseShuffleIndices.empty() &&
3820             !Data.first->ReorderIndices.empty() &&
3821             !Data.first->isAltShuffle()) {
3822           // Insert user node to the list to try to sink reordering deeper in
3823           // the graph.
3824           OrderedEntries.insert(Data.first);
3825         }
3826       } else {
3827         reorderOrder(Data.first->ReorderIndices, Mask);
3828       }
3829     }
3830   }
3831   // If the reordering is unnecessary, just remove the reorder.
3832   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3833       VectorizableTree.front()->ReuseShuffleIndices.empty())
3834     VectorizableTree.front()->ReorderIndices.clear();
3835 }
3836 
3837 void BoUpSLP::buildExternalUses(
3838     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3839   // Collect the values that we need to extract from the tree.
3840   for (auto &TEPtr : VectorizableTree) {
3841     TreeEntry *Entry = TEPtr.get();
3842 
3843     // No need to handle users of gathered values.
3844     if (Entry->State == TreeEntry::NeedToGather)
3845       continue;
3846 
3847     // For each lane:
3848     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3849       Value *Scalar = Entry->Scalars[Lane];
3850       int FoundLane = Entry->findLaneForValue(Scalar);
3851 
3852       // Check if the scalar is externally used as an extra arg.
3853       auto ExtI = ExternallyUsedValues.find(Scalar);
3854       if (ExtI != ExternallyUsedValues.end()) {
3855         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3856                           << Lane << " from " << *Scalar << ".\n");
3857         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3858       }
3859       for (User *U : Scalar->users()) {
3860         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3861 
3862         Instruction *UserInst = dyn_cast<Instruction>(U);
3863         if (!UserInst)
3864           continue;
3865 
3866         if (isDeleted(UserInst))
3867           continue;
3868 
3869         // Skip in-tree scalars that become vectors
3870         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3871           Value *UseScalar = UseEntry->Scalars[0];
3872           // Some in-tree scalars will remain as scalar in vectorized
3873           // instructions. If that is the case, the one in Lane 0 will
3874           // be used.
3875           if (UseScalar != U ||
3876               UseEntry->State == TreeEntry::ScatterVectorize ||
3877               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3878             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3879                               << ".\n");
3880             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3881             continue;
3882           }
3883         }
3884 
3885         // Ignore users in the user ignore list.
3886         if (is_contained(UserIgnoreList, UserInst))
3887           continue;
3888 
3889         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3890                           << Lane << " from " << *Scalar << ".\n");
3891         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3892       }
3893     }
3894   }
3895 }
3896 
3897 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3898                         ArrayRef<Value *> UserIgnoreLst) {
3899   deleteTree();
3900   UserIgnoreList = UserIgnoreLst;
3901   if (!allSameType(Roots))
3902     return;
3903   buildTree_rec(Roots, 0, EdgeInfo());
3904 }
3905 
3906 namespace {
3907 /// Tracks the state we can represent the loads in the given sequence.
3908 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3909 } // anonymous namespace
3910 
3911 /// Checks if the given array of loads can be represented as a vectorized,
3912 /// scatter or just simple gather.
3913 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3914                                     const TargetTransformInfo &TTI,
3915                                     const DataLayout &DL, ScalarEvolution &SE,
3916                                     SmallVectorImpl<unsigned> &Order,
3917                                     SmallVectorImpl<Value *> &PointerOps) {
3918   // Check that a vectorized load would load the same memory as a scalar
3919   // load. For example, we don't want to vectorize loads that are smaller
3920   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3921   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3922   // from such a struct, we read/write packed bits disagreeing with the
3923   // unvectorized version.
3924   Type *ScalarTy = VL0->getType();
3925 
3926   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3927     return LoadsState::Gather;
3928 
3929   // Make sure all loads in the bundle are simple - we can't vectorize
3930   // atomic or volatile loads.
3931   PointerOps.clear();
3932   PointerOps.resize(VL.size());
3933   auto *POIter = PointerOps.begin();
3934   for (Value *V : VL) {
3935     auto *L = cast<LoadInst>(V);
3936     if (!L->isSimple())
3937       return LoadsState::Gather;
3938     *POIter = L->getPointerOperand();
3939     ++POIter;
3940   }
3941 
3942   Order.clear();
3943   // Check the order of pointer operands.
3944   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3945     Value *Ptr0;
3946     Value *PtrN;
3947     if (Order.empty()) {
3948       Ptr0 = PointerOps.front();
3949       PtrN = PointerOps.back();
3950     } else {
3951       Ptr0 = PointerOps[Order.front()];
3952       PtrN = PointerOps[Order.back()];
3953     }
3954     Optional<int> Diff =
3955         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3956     // Check that the sorted loads are consecutive.
3957     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3958       return LoadsState::Vectorize;
3959     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3960     for (Value *V : VL)
3961       CommonAlignment =
3962           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3963     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3964                                 CommonAlignment))
3965       return LoadsState::ScatterVectorize;
3966   }
3967 
3968   return LoadsState::Gather;
3969 }
3970 
3971 /// \return true if the specified list of values has only one instruction that
3972 /// requires scheduling, false otherwise.
3973 #ifndef NDEBUG
3974 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3975   Value *NeedsScheduling = nullptr;
3976   for (Value *V : VL) {
3977     if (doesNotNeedToBeScheduled(V))
3978       continue;
3979     if (!NeedsScheduling) {
3980       NeedsScheduling = V;
3981       continue;
3982     }
3983     return false;
3984   }
3985   return NeedsScheduling;
3986 }
3987 #endif
3988 
3989 /// Generates key/subkey pair for the given value to provide effective sorting
3990 /// of the values and better detection of the vectorizable values sequences. The
3991 /// keys/subkeys can be used for better sorting of the values themselves (keys)
3992 /// and in values subgroups (subkeys).
3993 static std::pair<size_t, size_t> generateKeySubkey(
3994     Value *V, const TargetLibraryInfo *TLI,
3995     function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
3996     bool AllowAlternate) {
3997   hash_code Key = hash_value(V->getValueID() + 2);
3998   hash_code SubKey = hash_value(0);
3999   // Sort the loads by the distance between the pointers.
4000   if (auto *LI = dyn_cast<LoadInst>(V)) {
4001     Key = hash_combine(hash_value(LI->getParent()), Key);
4002     if (LI->isSimple())
4003       SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4004     else
4005       SubKey = hash_value(LI);
4006   } else if (isVectorLikeInstWithConstOps(V)) {
4007     // Sort extracts by the vector operands.
4008     if (isa<ExtractElementInst, UndefValue>(V))
4009       Key = hash_value(Value::UndefValueVal + 1);
4010     if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4011       if (!isUndefVector(EI->getVectorOperand()) &&
4012           !isa<UndefValue>(EI->getIndexOperand()))
4013         SubKey = hash_value(EI->getVectorOperand());
4014     }
4015   } else if (auto *I = dyn_cast<Instruction>(V)) {
4016     // Sort other instructions just by the opcodes except for CMPInst.
4017     // For CMP also sort by the predicate kind.
4018     if ((isa<BinaryOperator>(I) || isa<CastInst>(I)) &&
4019         isValidForAlternation(I->getOpcode())) {
4020       if (AllowAlternate)
4021         Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4022       else
4023         Key = hash_combine(hash_value(I->getOpcode()), Key);
4024       SubKey = hash_combine(
4025           hash_value(I->getOpcode()), hash_value(I->getType()),
4026           hash_value(isa<BinaryOperator>(I)
4027                          ? I->getType()
4028                          : cast<CastInst>(I)->getOperand(0)->getType()));
4029     } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4030       CmpInst::Predicate Pred = CI->getPredicate();
4031       if (CI->isCommutative())
4032         Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4033       CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
4034       SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4035                             hash_value(SwapPred),
4036                             hash_value(CI->getOperand(0)->getType()));
4037     } else if (auto *Call = dyn_cast<CallInst>(I)) {
4038       Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
4039       if (isTriviallyVectorizable(ID))
4040         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4041       else if (!VFDatabase(*Call).getMappings(*Call).empty())
4042         SubKey = hash_combine(hash_value(I->getOpcode()),
4043                               hash_value(Call->getCalledFunction()));
4044       else
4045         SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4046       for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4047         SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4048                               hash_value(Op.Tag), SubKey);
4049     } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4050       if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4051         SubKey = hash_value(Gep->getPointerOperand());
4052       else
4053         SubKey = hash_value(Gep);
4054     } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4055                !isa<ConstantInt>(I->getOperand(1))) {
4056       // Do not try to vectorize instructions with potentially high cost.
4057       SubKey = hash_value(I);
4058     } else {
4059       SubKey = hash_value(I->getOpcode());
4060     }
4061     Key = hash_combine(hash_value(I->getParent()), Key);
4062   }
4063   return std::make_pair(Key, SubKey);
4064 }
4065 
4066 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4067                             const EdgeInfo &UserTreeIdx) {
4068   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4069 
4070   SmallVector<int> ReuseShuffleIndicies;
4071   SmallVector<Value *> UniqueValues;
4072   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4073                                 &UserTreeIdx,
4074                                 this](const InstructionsState &S) {
4075     // Check that every instruction appears once in this bundle.
4076     DenseMap<Value *, unsigned> UniquePositions;
4077     for (Value *V : VL) {
4078       if (isConstant(V)) {
4079         ReuseShuffleIndicies.emplace_back(
4080             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4081         UniqueValues.emplace_back(V);
4082         continue;
4083       }
4084       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4085       ReuseShuffleIndicies.emplace_back(Res.first->second);
4086       if (Res.second)
4087         UniqueValues.emplace_back(V);
4088     }
4089     size_t NumUniqueScalarValues = UniqueValues.size();
4090     if (NumUniqueScalarValues == VL.size()) {
4091       ReuseShuffleIndicies.clear();
4092     } else {
4093       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4094       if (NumUniqueScalarValues <= 1 ||
4095           (UniquePositions.size() == 1 && all_of(UniqueValues,
4096                                                  [](Value *V) {
4097                                                    return isa<UndefValue>(V) ||
4098                                                           !isConstant(V);
4099                                                  })) ||
4100           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4101         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4102         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4103         return false;
4104       }
4105       VL = UniqueValues;
4106     }
4107     return true;
4108   };
4109 
4110   InstructionsState S = getSameOpcode(VL);
4111   if (Depth == RecursionMaxDepth) {
4112     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4113     if (TryToFindDuplicates(S))
4114       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4115                    ReuseShuffleIndicies);
4116     return;
4117   }
4118 
4119   // Don't handle scalable vectors
4120   if (S.getOpcode() == Instruction::ExtractElement &&
4121       isa<ScalableVectorType>(
4122           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4123     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4124     if (TryToFindDuplicates(S))
4125       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4126                    ReuseShuffleIndicies);
4127     return;
4128   }
4129 
4130   // Don't handle vectors.
4131   if (S.OpValue->getType()->isVectorTy() &&
4132       !isa<InsertElementInst>(S.OpValue)) {
4133     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4134     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4135     return;
4136   }
4137 
4138   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4139     if (SI->getValueOperand()->getType()->isVectorTy()) {
4140       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4141       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4142       return;
4143     }
4144 
4145   // If all of the operands are identical or constant we have a simple solution.
4146   // If we deal with insert/extract instructions, they all must have constant
4147   // indices, otherwise we should gather them, not try to vectorize.
4148   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4149       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4150        !all_of(VL, isVectorLikeInstWithConstOps))) {
4151     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4152     if (TryToFindDuplicates(S))
4153       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4154                    ReuseShuffleIndicies);
4155     return;
4156   }
4157 
4158   // We now know that this is a vector of instructions of the same type from
4159   // the same block.
4160 
4161   // Don't vectorize ephemeral values.
4162   for (Value *V : VL) {
4163     if (EphValues.count(V)) {
4164       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4165                         << ") is ephemeral.\n");
4166       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4167       return;
4168     }
4169   }
4170 
4171   // Check if this is a duplicate of another entry.
4172   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4173     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4174     if (!E->isSame(VL)) {
4175       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4176       if (TryToFindDuplicates(S))
4177         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4178                      ReuseShuffleIndicies);
4179       return;
4180     }
4181     // Record the reuse of the tree node.  FIXME, currently this is only used to
4182     // properly draw the graph rather than for the actual vectorization.
4183     E->UserTreeIndices.push_back(UserTreeIdx);
4184     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4185                       << ".\n");
4186     return;
4187   }
4188 
4189   // Check that none of the instructions in the bundle are already in the tree.
4190   for (Value *V : VL) {
4191     auto *I = dyn_cast<Instruction>(V);
4192     if (!I)
4193       continue;
4194     if (getTreeEntry(I)) {
4195       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4196                         << ") is already in tree.\n");
4197       if (TryToFindDuplicates(S))
4198         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4199                      ReuseShuffleIndicies);
4200       return;
4201     }
4202   }
4203 
4204   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4205   for (Value *V : VL) {
4206     if (is_contained(UserIgnoreList, V)) {
4207       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4208       if (TryToFindDuplicates(S))
4209         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4210                      ReuseShuffleIndicies);
4211       return;
4212     }
4213   }
4214 
4215   // Check that all of the users of the scalars that we want to vectorize are
4216   // schedulable.
4217   auto *VL0 = cast<Instruction>(S.OpValue);
4218   BasicBlock *BB = VL0->getParent();
4219 
4220   if (!DT->isReachableFromEntry(BB)) {
4221     // Don't go into unreachable blocks. They may contain instructions with
4222     // dependency cycles which confuse the final scheduling.
4223     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4224     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4225     return;
4226   }
4227 
4228   // Check that every instruction appears once in this bundle.
4229   if (!TryToFindDuplicates(S))
4230     return;
4231 
4232   auto &BSRef = BlocksSchedules[BB];
4233   if (!BSRef)
4234     BSRef = std::make_unique<BlockScheduling>(BB);
4235 
4236   BlockScheduling &BS = *BSRef;
4237 
4238   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4239 #ifdef EXPENSIVE_CHECKS
4240   // Make sure we didn't break any internal invariants
4241   BS.verify();
4242 #endif
4243   if (!Bundle) {
4244     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4245     assert((!BS.getScheduleData(VL0) ||
4246             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4247            "tryScheduleBundle should cancelScheduling on failure");
4248     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4249                  ReuseShuffleIndicies);
4250     return;
4251   }
4252   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4253 
4254   unsigned ShuffleOrOp = S.isAltShuffle() ?
4255                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4256   switch (ShuffleOrOp) {
4257     case Instruction::PHI: {
4258       auto *PH = cast<PHINode>(VL0);
4259 
4260       // Check for terminator values (e.g. invoke).
4261       for (Value *V : VL)
4262         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4263           Instruction *Term = dyn_cast<Instruction>(Incoming);
4264           if (Term && Term->isTerminator()) {
4265             LLVM_DEBUG(dbgs()
4266                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4267             BS.cancelScheduling(VL, VL0);
4268             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4269                          ReuseShuffleIndicies);
4270             return;
4271           }
4272         }
4273 
4274       TreeEntry *TE =
4275           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4276       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4277 
4278       // Keeps the reordered operands to avoid code duplication.
4279       SmallVector<ValueList, 2> OperandsVec;
4280       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4281         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4282           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4283           TE->setOperand(I, Operands);
4284           OperandsVec.push_back(Operands);
4285           continue;
4286         }
4287         ValueList Operands;
4288         // Prepare the operand vector.
4289         for (Value *V : VL)
4290           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4291               PH->getIncomingBlock(I)));
4292         TE->setOperand(I, Operands);
4293         OperandsVec.push_back(Operands);
4294       }
4295       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4296         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4297       return;
4298     }
4299     case Instruction::ExtractValue:
4300     case Instruction::ExtractElement: {
4301       OrdersType CurrentOrder;
4302       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4303       if (Reuse) {
4304         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4305         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4306                      ReuseShuffleIndicies);
4307         // This is a special case, as it does not gather, but at the same time
4308         // we are not extending buildTree_rec() towards the operands.
4309         ValueList Op0;
4310         Op0.assign(VL.size(), VL0->getOperand(0));
4311         VectorizableTree.back()->setOperand(0, Op0);
4312         return;
4313       }
4314       if (!CurrentOrder.empty()) {
4315         LLVM_DEBUG({
4316           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4317                     "with order";
4318           for (unsigned Idx : CurrentOrder)
4319             dbgs() << " " << Idx;
4320           dbgs() << "\n";
4321         });
4322         fixupOrderingIndices(CurrentOrder);
4323         // Insert new order with initial value 0, if it does not exist,
4324         // otherwise return the iterator to the existing one.
4325         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4326                      ReuseShuffleIndicies, CurrentOrder);
4327         // This is a special case, as it does not gather, but at the same time
4328         // we are not extending buildTree_rec() towards the operands.
4329         ValueList Op0;
4330         Op0.assign(VL.size(), VL0->getOperand(0));
4331         VectorizableTree.back()->setOperand(0, Op0);
4332         return;
4333       }
4334       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4335       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4336                    ReuseShuffleIndicies);
4337       BS.cancelScheduling(VL, VL0);
4338       return;
4339     }
4340     case Instruction::InsertElement: {
4341       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4342 
4343       // Check that we have a buildvector and not a shuffle of 2 or more
4344       // different vectors.
4345       ValueSet SourceVectors;
4346       for (Value *V : VL) {
4347         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4348         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4349       }
4350 
4351       if (count_if(VL, [&SourceVectors](Value *V) {
4352             return !SourceVectors.contains(V);
4353           }) >= 2) {
4354         // Found 2nd source vector - cancel.
4355         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4356                              "different source vectors.\n");
4357         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4358         BS.cancelScheduling(VL, VL0);
4359         return;
4360       }
4361 
4362       auto OrdCompare = [](const std::pair<int, int> &P1,
4363                            const std::pair<int, int> &P2) {
4364         return P1.first > P2.first;
4365       };
4366       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4367                     decltype(OrdCompare)>
4368           Indices(OrdCompare);
4369       for (int I = 0, E = VL.size(); I < E; ++I) {
4370         unsigned Idx = *getInsertIndex(VL[I]);
4371         Indices.emplace(Idx, I);
4372       }
4373       OrdersType CurrentOrder(VL.size(), VL.size());
4374       bool IsIdentity = true;
4375       for (int I = 0, E = VL.size(); I < E; ++I) {
4376         CurrentOrder[Indices.top().second] = I;
4377         IsIdentity &= Indices.top().second == I;
4378         Indices.pop();
4379       }
4380       if (IsIdentity)
4381         CurrentOrder.clear();
4382       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4383                                    None, CurrentOrder);
4384       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4385 
4386       constexpr int NumOps = 2;
4387       ValueList VectorOperands[NumOps];
4388       for (int I = 0; I < NumOps; ++I) {
4389         for (Value *V : VL)
4390           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4391 
4392         TE->setOperand(I, VectorOperands[I]);
4393       }
4394       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4395       return;
4396     }
4397     case Instruction::Load: {
4398       // Check that a vectorized load would load the same memory as a scalar
4399       // load. For example, we don't want to vectorize loads that are smaller
4400       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4401       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4402       // from such a struct, we read/write packed bits disagreeing with the
4403       // unvectorized version.
4404       SmallVector<Value *> PointerOps;
4405       OrdersType CurrentOrder;
4406       TreeEntry *TE = nullptr;
4407       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4408                                 PointerOps)) {
4409       case LoadsState::Vectorize:
4410         if (CurrentOrder.empty()) {
4411           // Original loads are consecutive and does not require reordering.
4412           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4413                             ReuseShuffleIndicies);
4414           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4415         } else {
4416           fixupOrderingIndices(CurrentOrder);
4417           // Need to reorder.
4418           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4419                             ReuseShuffleIndicies, CurrentOrder);
4420           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4421         }
4422         TE->setOperandsInOrder();
4423         break;
4424       case LoadsState::ScatterVectorize:
4425         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4426         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4427                           UserTreeIdx, ReuseShuffleIndicies);
4428         TE->setOperandsInOrder();
4429         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4430         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4431         break;
4432       case LoadsState::Gather:
4433         BS.cancelScheduling(VL, VL0);
4434         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4435                      ReuseShuffleIndicies);
4436 #ifndef NDEBUG
4437         Type *ScalarTy = VL0->getType();
4438         if (DL->getTypeSizeInBits(ScalarTy) !=
4439             DL->getTypeAllocSizeInBits(ScalarTy))
4440           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4441         else if (any_of(VL, [](Value *V) {
4442                    return !cast<LoadInst>(V)->isSimple();
4443                  }))
4444           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4445         else
4446           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4447 #endif // NDEBUG
4448         break;
4449       }
4450       return;
4451     }
4452     case Instruction::ZExt:
4453     case Instruction::SExt:
4454     case Instruction::FPToUI:
4455     case Instruction::FPToSI:
4456     case Instruction::FPExt:
4457     case Instruction::PtrToInt:
4458     case Instruction::IntToPtr:
4459     case Instruction::SIToFP:
4460     case Instruction::UIToFP:
4461     case Instruction::Trunc:
4462     case Instruction::FPTrunc:
4463     case Instruction::BitCast: {
4464       Type *SrcTy = VL0->getOperand(0)->getType();
4465       for (Value *V : VL) {
4466         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4467         if (Ty != SrcTy || !isValidElementType(Ty)) {
4468           BS.cancelScheduling(VL, VL0);
4469           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4470                        ReuseShuffleIndicies);
4471           LLVM_DEBUG(dbgs()
4472                      << "SLP: Gathering casts with different src types.\n");
4473           return;
4474         }
4475       }
4476       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4477                                    ReuseShuffleIndicies);
4478       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4479 
4480       TE->setOperandsInOrder();
4481       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4482         ValueList Operands;
4483         // Prepare the operand vector.
4484         for (Value *V : VL)
4485           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4486 
4487         buildTree_rec(Operands, Depth + 1, {TE, i});
4488       }
4489       return;
4490     }
4491     case Instruction::ICmp:
4492     case Instruction::FCmp: {
4493       // Check that all of the compares have the same predicate.
4494       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4495       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4496       Type *ComparedTy = VL0->getOperand(0)->getType();
4497       for (Value *V : VL) {
4498         CmpInst *Cmp = cast<CmpInst>(V);
4499         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4500             Cmp->getOperand(0)->getType() != ComparedTy) {
4501           BS.cancelScheduling(VL, VL0);
4502           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4503                        ReuseShuffleIndicies);
4504           LLVM_DEBUG(dbgs()
4505                      << "SLP: Gathering cmp with different predicate.\n");
4506           return;
4507         }
4508       }
4509 
4510       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4511                                    ReuseShuffleIndicies);
4512       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4513 
4514       ValueList Left, Right;
4515       if (cast<CmpInst>(VL0)->isCommutative()) {
4516         // Commutative predicate - collect + sort operands of the instructions
4517         // so that each side is more likely to have the same opcode.
4518         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4519         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4520       } else {
4521         // Collect operands - commute if it uses the swapped predicate.
4522         for (Value *V : VL) {
4523           auto *Cmp = cast<CmpInst>(V);
4524           Value *LHS = Cmp->getOperand(0);
4525           Value *RHS = Cmp->getOperand(1);
4526           if (Cmp->getPredicate() != P0)
4527             std::swap(LHS, RHS);
4528           Left.push_back(LHS);
4529           Right.push_back(RHS);
4530         }
4531       }
4532       TE->setOperand(0, Left);
4533       TE->setOperand(1, Right);
4534       buildTree_rec(Left, Depth + 1, {TE, 0});
4535       buildTree_rec(Right, Depth + 1, {TE, 1});
4536       return;
4537     }
4538     case Instruction::Select:
4539     case Instruction::FNeg:
4540     case Instruction::Add:
4541     case Instruction::FAdd:
4542     case Instruction::Sub:
4543     case Instruction::FSub:
4544     case Instruction::Mul:
4545     case Instruction::FMul:
4546     case Instruction::UDiv:
4547     case Instruction::SDiv:
4548     case Instruction::FDiv:
4549     case Instruction::URem:
4550     case Instruction::SRem:
4551     case Instruction::FRem:
4552     case Instruction::Shl:
4553     case Instruction::LShr:
4554     case Instruction::AShr:
4555     case Instruction::And:
4556     case Instruction::Or:
4557     case Instruction::Xor: {
4558       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4559                                    ReuseShuffleIndicies);
4560       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4561 
4562       // Sort operands of the instructions so that each side is more likely to
4563       // have the same opcode.
4564       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4565         ValueList Left, Right;
4566         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4567         TE->setOperand(0, Left);
4568         TE->setOperand(1, Right);
4569         buildTree_rec(Left, Depth + 1, {TE, 0});
4570         buildTree_rec(Right, Depth + 1, {TE, 1});
4571         return;
4572       }
4573 
4574       TE->setOperandsInOrder();
4575       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4576         ValueList Operands;
4577         // Prepare the operand vector.
4578         for (Value *V : VL)
4579           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4580 
4581         buildTree_rec(Operands, Depth + 1, {TE, i});
4582       }
4583       return;
4584     }
4585     case Instruction::GetElementPtr: {
4586       // We don't combine GEPs with complicated (nested) indexing.
4587       for (Value *V : VL) {
4588         if (cast<Instruction>(V)->getNumOperands() != 2) {
4589           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4590           BS.cancelScheduling(VL, VL0);
4591           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4592                        ReuseShuffleIndicies);
4593           return;
4594         }
4595       }
4596 
4597       // We can't combine several GEPs into one vector if they operate on
4598       // different types.
4599       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4600       for (Value *V : VL) {
4601         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4602         if (Ty0 != CurTy) {
4603           LLVM_DEBUG(dbgs()
4604                      << "SLP: not-vectorizable GEP (different types).\n");
4605           BS.cancelScheduling(VL, VL0);
4606           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4607                        ReuseShuffleIndicies);
4608           return;
4609         }
4610       }
4611 
4612       // We don't combine GEPs with non-constant indexes.
4613       Type *Ty1 = VL0->getOperand(1)->getType();
4614       for (Value *V : VL) {
4615         auto Op = cast<Instruction>(V)->getOperand(1);
4616         if (!isa<ConstantInt>(Op) ||
4617             (Op->getType() != Ty1 &&
4618              Op->getType()->getScalarSizeInBits() >
4619                  DL->getIndexSizeInBits(
4620                      V->getType()->getPointerAddressSpace()))) {
4621           LLVM_DEBUG(dbgs()
4622                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4623           BS.cancelScheduling(VL, VL0);
4624           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4625                        ReuseShuffleIndicies);
4626           return;
4627         }
4628       }
4629 
4630       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4631                                    ReuseShuffleIndicies);
4632       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4633       SmallVector<ValueList, 2> Operands(2);
4634       // Prepare the operand vector for pointer operands.
4635       for (Value *V : VL)
4636         Operands.front().push_back(
4637             cast<GetElementPtrInst>(V)->getPointerOperand());
4638       TE->setOperand(0, Operands.front());
4639       // Need to cast all indices to the same type before vectorization to
4640       // avoid crash.
4641       // Required to be able to find correct matches between different gather
4642       // nodes and reuse the vectorized values rather than trying to gather them
4643       // again.
4644       int IndexIdx = 1;
4645       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4646       Type *Ty = all_of(VL,
4647                         [VL0Ty, IndexIdx](Value *V) {
4648                           return VL0Ty == cast<GetElementPtrInst>(V)
4649                                               ->getOperand(IndexIdx)
4650                                               ->getType();
4651                         })
4652                      ? VL0Ty
4653                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4654                                             ->getPointerOperandType()
4655                                             ->getScalarType());
4656       // Prepare the operand vector.
4657       for (Value *V : VL) {
4658         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4659         auto *CI = cast<ConstantInt>(Op);
4660         Operands.back().push_back(ConstantExpr::getIntegerCast(
4661             CI, Ty, CI->getValue().isSignBitSet()));
4662       }
4663       TE->setOperand(IndexIdx, Operands.back());
4664 
4665       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4666         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4667       return;
4668     }
4669     case Instruction::Store: {
4670       // Check if the stores are consecutive or if we need to swizzle them.
4671       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4672       // Avoid types that are padded when being allocated as scalars, while
4673       // being packed together in a vector (such as i1).
4674       if (DL->getTypeSizeInBits(ScalarTy) !=
4675           DL->getTypeAllocSizeInBits(ScalarTy)) {
4676         BS.cancelScheduling(VL, VL0);
4677         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4678                      ReuseShuffleIndicies);
4679         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4680         return;
4681       }
4682       // Make sure all stores in the bundle are simple - we can't vectorize
4683       // atomic or volatile stores.
4684       SmallVector<Value *, 4> PointerOps(VL.size());
4685       ValueList Operands(VL.size());
4686       auto POIter = PointerOps.begin();
4687       auto OIter = Operands.begin();
4688       for (Value *V : VL) {
4689         auto *SI = cast<StoreInst>(V);
4690         if (!SI->isSimple()) {
4691           BS.cancelScheduling(VL, VL0);
4692           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4693                        ReuseShuffleIndicies);
4694           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4695           return;
4696         }
4697         *POIter = SI->getPointerOperand();
4698         *OIter = SI->getValueOperand();
4699         ++POIter;
4700         ++OIter;
4701       }
4702 
4703       OrdersType CurrentOrder;
4704       // Check the order of pointer operands.
4705       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4706         Value *Ptr0;
4707         Value *PtrN;
4708         if (CurrentOrder.empty()) {
4709           Ptr0 = PointerOps.front();
4710           PtrN = PointerOps.back();
4711         } else {
4712           Ptr0 = PointerOps[CurrentOrder.front()];
4713           PtrN = PointerOps[CurrentOrder.back()];
4714         }
4715         Optional<int> Dist =
4716             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4717         // Check that the sorted pointer operands are consecutive.
4718         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4719           if (CurrentOrder.empty()) {
4720             // Original stores are consecutive and does not require reordering.
4721             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4722                                          UserTreeIdx, ReuseShuffleIndicies);
4723             TE->setOperandsInOrder();
4724             buildTree_rec(Operands, Depth + 1, {TE, 0});
4725             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4726           } else {
4727             fixupOrderingIndices(CurrentOrder);
4728             TreeEntry *TE =
4729                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4730                              ReuseShuffleIndicies, CurrentOrder);
4731             TE->setOperandsInOrder();
4732             buildTree_rec(Operands, Depth + 1, {TE, 0});
4733             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4734           }
4735           return;
4736         }
4737       }
4738 
4739       BS.cancelScheduling(VL, VL0);
4740       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4741                    ReuseShuffleIndicies);
4742       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4743       return;
4744     }
4745     case Instruction::Call: {
4746       // Check if the calls are all to the same vectorizable intrinsic or
4747       // library function.
4748       CallInst *CI = cast<CallInst>(VL0);
4749       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4750 
4751       VFShape Shape = VFShape::get(
4752           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4753           false /*HasGlobalPred*/);
4754       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4755 
4756       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4757         BS.cancelScheduling(VL, VL0);
4758         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4759                      ReuseShuffleIndicies);
4760         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4761         return;
4762       }
4763       Function *F = CI->getCalledFunction();
4764       unsigned NumArgs = CI->arg_size();
4765       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4766       for (unsigned j = 0; j != NumArgs; ++j)
4767         if (hasVectorInstrinsicScalarOpd(ID, j))
4768           ScalarArgs[j] = CI->getArgOperand(j);
4769       for (Value *V : VL) {
4770         CallInst *CI2 = dyn_cast<CallInst>(V);
4771         if (!CI2 || CI2->getCalledFunction() != F ||
4772             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4773             (VecFunc &&
4774              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4775             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4776           BS.cancelScheduling(VL, VL0);
4777           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4778                        ReuseShuffleIndicies);
4779           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4780                             << "\n");
4781           return;
4782         }
4783         // Some intrinsics have scalar arguments and should be same in order for
4784         // them to be vectorized.
4785         for (unsigned j = 0; j != NumArgs; ++j) {
4786           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4787             Value *A1J = CI2->getArgOperand(j);
4788             if (ScalarArgs[j] != A1J) {
4789               BS.cancelScheduling(VL, VL0);
4790               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4791                            ReuseShuffleIndicies);
4792               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4793                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4794                                 << "\n");
4795               return;
4796             }
4797           }
4798         }
4799         // Verify that the bundle operands are identical between the two calls.
4800         if (CI->hasOperandBundles() &&
4801             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4802                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4803                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4804           BS.cancelScheduling(VL, VL0);
4805           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4806                        ReuseShuffleIndicies);
4807           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4808                             << *CI << "!=" << *V << '\n');
4809           return;
4810         }
4811       }
4812 
4813       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4814                                    ReuseShuffleIndicies);
4815       TE->setOperandsInOrder();
4816       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4817         // For scalar operands no need to to create an entry since no need to
4818         // vectorize it.
4819         if (hasVectorInstrinsicScalarOpd(ID, i))
4820           continue;
4821         ValueList Operands;
4822         // Prepare the operand vector.
4823         for (Value *V : VL) {
4824           auto *CI2 = cast<CallInst>(V);
4825           Operands.push_back(CI2->getArgOperand(i));
4826         }
4827         buildTree_rec(Operands, Depth + 1, {TE, i});
4828       }
4829       return;
4830     }
4831     case Instruction::ShuffleVector: {
4832       // If this is not an alternate sequence of opcode like add-sub
4833       // then do not vectorize this instruction.
4834       if (!S.isAltShuffle()) {
4835         BS.cancelScheduling(VL, VL0);
4836         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4837                      ReuseShuffleIndicies);
4838         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4839         return;
4840       }
4841       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4842                                    ReuseShuffleIndicies);
4843       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4844 
4845       // Reorder operands if reordering would enable vectorization.
4846       auto *CI = dyn_cast<CmpInst>(VL0);
4847       if (isa<BinaryOperator>(VL0) || CI) {
4848         ValueList Left, Right;
4849         if (!CI || all_of(VL, [](Value *V) {
4850               return cast<CmpInst>(V)->isCommutative();
4851             })) {
4852           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4853         } else {
4854           CmpInst::Predicate P0 = CI->getPredicate();
4855           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4856           assert(P0 != AltP0 &&
4857                  "Expected different main/alternate predicates.");
4858           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4859           Value *BaseOp0 = VL0->getOperand(0);
4860           Value *BaseOp1 = VL0->getOperand(1);
4861           // Collect operands - commute if it uses the swapped predicate or
4862           // alternate operation.
4863           for (Value *V : VL) {
4864             auto *Cmp = cast<CmpInst>(V);
4865             Value *LHS = Cmp->getOperand(0);
4866             Value *RHS = Cmp->getOperand(1);
4867             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4868             if (P0 == AltP0Swapped) {
4869               if (CI != Cmp && S.AltOp != Cmp &&
4870                   ((P0 == CurrentPred &&
4871                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4872                    (AltP0 == CurrentPred &&
4873                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4874                 std::swap(LHS, RHS);
4875             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4876               std::swap(LHS, RHS);
4877             }
4878             Left.push_back(LHS);
4879             Right.push_back(RHS);
4880           }
4881         }
4882         TE->setOperand(0, Left);
4883         TE->setOperand(1, Right);
4884         buildTree_rec(Left, Depth + 1, {TE, 0});
4885         buildTree_rec(Right, Depth + 1, {TE, 1});
4886         return;
4887       }
4888 
4889       TE->setOperandsInOrder();
4890       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4891         ValueList Operands;
4892         // Prepare the operand vector.
4893         for (Value *V : VL)
4894           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4895 
4896         buildTree_rec(Operands, Depth + 1, {TE, i});
4897       }
4898       return;
4899     }
4900     default:
4901       BS.cancelScheduling(VL, VL0);
4902       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4903                    ReuseShuffleIndicies);
4904       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4905       return;
4906   }
4907 }
4908 
4909 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4910   unsigned N = 1;
4911   Type *EltTy = T;
4912 
4913   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4914          isa<VectorType>(EltTy)) {
4915     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4916       // Check that struct is homogeneous.
4917       for (const auto *Ty : ST->elements())
4918         if (Ty != *ST->element_begin())
4919           return 0;
4920       N *= ST->getNumElements();
4921       EltTy = *ST->element_begin();
4922     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4923       N *= AT->getNumElements();
4924       EltTy = AT->getElementType();
4925     } else {
4926       auto *VT = cast<FixedVectorType>(EltTy);
4927       N *= VT->getNumElements();
4928       EltTy = VT->getElementType();
4929     }
4930   }
4931 
4932   if (!isValidElementType(EltTy))
4933     return 0;
4934   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4935   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4936     return 0;
4937   return N;
4938 }
4939 
4940 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4941                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4942   const auto *It = find_if(VL, [](Value *V) {
4943     return isa<ExtractElementInst, ExtractValueInst>(V);
4944   });
4945   assert(It != VL.end() && "Expected at least one extract instruction.");
4946   auto *E0 = cast<Instruction>(*It);
4947   assert(all_of(VL,
4948                 [](Value *V) {
4949                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4950                       V);
4951                 }) &&
4952          "Invalid opcode");
4953   // Check if all of the extracts come from the same vector and from the
4954   // correct offset.
4955   Value *Vec = E0->getOperand(0);
4956 
4957   CurrentOrder.clear();
4958 
4959   // We have to extract from a vector/aggregate with the same number of elements.
4960   unsigned NElts;
4961   if (E0->getOpcode() == Instruction::ExtractValue) {
4962     const DataLayout &DL = E0->getModule()->getDataLayout();
4963     NElts = canMapToVector(Vec->getType(), DL);
4964     if (!NElts)
4965       return false;
4966     // Check if load can be rewritten as load of vector.
4967     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4968     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4969       return false;
4970   } else {
4971     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4972   }
4973 
4974   if (NElts != VL.size())
4975     return false;
4976 
4977   // Check that all of the indices extract from the correct offset.
4978   bool ShouldKeepOrder = true;
4979   unsigned E = VL.size();
4980   // Assign to all items the initial value E + 1 so we can check if the extract
4981   // instruction index was used already.
4982   // Also, later we can check that all the indices are used and we have a
4983   // consecutive access in the extract instructions, by checking that no
4984   // element of CurrentOrder still has value E + 1.
4985   CurrentOrder.assign(E, E);
4986   unsigned I = 0;
4987   for (; I < E; ++I) {
4988     auto *Inst = dyn_cast<Instruction>(VL[I]);
4989     if (!Inst)
4990       continue;
4991     if (Inst->getOperand(0) != Vec)
4992       break;
4993     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4994       if (isa<UndefValue>(EE->getIndexOperand()))
4995         continue;
4996     Optional<unsigned> Idx = getExtractIndex(Inst);
4997     if (!Idx)
4998       break;
4999     const unsigned ExtIdx = *Idx;
5000     if (ExtIdx != I) {
5001       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
5002         break;
5003       ShouldKeepOrder = false;
5004       CurrentOrder[ExtIdx] = I;
5005     } else {
5006       if (CurrentOrder[I] != E)
5007         break;
5008       CurrentOrder[I] = I;
5009     }
5010   }
5011   if (I < E) {
5012     CurrentOrder.clear();
5013     return false;
5014   }
5015   if (ShouldKeepOrder)
5016     CurrentOrder.clear();
5017 
5018   return ShouldKeepOrder;
5019 }
5020 
5021 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
5022                                     ArrayRef<Value *> VectorizedVals) const {
5023   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
5024          all_of(I->users(), [this](User *U) {
5025            return ScalarToTreeEntry.count(U) > 0 ||
5026                   isVectorLikeInstWithConstOps(U) ||
5027                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
5028          });
5029 }
5030 
5031 static std::pair<InstructionCost, InstructionCost>
5032 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
5033                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
5034   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5035 
5036   // Calculate the cost of the scalar and vector calls.
5037   SmallVector<Type *, 4> VecTys;
5038   for (Use &Arg : CI->args())
5039     VecTys.push_back(
5040         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
5041   FastMathFlags FMF;
5042   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
5043     FMF = FPCI->getFastMathFlags();
5044   SmallVector<const Value *> Arguments(CI->args());
5045   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
5046                                     dyn_cast<IntrinsicInst>(CI));
5047   auto IntrinsicCost =
5048     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
5049 
5050   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
5051                                      VecTy->getNumElements())),
5052                             false /*HasGlobalPred*/);
5053   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5054   auto LibCost = IntrinsicCost;
5055   if (!CI->isNoBuiltin() && VecFunc) {
5056     // Calculate the cost of the vector library call.
5057     // If the corresponding vector call is cheaper, return its cost.
5058     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5059                                     TTI::TCK_RecipThroughput);
5060   }
5061   return {IntrinsicCost, LibCost};
5062 }
5063 
5064 /// Compute the cost of creating a vector of type \p VecTy containing the
5065 /// extracted values from \p VL.
5066 static InstructionCost
5067 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5068                    TargetTransformInfo::ShuffleKind ShuffleKind,
5069                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5070   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5071 
5072   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5073       VecTy->getNumElements() < NumOfParts)
5074     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5075 
5076   bool AllConsecutive = true;
5077   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5078   unsigned Idx = -1;
5079   InstructionCost Cost = 0;
5080 
5081   // Process extracts in blocks of EltsPerVector to check if the source vector
5082   // operand can be re-used directly. If not, add the cost of creating a shuffle
5083   // to extract the values into a vector register.
5084   for (auto *V : VL) {
5085     ++Idx;
5086 
5087     // Need to exclude undefs from analysis.
5088     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5089       continue;
5090 
5091     // Reached the start of a new vector registers.
5092     if (Idx % EltsPerVector == 0) {
5093       AllConsecutive = true;
5094       continue;
5095     }
5096 
5097     // Check all extracts for a vector register on the target directly
5098     // extract values in order.
5099     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5100     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5101       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5102       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5103                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5104     }
5105 
5106     if (AllConsecutive)
5107       continue;
5108 
5109     // Skip all indices, except for the last index per vector block.
5110     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5111       continue;
5112 
5113     // If we have a series of extracts which are not consecutive and hence
5114     // cannot re-use the source vector register directly, compute the shuffle
5115     // cost to extract the a vector with EltsPerVector elements.
5116     Cost += TTI.getShuffleCost(
5117         TargetTransformInfo::SK_PermuteSingleSrc,
5118         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5119   }
5120   return Cost;
5121 }
5122 
5123 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5124 /// operations operands.
5125 static void
5126 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5127                       ArrayRef<int> ReusesIndices,
5128                       const function_ref<bool(Instruction *)> IsAltOp,
5129                       SmallVectorImpl<int> &Mask,
5130                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5131                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5132   unsigned Sz = VL.size();
5133   Mask.assign(Sz, UndefMaskElem);
5134   SmallVector<int> OrderMask;
5135   if (!ReorderIndices.empty())
5136     inversePermutation(ReorderIndices, OrderMask);
5137   for (unsigned I = 0; I < Sz; ++I) {
5138     unsigned Idx = I;
5139     if (!ReorderIndices.empty())
5140       Idx = OrderMask[I];
5141     auto *OpInst = cast<Instruction>(VL[Idx]);
5142     if (IsAltOp(OpInst)) {
5143       Mask[I] = Sz + Idx;
5144       if (AltScalars)
5145         AltScalars->push_back(OpInst);
5146     } else {
5147       Mask[I] = Idx;
5148       if (OpScalars)
5149         OpScalars->push_back(OpInst);
5150     }
5151   }
5152   if (!ReusesIndices.empty()) {
5153     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5154     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5155       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5156     });
5157     Mask.swap(NewMask);
5158   }
5159 }
5160 
5161 /// Checks if the specified instruction \p I is an alternate operation for the
5162 /// given \p MainOp and \p AltOp instructions.
5163 static bool isAlternateInstruction(const Instruction *I,
5164                                    const Instruction *MainOp,
5165                                    const Instruction *AltOp) {
5166   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5167     auto *AltCI0 = cast<CmpInst>(AltOp);
5168     auto *CI = cast<CmpInst>(I);
5169     CmpInst::Predicate P0 = CI0->getPredicate();
5170     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5171     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5172     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5173     CmpInst::Predicate CurrentPred = CI->getPredicate();
5174     if (P0 == AltP0Swapped)
5175       return I == AltCI0 ||
5176              (I != MainOp &&
5177               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5178                                    CI->getOperand(0), CI->getOperand(1)));
5179     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5180   }
5181   return I->getOpcode() == AltOp->getOpcode();
5182 }
5183 
5184 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5185                                       ArrayRef<Value *> VectorizedVals) {
5186   ArrayRef<Value*> VL = E->Scalars;
5187 
5188   Type *ScalarTy = VL[0]->getType();
5189   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5190     ScalarTy = SI->getValueOperand()->getType();
5191   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5192     ScalarTy = CI->getOperand(0)->getType();
5193   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5194     ScalarTy = IE->getOperand(1)->getType();
5195   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5196   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5197 
5198   // If we have computed a smaller type for the expression, update VecTy so
5199   // that the costs will be accurate.
5200   if (MinBWs.count(VL[0]))
5201     VecTy = FixedVectorType::get(
5202         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5203   unsigned EntryVF = E->getVectorFactor();
5204   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5205 
5206   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5207   // FIXME: it tries to fix a problem with MSVC buildbots.
5208   TargetTransformInfo &TTIRef = *TTI;
5209   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5210                                VectorizedVals, E](InstructionCost &Cost) {
5211     DenseMap<Value *, int> ExtractVectorsTys;
5212     SmallPtrSet<Value *, 4> CheckedExtracts;
5213     for (auto *V : VL) {
5214       if (isa<UndefValue>(V))
5215         continue;
5216       // If all users of instruction are going to be vectorized and this
5217       // instruction itself is not going to be vectorized, consider this
5218       // instruction as dead and remove its cost from the final cost of the
5219       // vectorized tree.
5220       // Also, avoid adjusting the cost for extractelements with multiple uses
5221       // in different graph entries.
5222       const TreeEntry *VE = getTreeEntry(V);
5223       if (!CheckedExtracts.insert(V).second ||
5224           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5225           (VE && VE != E))
5226         continue;
5227       auto *EE = cast<ExtractElementInst>(V);
5228       Optional<unsigned> EEIdx = getExtractIndex(EE);
5229       if (!EEIdx)
5230         continue;
5231       unsigned Idx = *EEIdx;
5232       if (TTIRef.getNumberOfParts(VecTy) !=
5233           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5234         auto It =
5235             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5236         It->getSecond() = std::min<int>(It->second, Idx);
5237       }
5238       // Take credit for instruction that will become dead.
5239       if (EE->hasOneUse()) {
5240         Instruction *Ext = EE->user_back();
5241         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5242             all_of(Ext->users(),
5243                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5244           // Use getExtractWithExtendCost() to calculate the cost of
5245           // extractelement/ext pair.
5246           Cost -=
5247               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5248                                               EE->getVectorOperandType(), Idx);
5249           // Add back the cost of s|zext which is subtracted separately.
5250           Cost += TTIRef.getCastInstrCost(
5251               Ext->getOpcode(), Ext->getType(), EE->getType(),
5252               TTI::getCastContextHint(Ext), CostKind, Ext);
5253           continue;
5254         }
5255       }
5256       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5257                                         EE->getVectorOperandType(), Idx);
5258     }
5259     // Add a cost for subvector extracts/inserts if required.
5260     for (const auto &Data : ExtractVectorsTys) {
5261       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5262       unsigned NumElts = VecTy->getNumElements();
5263       if (Data.second % NumElts == 0)
5264         continue;
5265       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5266         unsigned Idx = (Data.second / NumElts) * NumElts;
5267         unsigned EENumElts = EEVTy->getNumElements();
5268         if (Idx + NumElts <= EENumElts) {
5269           Cost +=
5270               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5271                                     EEVTy, None, Idx, VecTy);
5272         } else {
5273           // Need to round up the subvector type vectorization factor to avoid a
5274           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5275           // <= EENumElts.
5276           auto *SubVT =
5277               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5278           Cost +=
5279               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5280                                     EEVTy, None, Idx, SubVT);
5281         }
5282       } else {
5283         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5284                                       VecTy, None, 0, EEVTy);
5285       }
5286     }
5287   };
5288   if (E->State == TreeEntry::NeedToGather) {
5289     if (allConstant(VL))
5290       return 0;
5291     if (isa<InsertElementInst>(VL[0]))
5292       return InstructionCost::getInvalid();
5293     SmallVector<int> Mask;
5294     SmallVector<const TreeEntry *> Entries;
5295     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5296         isGatherShuffledEntry(E, Mask, Entries);
5297     if (Shuffle.hasValue()) {
5298       InstructionCost GatherCost = 0;
5299       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5300         // Perfect match in the graph, will reuse the previously vectorized
5301         // node. Cost is 0.
5302         LLVM_DEBUG(
5303             dbgs()
5304             << "SLP: perfect diamond match for gather bundle that starts with "
5305             << *VL.front() << ".\n");
5306         if (NeedToShuffleReuses)
5307           GatherCost =
5308               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5309                                   FinalVecTy, E->ReuseShuffleIndices);
5310       } else {
5311         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5312                           << " entries for bundle that starts with "
5313                           << *VL.front() << ".\n");
5314         // Detected that instead of gather we can emit a shuffle of single/two
5315         // previously vectorized nodes. Add the cost of the permutation rather
5316         // than gather.
5317         ::addMask(Mask, E->ReuseShuffleIndices);
5318         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5319       }
5320       return GatherCost;
5321     }
5322     if ((E->getOpcode() == Instruction::ExtractElement ||
5323          all_of(E->Scalars,
5324                 [](Value *V) {
5325                   return isa<ExtractElementInst, UndefValue>(V);
5326                 })) &&
5327         allSameType(VL)) {
5328       // Check that gather of extractelements can be represented as just a
5329       // shuffle of a single/two vectors the scalars are extracted from.
5330       SmallVector<int> Mask;
5331       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5332           isFixedVectorShuffle(VL, Mask);
5333       if (ShuffleKind.hasValue()) {
5334         // Found the bunch of extractelement instructions that must be gathered
5335         // into a vector and can be represented as a permutation elements in a
5336         // single input vector or of 2 input vectors.
5337         InstructionCost Cost =
5338             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5339         AdjustExtractsCost(Cost);
5340         if (NeedToShuffleReuses)
5341           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5342                                       FinalVecTy, E->ReuseShuffleIndices);
5343         return Cost;
5344       }
5345     }
5346     if (isSplat(VL)) {
5347       // Found the broadcasting of the single scalar, calculate the cost as the
5348       // broadcast.
5349       assert(VecTy == FinalVecTy &&
5350              "No reused scalars expected for broadcast.");
5351       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5352                                  /*Mask=*/None, /*Index=*/0,
5353                                  /*SubTp=*/nullptr, /*Args=*/VL);
5354     }
5355     InstructionCost ReuseShuffleCost = 0;
5356     if (NeedToShuffleReuses)
5357       ReuseShuffleCost = TTI->getShuffleCost(
5358           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5359     // Improve gather cost for gather of loads, if we can group some of the
5360     // loads into vector loads.
5361     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5362         !E->isAltShuffle()) {
5363       BoUpSLP::ValueSet VectorizedLoads;
5364       unsigned StartIdx = 0;
5365       unsigned VF = VL.size() / 2;
5366       unsigned VectorizedCnt = 0;
5367       unsigned ScatterVectorizeCnt = 0;
5368       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5369       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5370         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5371              Cnt += VF) {
5372           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5373           if (!VectorizedLoads.count(Slice.front()) &&
5374               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5375             SmallVector<Value *> PointerOps;
5376             OrdersType CurrentOrder;
5377             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5378                                               *SE, CurrentOrder, PointerOps);
5379             switch (LS) {
5380             case LoadsState::Vectorize:
5381             case LoadsState::ScatterVectorize:
5382               // Mark the vectorized loads so that we don't vectorize them
5383               // again.
5384               if (LS == LoadsState::Vectorize)
5385                 ++VectorizedCnt;
5386               else
5387                 ++ScatterVectorizeCnt;
5388               VectorizedLoads.insert(Slice.begin(), Slice.end());
5389               // If we vectorized initial block, no need to try to vectorize it
5390               // again.
5391               if (Cnt == StartIdx)
5392                 StartIdx += VF;
5393               break;
5394             case LoadsState::Gather:
5395               break;
5396             }
5397           }
5398         }
5399         // Check if the whole array was vectorized already - exit.
5400         if (StartIdx >= VL.size())
5401           break;
5402         // Found vectorizable parts - exit.
5403         if (!VectorizedLoads.empty())
5404           break;
5405       }
5406       if (!VectorizedLoads.empty()) {
5407         InstructionCost GatherCost = 0;
5408         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5409         bool NeedInsertSubvectorAnalysis =
5410             !NumParts || (VL.size() / VF) > NumParts;
5411         // Get the cost for gathered loads.
5412         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5413           if (VectorizedLoads.contains(VL[I]))
5414             continue;
5415           GatherCost += getGatherCost(VL.slice(I, VF));
5416         }
5417         // The cost for vectorized loads.
5418         InstructionCost ScalarsCost = 0;
5419         for (Value *V : VectorizedLoads) {
5420           auto *LI = cast<LoadInst>(V);
5421           ScalarsCost += TTI->getMemoryOpCost(
5422               Instruction::Load, LI->getType(), LI->getAlign(),
5423               LI->getPointerAddressSpace(), CostKind, LI);
5424         }
5425         auto *LI = cast<LoadInst>(E->getMainOp());
5426         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5427         Align Alignment = LI->getAlign();
5428         GatherCost +=
5429             VectorizedCnt *
5430             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5431                                  LI->getPointerAddressSpace(), CostKind, LI);
5432         GatherCost += ScatterVectorizeCnt *
5433                       TTI->getGatherScatterOpCost(
5434                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5435                           /*VariableMask=*/false, Alignment, CostKind, LI);
5436         if (NeedInsertSubvectorAnalysis) {
5437           // Add the cost for the subvectors insert.
5438           for (int I = VF, E = VL.size(); I < E; I += VF)
5439             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5440                                               None, I, LoadTy);
5441         }
5442         return ReuseShuffleCost + GatherCost - ScalarsCost;
5443       }
5444     }
5445     return ReuseShuffleCost + getGatherCost(VL);
5446   }
5447   InstructionCost CommonCost = 0;
5448   SmallVector<int> Mask;
5449   if (!E->ReorderIndices.empty()) {
5450     SmallVector<int> NewMask;
5451     if (E->getOpcode() == Instruction::Store) {
5452       // For stores the order is actually a mask.
5453       NewMask.resize(E->ReorderIndices.size());
5454       copy(E->ReorderIndices, NewMask.begin());
5455     } else {
5456       inversePermutation(E->ReorderIndices, NewMask);
5457     }
5458     ::addMask(Mask, NewMask);
5459   }
5460   if (NeedToShuffleReuses)
5461     ::addMask(Mask, E->ReuseShuffleIndices);
5462   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5463     CommonCost =
5464         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5465   assert((E->State == TreeEntry::Vectorize ||
5466           E->State == TreeEntry::ScatterVectorize) &&
5467          "Unhandled state");
5468   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5469   Instruction *VL0 = E->getMainOp();
5470   unsigned ShuffleOrOp =
5471       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5472   switch (ShuffleOrOp) {
5473     case Instruction::PHI:
5474       return 0;
5475 
5476     case Instruction::ExtractValue:
5477     case Instruction::ExtractElement: {
5478       // The common cost of removal ExtractElement/ExtractValue instructions +
5479       // the cost of shuffles, if required to resuffle the original vector.
5480       if (NeedToShuffleReuses) {
5481         unsigned Idx = 0;
5482         for (unsigned I : E->ReuseShuffleIndices) {
5483           if (ShuffleOrOp == Instruction::ExtractElement) {
5484             auto *EE = cast<ExtractElementInst>(VL[I]);
5485             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5486                                                   EE->getVectorOperandType(),
5487                                                   *getExtractIndex(EE));
5488           } else {
5489             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5490                                                   VecTy, Idx);
5491             ++Idx;
5492           }
5493         }
5494         Idx = EntryVF;
5495         for (Value *V : VL) {
5496           if (ShuffleOrOp == Instruction::ExtractElement) {
5497             auto *EE = cast<ExtractElementInst>(V);
5498             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5499                                                   EE->getVectorOperandType(),
5500                                                   *getExtractIndex(EE));
5501           } else {
5502             --Idx;
5503             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5504                                                   VecTy, Idx);
5505           }
5506         }
5507       }
5508       if (ShuffleOrOp == Instruction::ExtractValue) {
5509         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5510           auto *EI = cast<Instruction>(VL[I]);
5511           // Take credit for instruction that will become dead.
5512           if (EI->hasOneUse()) {
5513             Instruction *Ext = EI->user_back();
5514             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5515                 all_of(Ext->users(),
5516                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5517               // Use getExtractWithExtendCost() to calculate the cost of
5518               // extractelement/ext pair.
5519               CommonCost -= TTI->getExtractWithExtendCost(
5520                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5521               // Add back the cost of s|zext which is subtracted separately.
5522               CommonCost += TTI->getCastInstrCost(
5523                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5524                   TTI::getCastContextHint(Ext), CostKind, Ext);
5525               continue;
5526             }
5527           }
5528           CommonCost -=
5529               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5530         }
5531       } else {
5532         AdjustExtractsCost(CommonCost);
5533       }
5534       return CommonCost;
5535     }
5536     case Instruction::InsertElement: {
5537       assert(E->ReuseShuffleIndices.empty() &&
5538              "Unique insertelements only are expected.");
5539       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5540 
5541       unsigned const NumElts = SrcVecTy->getNumElements();
5542       unsigned const NumScalars = VL.size();
5543       APInt DemandedElts = APInt::getZero(NumElts);
5544       // TODO: Add support for Instruction::InsertValue.
5545       SmallVector<int> Mask;
5546       if (!E->ReorderIndices.empty()) {
5547         inversePermutation(E->ReorderIndices, Mask);
5548         Mask.append(NumElts - NumScalars, UndefMaskElem);
5549       } else {
5550         Mask.assign(NumElts, UndefMaskElem);
5551         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5552       }
5553       unsigned Offset = *getInsertIndex(VL0);
5554       bool IsIdentity = true;
5555       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5556       Mask.swap(PrevMask);
5557       for (unsigned I = 0; I < NumScalars; ++I) {
5558         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5559         DemandedElts.setBit(InsertIdx);
5560         IsIdentity &= InsertIdx - Offset == I;
5561         Mask[InsertIdx - Offset] = I;
5562       }
5563       assert(Offset < NumElts && "Failed to find vector index offset");
5564 
5565       InstructionCost Cost = 0;
5566       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5567                                             /*Insert*/ true, /*Extract*/ false);
5568 
5569       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5570         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5571         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5572         Cost += TTI->getShuffleCost(
5573             TargetTransformInfo::SK_PermuteSingleSrc,
5574             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5575       } else if (!IsIdentity) {
5576         auto *FirstInsert =
5577             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5578               return !is_contained(E->Scalars,
5579                                    cast<Instruction>(V)->getOperand(0));
5580             }));
5581         if (isUndefVector(FirstInsert->getOperand(0))) {
5582           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5583         } else {
5584           SmallVector<int> InsertMask(NumElts);
5585           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5586           for (unsigned I = 0; I < NumElts; I++) {
5587             if (Mask[I] != UndefMaskElem)
5588               InsertMask[Offset + I] = NumElts + I;
5589           }
5590           Cost +=
5591               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5592         }
5593       }
5594 
5595       return Cost;
5596     }
5597     case Instruction::ZExt:
5598     case Instruction::SExt:
5599     case Instruction::FPToUI:
5600     case Instruction::FPToSI:
5601     case Instruction::FPExt:
5602     case Instruction::PtrToInt:
5603     case Instruction::IntToPtr:
5604     case Instruction::SIToFP:
5605     case Instruction::UIToFP:
5606     case Instruction::Trunc:
5607     case Instruction::FPTrunc:
5608     case Instruction::BitCast: {
5609       Type *SrcTy = VL0->getOperand(0)->getType();
5610       InstructionCost ScalarEltCost =
5611           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5612                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5613       if (NeedToShuffleReuses) {
5614         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5615       }
5616 
5617       // Calculate the cost of this instruction.
5618       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5619 
5620       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5621       InstructionCost VecCost = 0;
5622       // Check if the values are candidates to demote.
5623       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5624         VecCost = CommonCost + TTI->getCastInstrCost(
5625                                    E->getOpcode(), VecTy, SrcVecTy,
5626                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5627       }
5628       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5629       return VecCost - ScalarCost;
5630     }
5631     case Instruction::FCmp:
5632     case Instruction::ICmp:
5633     case Instruction::Select: {
5634       // Calculate the cost of this instruction.
5635       InstructionCost ScalarEltCost =
5636           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5637                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5638       if (NeedToShuffleReuses) {
5639         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5640       }
5641       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5642       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5643 
5644       // Check if all entries in VL are either compares or selects with compares
5645       // as condition that have the same predicates.
5646       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5647       bool First = true;
5648       for (auto *V : VL) {
5649         CmpInst::Predicate CurrentPred;
5650         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5651         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5652              !match(V, MatchCmp)) ||
5653             (!First && VecPred != CurrentPred)) {
5654           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5655           break;
5656         }
5657         First = false;
5658         VecPred = CurrentPred;
5659       }
5660 
5661       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5662           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5663       // Check if it is possible and profitable to use min/max for selects in
5664       // VL.
5665       //
5666       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5667       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5668         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5669                                           {VecTy, VecTy});
5670         InstructionCost IntrinsicCost =
5671             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5672         // If the selects are the only uses of the compares, they will be dead
5673         // and we can adjust the cost by removing their cost.
5674         if (IntrinsicAndUse.second)
5675           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5676                                                    MaskTy, VecPred, CostKind);
5677         VecCost = std::min(VecCost, IntrinsicCost);
5678       }
5679       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5680       return CommonCost + VecCost - ScalarCost;
5681     }
5682     case Instruction::FNeg:
5683     case Instruction::Add:
5684     case Instruction::FAdd:
5685     case Instruction::Sub:
5686     case Instruction::FSub:
5687     case Instruction::Mul:
5688     case Instruction::FMul:
5689     case Instruction::UDiv:
5690     case Instruction::SDiv:
5691     case Instruction::FDiv:
5692     case Instruction::URem:
5693     case Instruction::SRem:
5694     case Instruction::FRem:
5695     case Instruction::Shl:
5696     case Instruction::LShr:
5697     case Instruction::AShr:
5698     case Instruction::And:
5699     case Instruction::Or:
5700     case Instruction::Xor: {
5701       // Certain instructions can be cheaper to vectorize if they have a
5702       // constant second vector operand.
5703       TargetTransformInfo::OperandValueKind Op1VK =
5704           TargetTransformInfo::OK_AnyValue;
5705       TargetTransformInfo::OperandValueKind Op2VK =
5706           TargetTransformInfo::OK_UniformConstantValue;
5707       TargetTransformInfo::OperandValueProperties Op1VP =
5708           TargetTransformInfo::OP_None;
5709       TargetTransformInfo::OperandValueProperties Op2VP =
5710           TargetTransformInfo::OP_PowerOf2;
5711 
5712       // If all operands are exactly the same ConstantInt then set the
5713       // operand kind to OK_UniformConstantValue.
5714       // If instead not all operands are constants, then set the operand kind
5715       // to OK_AnyValue. If all operands are constants but not the same,
5716       // then set the operand kind to OK_NonUniformConstantValue.
5717       ConstantInt *CInt0 = nullptr;
5718       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5719         const Instruction *I = cast<Instruction>(VL[i]);
5720         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5721         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5722         if (!CInt) {
5723           Op2VK = TargetTransformInfo::OK_AnyValue;
5724           Op2VP = TargetTransformInfo::OP_None;
5725           break;
5726         }
5727         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5728             !CInt->getValue().isPowerOf2())
5729           Op2VP = TargetTransformInfo::OP_None;
5730         if (i == 0) {
5731           CInt0 = CInt;
5732           continue;
5733         }
5734         if (CInt0 != CInt)
5735           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5736       }
5737 
5738       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5739       InstructionCost ScalarEltCost =
5740           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5741                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5742       if (NeedToShuffleReuses) {
5743         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5744       }
5745       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5746       InstructionCost VecCost =
5747           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5748                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5749       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5750       return CommonCost + VecCost - ScalarCost;
5751     }
5752     case Instruction::GetElementPtr: {
5753       TargetTransformInfo::OperandValueKind Op1VK =
5754           TargetTransformInfo::OK_AnyValue;
5755       TargetTransformInfo::OperandValueKind Op2VK =
5756           TargetTransformInfo::OK_UniformConstantValue;
5757 
5758       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5759           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5760       if (NeedToShuffleReuses) {
5761         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5762       }
5763       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5764       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5765           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5766       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5767       return CommonCost + VecCost - ScalarCost;
5768     }
5769     case Instruction::Load: {
5770       // Cost of wide load - cost of scalar loads.
5771       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5772       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5773           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5774       if (NeedToShuffleReuses) {
5775         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5776       }
5777       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5778       InstructionCost VecLdCost;
5779       if (E->State == TreeEntry::Vectorize) {
5780         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5781                                          CostKind, VL0);
5782       } else {
5783         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5784         Align CommonAlignment = Alignment;
5785         for (Value *V : VL)
5786           CommonAlignment =
5787               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5788         VecLdCost = TTI->getGatherScatterOpCost(
5789             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5790             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5791       }
5792       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5793       return CommonCost + VecLdCost - ScalarLdCost;
5794     }
5795     case Instruction::Store: {
5796       // We know that we can merge the stores. Calculate the cost.
5797       bool IsReorder = !E->ReorderIndices.empty();
5798       auto *SI =
5799           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5800       Align Alignment = SI->getAlign();
5801       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5802           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5803       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5804       InstructionCost VecStCost = TTI->getMemoryOpCost(
5805           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5806       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5807       return CommonCost + VecStCost - ScalarStCost;
5808     }
5809     case Instruction::Call: {
5810       CallInst *CI = cast<CallInst>(VL0);
5811       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5812 
5813       // Calculate the cost of the scalar and vector calls.
5814       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5815       InstructionCost ScalarEltCost =
5816           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5817       if (NeedToShuffleReuses) {
5818         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5819       }
5820       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5821 
5822       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5823       InstructionCost VecCallCost =
5824           std::min(VecCallCosts.first, VecCallCosts.second);
5825 
5826       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5827                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5828                         << " for " << *CI << "\n");
5829 
5830       return CommonCost + VecCallCost - ScalarCallCost;
5831     }
5832     case Instruction::ShuffleVector: {
5833       assert(E->isAltShuffle() &&
5834              ((Instruction::isBinaryOp(E->getOpcode()) &&
5835                Instruction::isBinaryOp(E->getAltOpcode())) ||
5836               (Instruction::isCast(E->getOpcode()) &&
5837                Instruction::isCast(E->getAltOpcode())) ||
5838               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5839              "Invalid Shuffle Vector Operand");
5840       InstructionCost ScalarCost = 0;
5841       if (NeedToShuffleReuses) {
5842         for (unsigned Idx : E->ReuseShuffleIndices) {
5843           Instruction *I = cast<Instruction>(VL[Idx]);
5844           CommonCost -= TTI->getInstructionCost(I, CostKind);
5845         }
5846         for (Value *V : VL) {
5847           Instruction *I = cast<Instruction>(V);
5848           CommonCost += TTI->getInstructionCost(I, CostKind);
5849         }
5850       }
5851       for (Value *V : VL) {
5852         Instruction *I = cast<Instruction>(V);
5853         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5854         ScalarCost += TTI->getInstructionCost(I, CostKind);
5855       }
5856       // VecCost is equal to sum of the cost of creating 2 vectors
5857       // and the cost of creating shuffle.
5858       InstructionCost VecCost = 0;
5859       // Try to find the previous shuffle node with the same operands and same
5860       // main/alternate ops.
5861       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5862         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5863           if (TE.get() == E)
5864             break;
5865           if (TE->isAltShuffle() &&
5866               ((TE->getOpcode() == E->getOpcode() &&
5867                 TE->getAltOpcode() == E->getAltOpcode()) ||
5868                (TE->getOpcode() == E->getAltOpcode() &&
5869                 TE->getAltOpcode() == E->getOpcode())) &&
5870               TE->hasEqualOperands(*E))
5871             return true;
5872         }
5873         return false;
5874       };
5875       if (TryFindNodeWithEqualOperands()) {
5876         LLVM_DEBUG({
5877           dbgs() << "SLP: diamond match for alternate node found.\n";
5878           E->dump();
5879         });
5880         // No need to add new vector costs here since we're going to reuse
5881         // same main/alternate vector ops, just do different shuffling.
5882       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5883         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5884         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5885                                                CostKind);
5886       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5887         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5888                                           Builder.getInt1Ty(),
5889                                           CI0->getPredicate(), CostKind, VL0);
5890         VecCost += TTI->getCmpSelInstrCost(
5891             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5892             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5893             E->getAltOp());
5894       } else {
5895         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5896         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5897         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5898         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5899         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5900                                         TTI::CastContextHint::None, CostKind);
5901         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5902                                          TTI::CastContextHint::None, CostKind);
5903       }
5904 
5905       SmallVector<int> Mask;
5906       buildShuffleEntryMask(
5907           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5908           [E](Instruction *I) {
5909             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5910             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5911           },
5912           Mask);
5913       CommonCost =
5914           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5915       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5916       return CommonCost + VecCost - ScalarCost;
5917     }
5918     default:
5919       llvm_unreachable("Unknown instruction");
5920   }
5921 }
5922 
5923 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5924   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5925                     << VectorizableTree.size() << " is fully vectorizable .\n");
5926 
5927   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5928     SmallVector<int> Mask;
5929     return TE->State == TreeEntry::NeedToGather &&
5930            !any_of(TE->Scalars,
5931                    [this](Value *V) { return EphValues.contains(V); }) &&
5932            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5933             TE->Scalars.size() < Limit ||
5934             ((TE->getOpcode() == Instruction::ExtractElement ||
5935               all_of(TE->Scalars,
5936                      [](Value *V) {
5937                        return isa<ExtractElementInst, UndefValue>(V);
5938                      })) &&
5939              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5940             (TE->State == TreeEntry::NeedToGather &&
5941              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5942   };
5943 
5944   // We only handle trees of heights 1 and 2.
5945   if (VectorizableTree.size() == 1 &&
5946       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5947        (ForReduction &&
5948         AreVectorizableGathers(VectorizableTree[0].get(),
5949                                VectorizableTree[0]->Scalars.size()) &&
5950         VectorizableTree[0]->getVectorFactor() > 2)))
5951     return true;
5952 
5953   if (VectorizableTree.size() != 2)
5954     return false;
5955 
5956   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5957   // with the second gather nodes if they have less scalar operands rather than
5958   // the initial tree element (may be profitable to shuffle the second gather)
5959   // or they are extractelements, which form shuffle.
5960   SmallVector<int> Mask;
5961   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5962       AreVectorizableGathers(VectorizableTree[1].get(),
5963                              VectorizableTree[0]->Scalars.size()))
5964     return true;
5965 
5966   // Gathering cost would be too much for tiny trees.
5967   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5968       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5969        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5970     return false;
5971 
5972   return true;
5973 }
5974 
5975 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5976                                        TargetTransformInfo *TTI,
5977                                        bool MustMatchOrInst) {
5978   // Look past the root to find a source value. Arbitrarily follow the
5979   // path through operand 0 of any 'or'. Also, peek through optional
5980   // shift-left-by-multiple-of-8-bits.
5981   Value *ZextLoad = Root;
5982   const APInt *ShAmtC;
5983   bool FoundOr = false;
5984   while (!isa<ConstantExpr>(ZextLoad) &&
5985          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5986           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5987            ShAmtC->urem(8) == 0))) {
5988     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5989     ZextLoad = BinOp->getOperand(0);
5990     if (BinOp->getOpcode() == Instruction::Or)
5991       FoundOr = true;
5992   }
5993   // Check if the input is an extended load of the required or/shift expression.
5994   Value *Load;
5995   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5996       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5997     return false;
5998 
5999   // Require that the total load bit width is a legal integer type.
6000   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
6001   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
6002   Type *SrcTy = Load->getType();
6003   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
6004   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
6005     return false;
6006 
6007   // Everything matched - assume that we can fold the whole sequence using
6008   // load combining.
6009   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
6010              << *(cast<Instruction>(Root)) << "\n");
6011 
6012   return true;
6013 }
6014 
6015 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
6016   if (RdxKind != RecurKind::Or)
6017     return false;
6018 
6019   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6020   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
6021   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
6022                                     /* MatchOr */ false);
6023 }
6024 
6025 bool BoUpSLP::isLoadCombineCandidate() const {
6026   // Peek through a final sequence of stores and check if all operations are
6027   // likely to be load-combined.
6028   unsigned NumElts = VectorizableTree[0]->Scalars.size();
6029   for (Value *Scalar : VectorizableTree[0]->Scalars) {
6030     Value *X;
6031     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
6032         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
6033       return false;
6034   }
6035   return true;
6036 }
6037 
6038 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
6039   // No need to vectorize inserts of gathered values.
6040   if (VectorizableTree.size() == 2 &&
6041       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
6042       VectorizableTree[1]->State == TreeEntry::NeedToGather)
6043     return true;
6044 
6045   // We can vectorize the tree if its size is greater than or equal to the
6046   // minimum size specified by the MinTreeSize command line option.
6047   if (VectorizableTree.size() >= MinTreeSize)
6048     return false;
6049 
6050   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
6051   // can vectorize it if we can prove it fully vectorizable.
6052   if (isFullyVectorizableTinyTree(ForReduction))
6053     return false;
6054 
6055   assert(VectorizableTree.empty()
6056              ? ExternalUses.empty()
6057              : true && "We shouldn't have any external users");
6058 
6059   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6060   // vectorizable.
6061   return true;
6062 }
6063 
6064 InstructionCost BoUpSLP::getSpillCost() const {
6065   // Walk from the bottom of the tree to the top, tracking which values are
6066   // live. When we see a call instruction that is not part of our tree,
6067   // query TTI to see if there is a cost to keeping values live over it
6068   // (for example, if spills and fills are required).
6069   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6070   InstructionCost Cost = 0;
6071 
6072   SmallPtrSet<Instruction*, 4> LiveValues;
6073   Instruction *PrevInst = nullptr;
6074 
6075   // The entries in VectorizableTree are not necessarily ordered by their
6076   // position in basic blocks. Collect them and order them by dominance so later
6077   // instructions are guaranteed to be visited first. For instructions in
6078   // different basic blocks, we only scan to the beginning of the block, so
6079   // their order does not matter, as long as all instructions in a basic block
6080   // are grouped together. Using dominance ensures a deterministic order.
6081   SmallVector<Instruction *, 16> OrderedScalars;
6082   for (const auto &TEPtr : VectorizableTree) {
6083     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6084     if (!Inst)
6085       continue;
6086     OrderedScalars.push_back(Inst);
6087   }
6088   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6089     auto *NodeA = DT->getNode(A->getParent());
6090     auto *NodeB = DT->getNode(B->getParent());
6091     assert(NodeA && "Should only process reachable instructions");
6092     assert(NodeB && "Should only process reachable instructions");
6093     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6094            "Different nodes should have different DFS numbers");
6095     if (NodeA != NodeB)
6096       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6097     return B->comesBefore(A);
6098   });
6099 
6100   for (Instruction *Inst : OrderedScalars) {
6101     if (!PrevInst) {
6102       PrevInst = Inst;
6103       continue;
6104     }
6105 
6106     // Update LiveValues.
6107     LiveValues.erase(PrevInst);
6108     for (auto &J : PrevInst->operands()) {
6109       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6110         LiveValues.insert(cast<Instruction>(&*J));
6111     }
6112 
6113     LLVM_DEBUG({
6114       dbgs() << "SLP: #LV: " << LiveValues.size();
6115       for (auto *X : LiveValues)
6116         dbgs() << " " << X->getName();
6117       dbgs() << ", Looking at ";
6118       Inst->dump();
6119     });
6120 
6121     // Now find the sequence of instructions between PrevInst and Inst.
6122     unsigned NumCalls = 0;
6123     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6124                                  PrevInstIt =
6125                                      PrevInst->getIterator().getReverse();
6126     while (InstIt != PrevInstIt) {
6127       if (PrevInstIt == PrevInst->getParent()->rend()) {
6128         PrevInstIt = Inst->getParent()->rbegin();
6129         continue;
6130       }
6131 
6132       // Debug information does not impact spill cost.
6133       if ((isa<CallInst>(&*PrevInstIt) &&
6134            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6135           &*PrevInstIt != PrevInst)
6136         NumCalls++;
6137 
6138       ++PrevInstIt;
6139     }
6140 
6141     if (NumCalls) {
6142       SmallVector<Type*, 4> V;
6143       for (auto *II : LiveValues) {
6144         auto *ScalarTy = II->getType();
6145         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6146           ScalarTy = VectorTy->getElementType();
6147         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6148       }
6149       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6150     }
6151 
6152     PrevInst = Inst;
6153   }
6154 
6155   return Cost;
6156 }
6157 
6158 /// Check if two insertelement instructions are from the same buildvector.
6159 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6160                                             InsertElementInst *V) {
6161   // Instructions must be from the same basic blocks.
6162   if (VU->getParent() != V->getParent())
6163     return false;
6164   // Checks if 2 insertelements are from the same buildvector.
6165   if (VU->getType() != V->getType())
6166     return false;
6167   // Multiple used inserts are separate nodes.
6168   if (!VU->hasOneUse() && !V->hasOneUse())
6169     return false;
6170   auto *IE1 = VU;
6171   auto *IE2 = V;
6172   // Go through the vector operand of insertelement instructions trying to find
6173   // either VU as the original vector for IE2 or V as the original vector for
6174   // IE1.
6175   do {
6176     if (IE2 == VU || IE1 == V)
6177       return true;
6178     if (IE1) {
6179       if (IE1 != VU && !IE1->hasOneUse())
6180         IE1 = nullptr;
6181       else
6182         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6183     }
6184     if (IE2) {
6185       if (IE2 != V && !IE2->hasOneUse())
6186         IE2 = nullptr;
6187       else
6188         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6189     }
6190   } while (IE1 || IE2);
6191   return false;
6192 }
6193 
6194 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6195   InstructionCost Cost = 0;
6196   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6197                     << VectorizableTree.size() << ".\n");
6198 
6199   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6200 
6201   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6202     TreeEntry &TE = *VectorizableTree[I];
6203 
6204     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6205     Cost += C;
6206     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6207                       << " for bundle that starts with " << *TE.Scalars[0]
6208                       << ".\n"
6209                       << "SLP: Current total cost = " << Cost << "\n");
6210   }
6211 
6212   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6213   InstructionCost ExtractCost = 0;
6214   SmallVector<unsigned> VF;
6215   SmallVector<SmallVector<int>> ShuffleMask;
6216   SmallVector<Value *> FirstUsers;
6217   SmallVector<APInt> DemandedElts;
6218   for (ExternalUser &EU : ExternalUses) {
6219     // We only add extract cost once for the same scalar.
6220     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6221         !ExtractCostCalculated.insert(EU.Scalar).second)
6222       continue;
6223 
6224     // Uses by ephemeral values are free (because the ephemeral value will be
6225     // removed prior to code generation, and so the extraction will be
6226     // removed as well).
6227     if (EphValues.count(EU.User))
6228       continue;
6229 
6230     // No extract cost for vector "scalar"
6231     if (isa<FixedVectorType>(EU.Scalar->getType()))
6232       continue;
6233 
6234     // Already counted the cost for external uses when tried to adjust the cost
6235     // for extractelements, no need to add it again.
6236     if (isa<ExtractElementInst>(EU.Scalar))
6237       continue;
6238 
6239     // If found user is an insertelement, do not calculate extract cost but try
6240     // to detect it as a final shuffled/identity match.
6241     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6242       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6243         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6244         if (InsertIdx) {
6245           auto *It = find_if(FirstUsers, [VU](Value *V) {
6246             return areTwoInsertFromSameBuildVector(VU,
6247                                                    cast<InsertElementInst>(V));
6248           });
6249           int VecId = -1;
6250           if (It == FirstUsers.end()) {
6251             VF.push_back(FTy->getNumElements());
6252             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6253             // Find the insertvector, vectorized in tree, if any.
6254             Value *Base = VU;
6255             while (isa<InsertElementInst>(Base)) {
6256               // Build the mask for the vectorized insertelement instructions.
6257               if (const TreeEntry *E = getTreeEntry(Base)) {
6258                 VU = cast<InsertElementInst>(Base);
6259                 do {
6260                   int Idx = E->findLaneForValue(Base);
6261                   ShuffleMask.back()[Idx] = Idx;
6262                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6263                 } while (E == getTreeEntry(Base));
6264                 break;
6265               }
6266               Base = cast<InsertElementInst>(Base)->getOperand(0);
6267             }
6268             FirstUsers.push_back(VU);
6269             DemandedElts.push_back(APInt::getZero(VF.back()));
6270             VecId = FirstUsers.size() - 1;
6271           } else {
6272             VecId = std::distance(FirstUsers.begin(), It);
6273           }
6274           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6275           DemandedElts[VecId].setBit(*InsertIdx);
6276           continue;
6277         }
6278       }
6279     }
6280 
6281     // If we plan to rewrite the tree in a smaller type, we will need to sign
6282     // extend the extracted value back to the original type. Here, we account
6283     // for the extract and the added cost of the sign extend if needed.
6284     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6285     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6286     if (MinBWs.count(ScalarRoot)) {
6287       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6288       auto Extend =
6289           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6290       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6291       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6292                                                    VecTy, EU.Lane);
6293     } else {
6294       ExtractCost +=
6295           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6296     }
6297   }
6298 
6299   InstructionCost SpillCost = getSpillCost();
6300   Cost += SpillCost + ExtractCost;
6301   if (FirstUsers.size() == 1) {
6302     int Limit = ShuffleMask.front().size() * 2;
6303     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6304         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6305       InstructionCost C = TTI->getShuffleCost(
6306           TTI::SK_PermuteSingleSrc,
6307           cast<FixedVectorType>(FirstUsers.front()->getType()),
6308           ShuffleMask.front());
6309       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6310                         << " for final shuffle of insertelement external users "
6311                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6312                         << "SLP: Current total cost = " << Cost << "\n");
6313       Cost += C;
6314     }
6315     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6316         cast<FixedVectorType>(FirstUsers.front()->getType()),
6317         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6318     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6319                       << " for insertelements gather.\n"
6320                       << "SLP: Current total cost = " << Cost << "\n");
6321     Cost -= InsertCost;
6322   } else if (FirstUsers.size() >= 2) {
6323     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6324     // Combined masks of the first 2 vectors.
6325     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6326     copy(ShuffleMask.front(), CombinedMask.begin());
6327     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6328     auto *VecTy = FixedVectorType::get(
6329         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6330         MaxVF);
6331     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6332       if (ShuffleMask[1][I] != UndefMaskElem) {
6333         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6334         CombinedDemandedElts.setBit(I);
6335       }
6336     }
6337     InstructionCost C =
6338         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6339     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6340                       << " for final shuffle of vector node and external "
6341                          "insertelement users "
6342                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6343                       << "SLP: Current total cost = " << Cost << "\n");
6344     Cost += C;
6345     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6346         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6347     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6348                       << " for insertelements gather.\n"
6349                       << "SLP: Current total cost = " << Cost << "\n");
6350     Cost -= InsertCost;
6351     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6352       // Other elements - permutation of 2 vectors (the initial one and the
6353       // next Ith incoming vector).
6354       unsigned VF = ShuffleMask[I].size();
6355       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6356         int Mask = ShuffleMask[I][Idx];
6357         if (Mask != UndefMaskElem)
6358           CombinedMask[Idx] = MaxVF + Mask;
6359         else if (CombinedMask[Idx] != UndefMaskElem)
6360           CombinedMask[Idx] = Idx;
6361       }
6362       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6363         if (CombinedMask[Idx] != UndefMaskElem)
6364           CombinedMask[Idx] = Idx;
6365       InstructionCost C =
6366           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6367       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6368                         << " for final shuffle of vector node and external "
6369                            "insertelement users "
6370                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6371                         << "SLP: Current total cost = " << Cost << "\n");
6372       Cost += C;
6373       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6374           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6375           /*Insert*/ true, /*Extract*/ false);
6376       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6377                         << " for insertelements gather.\n"
6378                         << "SLP: Current total cost = " << Cost << "\n");
6379       Cost -= InsertCost;
6380     }
6381   }
6382 
6383 #ifndef NDEBUG
6384   SmallString<256> Str;
6385   {
6386     raw_svector_ostream OS(Str);
6387     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6388        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6389        << "SLP: Total Cost = " << Cost << ".\n";
6390   }
6391   LLVM_DEBUG(dbgs() << Str);
6392   if (ViewSLPTree)
6393     ViewGraph(this, "SLP" + F->getName(), false, Str);
6394 #endif
6395 
6396   return Cost;
6397 }
6398 
6399 Optional<TargetTransformInfo::ShuffleKind>
6400 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6401                                SmallVectorImpl<const TreeEntry *> &Entries) {
6402   // TODO: currently checking only for Scalars in the tree entry, need to count
6403   // reused elements too for better cost estimation.
6404   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6405   Entries.clear();
6406   // Build a lists of values to tree entries.
6407   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6408   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6409     if (EntryPtr.get() == TE)
6410       break;
6411     if (EntryPtr->State != TreeEntry::NeedToGather)
6412       continue;
6413     for (Value *V : EntryPtr->Scalars)
6414       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6415   }
6416   // Find all tree entries used by the gathered values. If no common entries
6417   // found - not a shuffle.
6418   // Here we build a set of tree nodes for each gathered value and trying to
6419   // find the intersection between these sets. If we have at least one common
6420   // tree node for each gathered value - we have just a permutation of the
6421   // single vector. If we have 2 different sets, we're in situation where we
6422   // have a permutation of 2 input vectors.
6423   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6424   DenseMap<Value *, int> UsedValuesEntry;
6425   for (Value *V : TE->Scalars) {
6426     if (isa<UndefValue>(V))
6427       continue;
6428     // Build a list of tree entries where V is used.
6429     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6430     auto It = ValueToTEs.find(V);
6431     if (It != ValueToTEs.end())
6432       VToTEs = It->second;
6433     if (const TreeEntry *VTE = getTreeEntry(V))
6434       VToTEs.insert(VTE);
6435     if (VToTEs.empty())
6436       return None;
6437     if (UsedTEs.empty()) {
6438       // The first iteration, just insert the list of nodes to vector.
6439       UsedTEs.push_back(VToTEs);
6440     } else {
6441       // Need to check if there are any previously used tree nodes which use V.
6442       // If there are no such nodes, consider that we have another one input
6443       // vector.
6444       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6445       unsigned Idx = 0;
6446       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6447         // Do we have a non-empty intersection of previously listed tree entries
6448         // and tree entries using current V?
6449         set_intersect(VToTEs, Set);
6450         if (!VToTEs.empty()) {
6451           // Yes, write the new subset and continue analysis for the next
6452           // scalar.
6453           Set.swap(VToTEs);
6454           break;
6455         }
6456         VToTEs = SavedVToTEs;
6457         ++Idx;
6458       }
6459       // No non-empty intersection found - need to add a second set of possible
6460       // source vectors.
6461       if (Idx == UsedTEs.size()) {
6462         // If the number of input vectors is greater than 2 - not a permutation,
6463         // fallback to the regular gather.
6464         if (UsedTEs.size() == 2)
6465           return None;
6466         UsedTEs.push_back(SavedVToTEs);
6467         Idx = UsedTEs.size() - 1;
6468       }
6469       UsedValuesEntry.try_emplace(V, Idx);
6470     }
6471   }
6472 
6473   if (UsedTEs.empty()) {
6474     assert(all_of(TE->Scalars, UndefValue::classof) &&
6475            "Expected vector of undefs only.");
6476     return None;
6477   }
6478 
6479   unsigned VF = 0;
6480   if (UsedTEs.size() == 1) {
6481     // Try to find the perfect match in another gather node at first.
6482     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6483       return EntryPtr->isSame(TE->Scalars);
6484     });
6485     if (It != UsedTEs.front().end()) {
6486       Entries.push_back(*It);
6487       std::iota(Mask.begin(), Mask.end(), 0);
6488       return TargetTransformInfo::SK_PermuteSingleSrc;
6489     }
6490     // No perfect match, just shuffle, so choose the first tree node.
6491     Entries.push_back(*UsedTEs.front().begin());
6492   } else {
6493     // Try to find nodes with the same vector factor.
6494     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6495     DenseMap<int, const TreeEntry *> VFToTE;
6496     for (const TreeEntry *TE : UsedTEs.front())
6497       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6498     for (const TreeEntry *TE : UsedTEs.back()) {
6499       auto It = VFToTE.find(TE->getVectorFactor());
6500       if (It != VFToTE.end()) {
6501         VF = It->first;
6502         Entries.push_back(It->second);
6503         Entries.push_back(TE);
6504         break;
6505       }
6506     }
6507     // No 2 source vectors with the same vector factor - give up and do regular
6508     // gather.
6509     if (Entries.empty())
6510       return None;
6511   }
6512 
6513   // Build a shuffle mask for better cost estimation and vector emission.
6514   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6515     Value *V = TE->Scalars[I];
6516     if (isa<UndefValue>(V))
6517       continue;
6518     unsigned Idx = UsedValuesEntry.lookup(V);
6519     const TreeEntry *VTE = Entries[Idx];
6520     int FoundLane = VTE->findLaneForValue(V);
6521     Mask[I] = Idx * VF + FoundLane;
6522     // Extra check required by isSingleSourceMaskImpl function (called by
6523     // ShuffleVectorInst::isSingleSourceMask).
6524     if (Mask[I] >= 2 * E)
6525       return None;
6526   }
6527   switch (Entries.size()) {
6528   case 1:
6529     return TargetTransformInfo::SK_PermuteSingleSrc;
6530   case 2:
6531     return TargetTransformInfo::SK_PermuteTwoSrc;
6532   default:
6533     break;
6534   }
6535   return None;
6536 }
6537 
6538 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6539                                        const APInt &ShuffledIndices,
6540                                        bool NeedToShuffle) const {
6541   InstructionCost Cost =
6542       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6543                                     /*Extract*/ false);
6544   if (NeedToShuffle)
6545     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6546   return Cost;
6547 }
6548 
6549 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6550   // Find the type of the operands in VL.
6551   Type *ScalarTy = VL[0]->getType();
6552   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6553     ScalarTy = SI->getValueOperand()->getType();
6554   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6555   bool DuplicateNonConst = false;
6556   // Find the cost of inserting/extracting values from the vector.
6557   // Check if the same elements are inserted several times and count them as
6558   // shuffle candidates.
6559   APInt ShuffledElements = APInt::getZero(VL.size());
6560   DenseSet<Value *> UniqueElements;
6561   // Iterate in reverse order to consider insert elements with the high cost.
6562   for (unsigned I = VL.size(); I > 0; --I) {
6563     unsigned Idx = I - 1;
6564     // No need to shuffle duplicates for constants.
6565     if (isConstant(VL[Idx])) {
6566       ShuffledElements.setBit(Idx);
6567       continue;
6568     }
6569     if (!UniqueElements.insert(VL[Idx]).second) {
6570       DuplicateNonConst = true;
6571       ShuffledElements.setBit(Idx);
6572     }
6573   }
6574   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6575 }
6576 
6577 // Perform operand reordering on the instructions in VL and return the reordered
6578 // operands in Left and Right.
6579 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6580                                              SmallVectorImpl<Value *> &Left,
6581                                              SmallVectorImpl<Value *> &Right,
6582                                              const DataLayout &DL,
6583                                              ScalarEvolution &SE,
6584                                              const BoUpSLP &R) {
6585   if (VL.empty())
6586     return;
6587   VLOperands Ops(VL, DL, SE, R);
6588   // Reorder the operands in place.
6589   Ops.reorder();
6590   Left = Ops.getVL(0);
6591   Right = Ops.getVL(1);
6592 }
6593 
6594 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6595   // Get the basic block this bundle is in. All instructions in the bundle
6596   // should be in this block.
6597   auto *Front = E->getMainOp();
6598   auto *BB = Front->getParent();
6599   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6600     auto *I = cast<Instruction>(V);
6601     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6602   }));
6603 
6604   auto &&FindLastInst = [E, Front]() {
6605     Instruction *LastInst = Front;
6606     for (Value *V : E->Scalars) {
6607       auto *I = dyn_cast<Instruction>(V);
6608       if (!I)
6609         continue;
6610       if (LastInst->comesBefore(I))
6611         LastInst = I;
6612     }
6613     return LastInst;
6614   };
6615 
6616   auto &&FindFirstInst = [E, Front]() {
6617     Instruction *FirstInst = Front;
6618     for (Value *V : E->Scalars) {
6619       auto *I = dyn_cast<Instruction>(V);
6620       if (!I)
6621         continue;
6622       if (I->comesBefore(FirstInst))
6623         FirstInst = I;
6624     }
6625     return FirstInst;
6626   };
6627 
6628   // Set the insert point to the beginning of the basic block if the entry
6629   // should not be scheduled.
6630   if (E->State != TreeEntry::NeedToGather &&
6631       doesNotNeedToSchedule(E->Scalars)) {
6632     BasicBlock::iterator InsertPt;
6633     if (all_of(E->Scalars, isUsedOutsideBlock))
6634       InsertPt = FindLastInst()->getIterator();
6635     else
6636       InsertPt = FindFirstInst()->getIterator();
6637     Builder.SetInsertPoint(BB, InsertPt);
6638     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6639     return;
6640   }
6641 
6642   // The last instruction in the bundle in program order.
6643   Instruction *LastInst = nullptr;
6644 
6645   // Find the last instruction. The common case should be that BB has been
6646   // scheduled, and the last instruction is VL.back(). So we start with
6647   // VL.back() and iterate over schedule data until we reach the end of the
6648   // bundle. The end of the bundle is marked by null ScheduleData.
6649   if (BlocksSchedules.count(BB)) {
6650     Value *V = E->isOneOf(E->Scalars.back());
6651     if (doesNotNeedToBeScheduled(V))
6652       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6653     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6654     if (Bundle && Bundle->isPartOfBundle())
6655       for (; Bundle; Bundle = Bundle->NextInBundle)
6656         if (Bundle->OpValue == Bundle->Inst)
6657           LastInst = Bundle->Inst;
6658   }
6659 
6660   // LastInst can still be null at this point if there's either not an entry
6661   // for BB in BlocksSchedules or there's no ScheduleData available for
6662   // VL.back(). This can be the case if buildTree_rec aborts for various
6663   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6664   // size is reached, etc.). ScheduleData is initialized in the scheduling
6665   // "dry-run".
6666   //
6667   // If this happens, we can still find the last instruction by brute force. We
6668   // iterate forwards from Front (inclusive) until we either see all
6669   // instructions in the bundle or reach the end of the block. If Front is the
6670   // last instruction in program order, LastInst will be set to Front, and we
6671   // will visit all the remaining instructions in the block.
6672   //
6673   // One of the reasons we exit early from buildTree_rec is to place an upper
6674   // bound on compile-time. Thus, taking an additional compile-time hit here is
6675   // not ideal. However, this should be exceedingly rare since it requires that
6676   // we both exit early from buildTree_rec and that the bundle be out-of-order
6677   // (causing us to iterate all the way to the end of the block).
6678   if (!LastInst)
6679     LastInst = FindLastInst();
6680   assert(LastInst && "Failed to find last instruction in bundle");
6681 
6682   // Set the insertion point after the last instruction in the bundle. Set the
6683   // debug location to Front.
6684   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6685   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6686 }
6687 
6688 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6689   // List of instructions/lanes from current block and/or the blocks which are
6690   // part of the current loop. These instructions will be inserted at the end to
6691   // make it possible to optimize loops and hoist invariant instructions out of
6692   // the loops body with better chances for success.
6693   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6694   SmallSet<int, 4> PostponedIndices;
6695   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6696   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6697     SmallPtrSet<BasicBlock *, 4> Visited;
6698     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6699       InsertBB = InsertBB->getSinglePredecessor();
6700     return InsertBB && InsertBB == InstBB;
6701   };
6702   for (int I = 0, E = VL.size(); I < E; ++I) {
6703     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6704       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6705            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6706           PostponedIndices.insert(I).second)
6707         PostponedInsts.emplace_back(Inst, I);
6708   }
6709 
6710   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6711     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6712     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6713     if (!InsElt)
6714       return Vec;
6715     GatherShuffleSeq.insert(InsElt);
6716     CSEBlocks.insert(InsElt->getParent());
6717     // Add to our 'need-to-extract' list.
6718     if (TreeEntry *Entry = getTreeEntry(V)) {
6719       // Find which lane we need to extract.
6720       unsigned FoundLane = Entry->findLaneForValue(V);
6721       ExternalUses.emplace_back(V, InsElt, FoundLane);
6722     }
6723     return Vec;
6724   };
6725   Value *Val0 =
6726       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6727   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6728   Value *Vec = PoisonValue::get(VecTy);
6729   SmallVector<int> NonConsts;
6730   // Insert constant values at first.
6731   for (int I = 0, E = VL.size(); I < E; ++I) {
6732     if (PostponedIndices.contains(I))
6733       continue;
6734     if (!isConstant(VL[I])) {
6735       NonConsts.push_back(I);
6736       continue;
6737     }
6738     Vec = CreateInsertElement(Vec, VL[I], I);
6739   }
6740   // Insert non-constant values.
6741   for (int I : NonConsts)
6742     Vec = CreateInsertElement(Vec, VL[I], I);
6743   // Append instructions, which are/may be part of the loop, in the end to make
6744   // it possible to hoist non-loop-based instructions.
6745   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6746     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6747 
6748   return Vec;
6749 }
6750 
6751 namespace {
6752 /// Merges shuffle masks and emits final shuffle instruction, if required.
6753 class ShuffleInstructionBuilder {
6754   IRBuilderBase &Builder;
6755   const unsigned VF = 0;
6756   bool IsFinalized = false;
6757   SmallVector<int, 4> Mask;
6758   /// Holds all of the instructions that we gathered.
6759   SetVector<Instruction *> &GatherShuffleSeq;
6760   /// A list of blocks that we are going to CSE.
6761   SetVector<BasicBlock *> &CSEBlocks;
6762 
6763 public:
6764   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6765                             SetVector<Instruction *> &GatherShuffleSeq,
6766                             SetVector<BasicBlock *> &CSEBlocks)
6767       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6768         CSEBlocks(CSEBlocks) {}
6769 
6770   /// Adds a mask, inverting it before applying.
6771   void addInversedMask(ArrayRef<unsigned> SubMask) {
6772     if (SubMask.empty())
6773       return;
6774     SmallVector<int, 4> NewMask;
6775     inversePermutation(SubMask, NewMask);
6776     addMask(NewMask);
6777   }
6778 
6779   /// Functions adds masks, merging them into  single one.
6780   void addMask(ArrayRef<unsigned> SubMask) {
6781     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6782     addMask(NewMask);
6783   }
6784 
6785   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6786 
6787   Value *finalize(Value *V) {
6788     IsFinalized = true;
6789     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6790     if (VF == ValueVF && Mask.empty())
6791       return V;
6792     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6793     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6794     addMask(NormalizedMask);
6795 
6796     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6797       return V;
6798     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6799     if (auto *I = dyn_cast<Instruction>(Vec)) {
6800       GatherShuffleSeq.insert(I);
6801       CSEBlocks.insert(I->getParent());
6802     }
6803     return Vec;
6804   }
6805 
6806   ~ShuffleInstructionBuilder() {
6807     assert((IsFinalized || Mask.empty()) &&
6808            "Shuffle construction must be finalized.");
6809   }
6810 };
6811 } // namespace
6812 
6813 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6814   const unsigned VF = VL.size();
6815   InstructionsState S = getSameOpcode(VL);
6816   if (S.getOpcode()) {
6817     if (TreeEntry *E = getTreeEntry(S.OpValue))
6818       if (E->isSame(VL)) {
6819         Value *V = vectorizeTree(E);
6820         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6821           if (!E->ReuseShuffleIndices.empty()) {
6822             // Reshuffle to get only unique values.
6823             // If some of the scalars are duplicated in the vectorization tree
6824             // entry, we do not vectorize them but instead generate a mask for
6825             // the reuses. But if there are several users of the same entry,
6826             // they may have different vectorization factors. This is especially
6827             // important for PHI nodes. In this case, we need to adapt the
6828             // resulting instruction for the user vectorization factor and have
6829             // to reshuffle it again to take only unique elements of the vector.
6830             // Without this code the function incorrectly returns reduced vector
6831             // instruction with the same elements, not with the unique ones.
6832 
6833             // block:
6834             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6835             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6836             // ... (use %2)
6837             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6838             // br %block
6839             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6840             SmallSet<int, 4> UsedIdxs;
6841             int Pos = 0;
6842             int Sz = VL.size();
6843             for (int Idx : E->ReuseShuffleIndices) {
6844               if (Idx != Sz && Idx != UndefMaskElem &&
6845                   UsedIdxs.insert(Idx).second)
6846                 UniqueIdxs[Idx] = Pos;
6847               ++Pos;
6848             }
6849             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6850                                             "less than original vector size.");
6851             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6852             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6853           } else {
6854             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6855                    "Expected vectorization factor less "
6856                    "than original vector size.");
6857             SmallVector<int> UniformMask(VF, 0);
6858             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6859             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6860           }
6861           if (auto *I = dyn_cast<Instruction>(V)) {
6862             GatherShuffleSeq.insert(I);
6863             CSEBlocks.insert(I->getParent());
6864           }
6865         }
6866         return V;
6867       }
6868   }
6869 
6870   // Can't vectorize this, so simply build a new vector with each lane
6871   // corresponding to the requested value.
6872   return createBuildVector(VL);
6873 }
6874 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6875   unsigned VF = VL.size();
6876   // Exploit possible reuse of values across lanes.
6877   SmallVector<int> ReuseShuffleIndicies;
6878   SmallVector<Value *> UniqueValues;
6879   if (VL.size() > 2) {
6880     DenseMap<Value *, unsigned> UniquePositions;
6881     unsigned NumValues =
6882         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6883                                     return !isa<UndefValue>(V);
6884                                   }).base());
6885     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6886     int UniqueVals = 0;
6887     for (Value *V : VL.drop_back(VL.size() - VF)) {
6888       if (isa<UndefValue>(V)) {
6889         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6890         continue;
6891       }
6892       if (isConstant(V)) {
6893         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6894         UniqueValues.emplace_back(V);
6895         continue;
6896       }
6897       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6898       ReuseShuffleIndicies.emplace_back(Res.first->second);
6899       if (Res.second) {
6900         UniqueValues.emplace_back(V);
6901         ++UniqueVals;
6902       }
6903     }
6904     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6905       // Emit pure splat vector.
6906       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6907                                   UndefMaskElem);
6908     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6909       ReuseShuffleIndicies.clear();
6910       UniqueValues.clear();
6911       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6912     }
6913     UniqueValues.append(VF - UniqueValues.size(),
6914                         PoisonValue::get(VL[0]->getType()));
6915     VL = UniqueValues;
6916   }
6917 
6918   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6919                                            CSEBlocks);
6920   Value *Vec = gather(VL);
6921   if (!ReuseShuffleIndicies.empty()) {
6922     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6923     Vec = ShuffleBuilder.finalize(Vec);
6924   }
6925   return Vec;
6926 }
6927 
6928 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6929   IRBuilder<>::InsertPointGuard Guard(Builder);
6930 
6931   if (E->VectorizedValue) {
6932     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6933     return E->VectorizedValue;
6934   }
6935 
6936   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6937   unsigned VF = E->getVectorFactor();
6938   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6939                                            CSEBlocks);
6940   if (E->State == TreeEntry::NeedToGather) {
6941     if (E->getMainOp())
6942       setInsertPointAfterBundle(E);
6943     Value *Vec;
6944     SmallVector<int> Mask;
6945     SmallVector<const TreeEntry *> Entries;
6946     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6947         isGatherShuffledEntry(E, Mask, Entries);
6948     if (Shuffle.hasValue()) {
6949       assert((Entries.size() == 1 || Entries.size() == 2) &&
6950              "Expected shuffle of 1 or 2 entries.");
6951       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6952                                         Entries.back()->VectorizedValue, Mask);
6953       if (auto *I = dyn_cast<Instruction>(Vec)) {
6954         GatherShuffleSeq.insert(I);
6955         CSEBlocks.insert(I->getParent());
6956       }
6957     } else {
6958       Vec = gather(E->Scalars);
6959     }
6960     if (NeedToShuffleReuses) {
6961       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6962       Vec = ShuffleBuilder.finalize(Vec);
6963     }
6964     E->VectorizedValue = Vec;
6965     return Vec;
6966   }
6967 
6968   assert((E->State == TreeEntry::Vectorize ||
6969           E->State == TreeEntry::ScatterVectorize) &&
6970          "Unhandled state");
6971   unsigned ShuffleOrOp =
6972       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6973   Instruction *VL0 = E->getMainOp();
6974   Type *ScalarTy = VL0->getType();
6975   if (auto *Store = dyn_cast<StoreInst>(VL0))
6976     ScalarTy = Store->getValueOperand()->getType();
6977   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6978     ScalarTy = IE->getOperand(1)->getType();
6979   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6980   switch (ShuffleOrOp) {
6981     case Instruction::PHI: {
6982       assert(
6983           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6984           "PHI reordering is free.");
6985       auto *PH = cast<PHINode>(VL0);
6986       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6987       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6988       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6989       Value *V = NewPhi;
6990 
6991       // Adjust insertion point once all PHI's have been generated.
6992       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6993       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6994 
6995       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6996       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6997       V = ShuffleBuilder.finalize(V);
6998 
6999       E->VectorizedValue = V;
7000 
7001       // PHINodes may have multiple entries from the same block. We want to
7002       // visit every block once.
7003       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
7004 
7005       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
7006         ValueList Operands;
7007         BasicBlock *IBB = PH->getIncomingBlock(i);
7008 
7009         if (!VisitedBBs.insert(IBB).second) {
7010           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
7011           continue;
7012         }
7013 
7014         Builder.SetInsertPoint(IBB->getTerminator());
7015         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
7016         Value *Vec = vectorizeTree(E->getOperand(i));
7017         NewPhi->addIncoming(Vec, IBB);
7018       }
7019 
7020       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
7021              "Invalid number of incoming values");
7022       return V;
7023     }
7024 
7025     case Instruction::ExtractElement: {
7026       Value *V = E->getSingleOperand(0);
7027       Builder.SetInsertPoint(VL0);
7028       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7029       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7030       V = ShuffleBuilder.finalize(V);
7031       E->VectorizedValue = V;
7032       return V;
7033     }
7034     case Instruction::ExtractValue: {
7035       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
7036       Builder.SetInsertPoint(LI);
7037       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
7038       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
7039       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
7040       Value *NewV = propagateMetadata(V, E->Scalars);
7041       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7042       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7043       NewV = ShuffleBuilder.finalize(NewV);
7044       E->VectorizedValue = NewV;
7045       return NewV;
7046     }
7047     case Instruction::InsertElement: {
7048       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
7049       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
7050       Value *V = vectorizeTree(E->getOperand(1));
7051 
7052       // Create InsertVector shuffle if necessary
7053       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
7054         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
7055       }));
7056       const unsigned NumElts =
7057           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
7058       const unsigned NumScalars = E->Scalars.size();
7059 
7060       unsigned Offset = *getInsertIndex(VL0);
7061       assert(Offset < NumElts && "Failed to find vector index offset");
7062 
7063       // Create shuffle to resize vector
7064       SmallVector<int> Mask;
7065       if (!E->ReorderIndices.empty()) {
7066         inversePermutation(E->ReorderIndices, Mask);
7067         Mask.append(NumElts - NumScalars, UndefMaskElem);
7068       } else {
7069         Mask.assign(NumElts, UndefMaskElem);
7070         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7071       }
7072       // Create InsertVector shuffle if necessary
7073       bool IsIdentity = true;
7074       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7075       Mask.swap(PrevMask);
7076       for (unsigned I = 0; I < NumScalars; ++I) {
7077         Value *Scalar = E->Scalars[PrevMask[I]];
7078         unsigned InsertIdx = *getInsertIndex(Scalar);
7079         IsIdentity &= InsertIdx - Offset == I;
7080         Mask[InsertIdx - Offset] = I;
7081       }
7082       if (!IsIdentity || NumElts != NumScalars) {
7083         V = Builder.CreateShuffleVector(V, Mask);
7084         if (auto *I = dyn_cast<Instruction>(V)) {
7085           GatherShuffleSeq.insert(I);
7086           CSEBlocks.insert(I->getParent());
7087         }
7088       }
7089 
7090       if ((!IsIdentity || Offset != 0 ||
7091            !isUndefVector(FirstInsert->getOperand(0))) &&
7092           NumElts != NumScalars) {
7093         SmallVector<int> InsertMask(NumElts);
7094         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7095         for (unsigned I = 0; I < NumElts; I++) {
7096           if (Mask[I] != UndefMaskElem)
7097             InsertMask[Offset + I] = NumElts + I;
7098         }
7099 
7100         V = Builder.CreateShuffleVector(
7101             FirstInsert->getOperand(0), V, InsertMask,
7102             cast<Instruction>(E->Scalars.back())->getName());
7103         if (auto *I = dyn_cast<Instruction>(V)) {
7104           GatherShuffleSeq.insert(I);
7105           CSEBlocks.insert(I->getParent());
7106         }
7107       }
7108 
7109       ++NumVectorInstructions;
7110       E->VectorizedValue = V;
7111       return V;
7112     }
7113     case Instruction::ZExt:
7114     case Instruction::SExt:
7115     case Instruction::FPToUI:
7116     case Instruction::FPToSI:
7117     case Instruction::FPExt:
7118     case Instruction::PtrToInt:
7119     case Instruction::IntToPtr:
7120     case Instruction::SIToFP:
7121     case Instruction::UIToFP:
7122     case Instruction::Trunc:
7123     case Instruction::FPTrunc:
7124     case Instruction::BitCast: {
7125       setInsertPointAfterBundle(E);
7126 
7127       Value *InVec = vectorizeTree(E->getOperand(0));
7128 
7129       if (E->VectorizedValue) {
7130         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7131         return E->VectorizedValue;
7132       }
7133 
7134       auto *CI = cast<CastInst>(VL0);
7135       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7136       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7137       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7138       V = ShuffleBuilder.finalize(V);
7139 
7140       E->VectorizedValue = V;
7141       ++NumVectorInstructions;
7142       return V;
7143     }
7144     case Instruction::FCmp:
7145     case Instruction::ICmp: {
7146       setInsertPointAfterBundle(E);
7147 
7148       Value *L = vectorizeTree(E->getOperand(0));
7149       Value *R = vectorizeTree(E->getOperand(1));
7150 
7151       if (E->VectorizedValue) {
7152         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7153         return E->VectorizedValue;
7154       }
7155 
7156       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7157       Value *V = Builder.CreateCmp(P0, L, R);
7158       propagateIRFlags(V, E->Scalars, VL0);
7159       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7160       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7161       V = ShuffleBuilder.finalize(V);
7162 
7163       E->VectorizedValue = V;
7164       ++NumVectorInstructions;
7165       return V;
7166     }
7167     case Instruction::Select: {
7168       setInsertPointAfterBundle(E);
7169 
7170       Value *Cond = vectorizeTree(E->getOperand(0));
7171       Value *True = vectorizeTree(E->getOperand(1));
7172       Value *False = vectorizeTree(E->getOperand(2));
7173 
7174       if (E->VectorizedValue) {
7175         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7176         return E->VectorizedValue;
7177       }
7178 
7179       Value *V = Builder.CreateSelect(Cond, True, False);
7180       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7181       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7182       V = ShuffleBuilder.finalize(V);
7183 
7184       E->VectorizedValue = V;
7185       ++NumVectorInstructions;
7186       return V;
7187     }
7188     case Instruction::FNeg: {
7189       setInsertPointAfterBundle(E);
7190 
7191       Value *Op = vectorizeTree(E->getOperand(0));
7192 
7193       if (E->VectorizedValue) {
7194         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7195         return E->VectorizedValue;
7196       }
7197 
7198       Value *V = Builder.CreateUnOp(
7199           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7200       propagateIRFlags(V, E->Scalars, VL0);
7201       if (auto *I = dyn_cast<Instruction>(V))
7202         V = propagateMetadata(I, E->Scalars);
7203 
7204       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7205       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7206       V = ShuffleBuilder.finalize(V);
7207 
7208       E->VectorizedValue = V;
7209       ++NumVectorInstructions;
7210 
7211       return V;
7212     }
7213     case Instruction::Add:
7214     case Instruction::FAdd:
7215     case Instruction::Sub:
7216     case Instruction::FSub:
7217     case Instruction::Mul:
7218     case Instruction::FMul:
7219     case Instruction::UDiv:
7220     case Instruction::SDiv:
7221     case Instruction::FDiv:
7222     case Instruction::URem:
7223     case Instruction::SRem:
7224     case Instruction::FRem:
7225     case Instruction::Shl:
7226     case Instruction::LShr:
7227     case Instruction::AShr:
7228     case Instruction::And:
7229     case Instruction::Or:
7230     case Instruction::Xor: {
7231       setInsertPointAfterBundle(E);
7232 
7233       Value *LHS = vectorizeTree(E->getOperand(0));
7234       Value *RHS = vectorizeTree(E->getOperand(1));
7235 
7236       if (E->VectorizedValue) {
7237         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7238         return E->VectorizedValue;
7239       }
7240 
7241       Value *V = Builder.CreateBinOp(
7242           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7243           RHS);
7244       propagateIRFlags(V, E->Scalars, VL0);
7245       if (auto *I = dyn_cast<Instruction>(V))
7246         V = propagateMetadata(I, E->Scalars);
7247 
7248       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7249       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7250       V = ShuffleBuilder.finalize(V);
7251 
7252       E->VectorizedValue = V;
7253       ++NumVectorInstructions;
7254 
7255       return V;
7256     }
7257     case Instruction::Load: {
7258       // Loads are inserted at the head of the tree because we don't want to
7259       // sink them all the way down past store instructions.
7260       setInsertPointAfterBundle(E);
7261 
7262       LoadInst *LI = cast<LoadInst>(VL0);
7263       Instruction *NewLI;
7264       unsigned AS = LI->getPointerAddressSpace();
7265       Value *PO = LI->getPointerOperand();
7266       if (E->State == TreeEntry::Vectorize) {
7267         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7268         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7269 
7270         // The pointer operand uses an in-tree scalar so we add the new BitCast
7271         // or LoadInst to ExternalUses list to make sure that an extract will
7272         // be generated in the future.
7273         if (TreeEntry *Entry = getTreeEntry(PO)) {
7274           // Find which lane we need to extract.
7275           unsigned FoundLane = Entry->findLaneForValue(PO);
7276           ExternalUses.emplace_back(
7277               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7278         }
7279       } else {
7280         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7281         Value *VecPtr = vectorizeTree(E->getOperand(0));
7282         // Use the minimum alignment of the gathered loads.
7283         Align CommonAlignment = LI->getAlign();
7284         for (Value *V : E->Scalars)
7285           CommonAlignment =
7286               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7287         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7288       }
7289       Value *V = propagateMetadata(NewLI, E->Scalars);
7290 
7291       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7292       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7293       V = ShuffleBuilder.finalize(V);
7294       E->VectorizedValue = V;
7295       ++NumVectorInstructions;
7296       return V;
7297     }
7298     case Instruction::Store: {
7299       auto *SI = cast<StoreInst>(VL0);
7300       unsigned AS = SI->getPointerAddressSpace();
7301 
7302       setInsertPointAfterBundle(E);
7303 
7304       Value *VecValue = vectorizeTree(E->getOperand(0));
7305       ShuffleBuilder.addMask(E->ReorderIndices);
7306       VecValue = ShuffleBuilder.finalize(VecValue);
7307 
7308       Value *ScalarPtr = SI->getPointerOperand();
7309       Value *VecPtr = Builder.CreateBitCast(
7310           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7311       StoreInst *ST =
7312           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7313 
7314       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7315       // StoreInst to ExternalUses to make sure that an extract will be
7316       // generated in the future.
7317       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7318         // Find which lane we need to extract.
7319         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7320         ExternalUses.push_back(ExternalUser(
7321             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7322             FoundLane));
7323       }
7324 
7325       Value *V = propagateMetadata(ST, E->Scalars);
7326 
7327       E->VectorizedValue = V;
7328       ++NumVectorInstructions;
7329       return V;
7330     }
7331     case Instruction::GetElementPtr: {
7332       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7333       setInsertPointAfterBundle(E);
7334 
7335       Value *Op0 = vectorizeTree(E->getOperand(0));
7336 
7337       SmallVector<Value *> OpVecs;
7338       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7339         Value *OpVec = vectorizeTree(E->getOperand(J));
7340         OpVecs.push_back(OpVec);
7341       }
7342 
7343       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7344       if (Instruction *I = dyn_cast<Instruction>(V))
7345         V = propagateMetadata(I, E->Scalars);
7346 
7347       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7348       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7349       V = ShuffleBuilder.finalize(V);
7350 
7351       E->VectorizedValue = V;
7352       ++NumVectorInstructions;
7353 
7354       return V;
7355     }
7356     case Instruction::Call: {
7357       CallInst *CI = cast<CallInst>(VL0);
7358       setInsertPointAfterBundle(E);
7359 
7360       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7361       if (Function *FI = CI->getCalledFunction())
7362         IID = FI->getIntrinsicID();
7363 
7364       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7365 
7366       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7367       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7368                           VecCallCosts.first <= VecCallCosts.second;
7369 
7370       Value *ScalarArg = nullptr;
7371       std::vector<Value *> OpVecs;
7372       SmallVector<Type *, 2> TysForDecl =
7373           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7374       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7375         ValueList OpVL;
7376         // Some intrinsics have scalar arguments. This argument should not be
7377         // vectorized.
7378         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7379           CallInst *CEI = cast<CallInst>(VL0);
7380           ScalarArg = CEI->getArgOperand(j);
7381           OpVecs.push_back(CEI->getArgOperand(j));
7382           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7383             TysForDecl.push_back(ScalarArg->getType());
7384           continue;
7385         }
7386 
7387         Value *OpVec = vectorizeTree(E->getOperand(j));
7388         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7389         OpVecs.push_back(OpVec);
7390       }
7391 
7392       Function *CF;
7393       if (!UseIntrinsic) {
7394         VFShape Shape =
7395             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7396                                   VecTy->getNumElements())),
7397                          false /*HasGlobalPred*/);
7398         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7399       } else {
7400         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7401       }
7402 
7403       SmallVector<OperandBundleDef, 1> OpBundles;
7404       CI->getOperandBundlesAsDefs(OpBundles);
7405       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7406 
7407       // The scalar argument uses an in-tree scalar so we add the new vectorized
7408       // call to ExternalUses list to make sure that an extract will be
7409       // generated in the future.
7410       if (ScalarArg) {
7411         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7412           // Find which lane we need to extract.
7413           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7414           ExternalUses.push_back(
7415               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7416         }
7417       }
7418 
7419       propagateIRFlags(V, E->Scalars, VL0);
7420       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7421       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7422       V = ShuffleBuilder.finalize(V);
7423 
7424       E->VectorizedValue = V;
7425       ++NumVectorInstructions;
7426       return V;
7427     }
7428     case Instruction::ShuffleVector: {
7429       assert(E->isAltShuffle() &&
7430              ((Instruction::isBinaryOp(E->getOpcode()) &&
7431                Instruction::isBinaryOp(E->getAltOpcode())) ||
7432               (Instruction::isCast(E->getOpcode()) &&
7433                Instruction::isCast(E->getAltOpcode())) ||
7434               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7435              "Invalid Shuffle Vector Operand");
7436 
7437       Value *LHS = nullptr, *RHS = nullptr;
7438       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7439         setInsertPointAfterBundle(E);
7440         LHS = vectorizeTree(E->getOperand(0));
7441         RHS = vectorizeTree(E->getOperand(1));
7442       } else {
7443         setInsertPointAfterBundle(E);
7444         LHS = vectorizeTree(E->getOperand(0));
7445       }
7446 
7447       if (E->VectorizedValue) {
7448         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7449         return E->VectorizedValue;
7450       }
7451 
7452       Value *V0, *V1;
7453       if (Instruction::isBinaryOp(E->getOpcode())) {
7454         V0 = Builder.CreateBinOp(
7455             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7456         V1 = Builder.CreateBinOp(
7457             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7458       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7459         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7460         auto *AltCI = cast<CmpInst>(E->getAltOp());
7461         CmpInst::Predicate AltPred = AltCI->getPredicate();
7462         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7463       } else {
7464         V0 = Builder.CreateCast(
7465             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7466         V1 = Builder.CreateCast(
7467             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7468       }
7469       // Add V0 and V1 to later analysis to try to find and remove matching
7470       // instruction, if any.
7471       for (Value *V : {V0, V1}) {
7472         if (auto *I = dyn_cast<Instruction>(V)) {
7473           GatherShuffleSeq.insert(I);
7474           CSEBlocks.insert(I->getParent());
7475         }
7476       }
7477 
7478       // Create shuffle to take alternate operations from the vector.
7479       // Also, gather up main and alt scalar ops to propagate IR flags to
7480       // each vector operation.
7481       ValueList OpScalars, AltScalars;
7482       SmallVector<int> Mask;
7483       buildShuffleEntryMask(
7484           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7485           [E](Instruction *I) {
7486             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7487             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7488           },
7489           Mask, &OpScalars, &AltScalars);
7490 
7491       propagateIRFlags(V0, OpScalars);
7492       propagateIRFlags(V1, AltScalars);
7493 
7494       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7495       if (auto *I = dyn_cast<Instruction>(V)) {
7496         V = propagateMetadata(I, E->Scalars);
7497         GatherShuffleSeq.insert(I);
7498         CSEBlocks.insert(I->getParent());
7499       }
7500       V = ShuffleBuilder.finalize(V);
7501 
7502       E->VectorizedValue = V;
7503       ++NumVectorInstructions;
7504 
7505       return V;
7506     }
7507     default:
7508     llvm_unreachable("unknown inst");
7509   }
7510   return nullptr;
7511 }
7512 
7513 Value *BoUpSLP::vectorizeTree() {
7514   ExtraValueToDebugLocsMap ExternallyUsedValues;
7515   return vectorizeTree(ExternallyUsedValues);
7516 }
7517 
7518 Value *
7519 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7520   // All blocks must be scheduled before any instructions are inserted.
7521   for (auto &BSIter : BlocksSchedules) {
7522     scheduleBlock(BSIter.second.get());
7523   }
7524 
7525   Builder.SetInsertPoint(&F->getEntryBlock().front());
7526   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7527 
7528   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7529   // vectorized root. InstCombine will then rewrite the entire expression. We
7530   // sign extend the extracted values below.
7531   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7532   if (MinBWs.count(ScalarRoot)) {
7533     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7534       // If current instr is a phi and not the last phi, insert it after the
7535       // last phi node.
7536       if (isa<PHINode>(I))
7537         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7538       else
7539         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7540     }
7541     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7542     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7543     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7544     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7545     VectorizableTree[0]->VectorizedValue = Trunc;
7546   }
7547 
7548   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7549                     << " values .\n");
7550 
7551   // Extract all of the elements with the external uses.
7552   for (const auto &ExternalUse : ExternalUses) {
7553     Value *Scalar = ExternalUse.Scalar;
7554     llvm::User *User = ExternalUse.User;
7555 
7556     // Skip users that we already RAUW. This happens when one instruction
7557     // has multiple uses of the same value.
7558     if (User && !is_contained(Scalar->users(), User))
7559       continue;
7560     TreeEntry *E = getTreeEntry(Scalar);
7561     assert(E && "Invalid scalar");
7562     assert(E->State != TreeEntry::NeedToGather &&
7563            "Extracting from a gather list");
7564 
7565     Value *Vec = E->VectorizedValue;
7566     assert(Vec && "Can't find vectorizable value");
7567 
7568     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7569     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7570       if (Scalar->getType() != Vec->getType()) {
7571         Value *Ex;
7572         // "Reuse" the existing extract to improve final codegen.
7573         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7574           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7575                                             ES->getOperand(1));
7576         } else {
7577           Ex = Builder.CreateExtractElement(Vec, Lane);
7578         }
7579         // If necessary, sign-extend or zero-extend ScalarRoot
7580         // to the larger type.
7581         if (!MinBWs.count(ScalarRoot))
7582           return Ex;
7583         if (MinBWs[ScalarRoot].second)
7584           return Builder.CreateSExt(Ex, Scalar->getType());
7585         return Builder.CreateZExt(Ex, Scalar->getType());
7586       }
7587       assert(isa<FixedVectorType>(Scalar->getType()) &&
7588              isa<InsertElementInst>(Scalar) &&
7589              "In-tree scalar of vector type is not insertelement?");
7590       return Vec;
7591     };
7592     // If User == nullptr, the Scalar is used as extra arg. Generate
7593     // ExtractElement instruction and update the record for this scalar in
7594     // ExternallyUsedValues.
7595     if (!User) {
7596       assert(ExternallyUsedValues.count(Scalar) &&
7597              "Scalar with nullptr as an external user must be registered in "
7598              "ExternallyUsedValues map");
7599       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7600         Builder.SetInsertPoint(VecI->getParent(),
7601                                std::next(VecI->getIterator()));
7602       } else {
7603         Builder.SetInsertPoint(&F->getEntryBlock().front());
7604       }
7605       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7606       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7607       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7608       auto It = ExternallyUsedValues.find(Scalar);
7609       assert(It != ExternallyUsedValues.end() &&
7610              "Externally used scalar is not found in ExternallyUsedValues");
7611       NewInstLocs.append(It->second);
7612       ExternallyUsedValues.erase(Scalar);
7613       // Required to update internally referenced instructions.
7614       Scalar->replaceAllUsesWith(NewInst);
7615       continue;
7616     }
7617 
7618     // Generate extracts for out-of-tree users.
7619     // Find the insertion point for the extractelement lane.
7620     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7621       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7622         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7623           if (PH->getIncomingValue(i) == Scalar) {
7624             Instruction *IncomingTerminator =
7625                 PH->getIncomingBlock(i)->getTerminator();
7626             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7627               Builder.SetInsertPoint(VecI->getParent(),
7628                                      std::next(VecI->getIterator()));
7629             } else {
7630               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7631             }
7632             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7633             CSEBlocks.insert(PH->getIncomingBlock(i));
7634             PH->setOperand(i, NewInst);
7635           }
7636         }
7637       } else {
7638         Builder.SetInsertPoint(cast<Instruction>(User));
7639         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7640         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7641         User->replaceUsesOfWith(Scalar, NewInst);
7642       }
7643     } else {
7644       Builder.SetInsertPoint(&F->getEntryBlock().front());
7645       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7646       CSEBlocks.insert(&F->getEntryBlock());
7647       User->replaceUsesOfWith(Scalar, NewInst);
7648     }
7649 
7650     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7651   }
7652 
7653   // For each vectorized value:
7654   for (auto &TEPtr : VectorizableTree) {
7655     TreeEntry *Entry = TEPtr.get();
7656 
7657     // No need to handle users of gathered values.
7658     if (Entry->State == TreeEntry::NeedToGather)
7659       continue;
7660 
7661     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7662 
7663     // For each lane:
7664     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7665       Value *Scalar = Entry->Scalars[Lane];
7666 
7667 #ifndef NDEBUG
7668       Type *Ty = Scalar->getType();
7669       if (!Ty->isVoidTy()) {
7670         for (User *U : Scalar->users()) {
7671           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7672 
7673           // It is legal to delete users in the ignorelist.
7674           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7675                   (isa_and_nonnull<Instruction>(U) &&
7676                    isDeleted(cast<Instruction>(U)))) &&
7677                  "Deleting out-of-tree value");
7678         }
7679       }
7680 #endif
7681       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7682       eraseInstruction(cast<Instruction>(Scalar));
7683     }
7684   }
7685 
7686   Builder.ClearInsertionPoint();
7687   InstrElementSize.clear();
7688 
7689   return VectorizableTree[0]->VectorizedValue;
7690 }
7691 
7692 void BoUpSLP::optimizeGatherSequence() {
7693   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7694                     << " gather sequences instructions.\n");
7695   // LICM InsertElementInst sequences.
7696   for (Instruction *I : GatherShuffleSeq) {
7697     if (isDeleted(I))
7698       continue;
7699 
7700     // Check if this block is inside a loop.
7701     Loop *L = LI->getLoopFor(I->getParent());
7702     if (!L)
7703       continue;
7704 
7705     // Check if it has a preheader.
7706     BasicBlock *PreHeader = L->getLoopPreheader();
7707     if (!PreHeader)
7708       continue;
7709 
7710     // If the vector or the element that we insert into it are
7711     // instructions that are defined in this basic block then we can't
7712     // hoist this instruction.
7713     if (any_of(I->operands(), [L](Value *V) {
7714           auto *OpI = dyn_cast<Instruction>(V);
7715           return OpI && L->contains(OpI);
7716         }))
7717       continue;
7718 
7719     // We can hoist this instruction. Move it to the pre-header.
7720     I->moveBefore(PreHeader->getTerminator());
7721   }
7722 
7723   // Make a list of all reachable blocks in our CSE queue.
7724   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7725   CSEWorkList.reserve(CSEBlocks.size());
7726   for (BasicBlock *BB : CSEBlocks)
7727     if (DomTreeNode *N = DT->getNode(BB)) {
7728       assert(DT->isReachableFromEntry(N));
7729       CSEWorkList.push_back(N);
7730     }
7731 
7732   // Sort blocks by domination. This ensures we visit a block after all blocks
7733   // dominating it are visited.
7734   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7735     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7736            "Different nodes should have different DFS numbers");
7737     return A->getDFSNumIn() < B->getDFSNumIn();
7738   });
7739 
7740   // Less defined shuffles can be replaced by the more defined copies.
7741   // Between two shuffles one is less defined if it has the same vector operands
7742   // and its mask indeces are the same as in the first one or undefs. E.g.
7743   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7744   // poison, <0, 0, 0, 0>.
7745   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7746                                            SmallVectorImpl<int> &NewMask) {
7747     if (I1->getType() != I2->getType())
7748       return false;
7749     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7750     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7751     if (!SI1 || !SI2)
7752       return I1->isIdenticalTo(I2);
7753     if (SI1->isIdenticalTo(SI2))
7754       return true;
7755     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7756       if (SI1->getOperand(I) != SI2->getOperand(I))
7757         return false;
7758     // Check if the second instruction is more defined than the first one.
7759     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7760     ArrayRef<int> SM1 = SI1->getShuffleMask();
7761     // Count trailing undefs in the mask to check the final number of used
7762     // registers.
7763     unsigned LastUndefsCnt = 0;
7764     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7765       if (SM1[I] == UndefMaskElem)
7766         ++LastUndefsCnt;
7767       else
7768         LastUndefsCnt = 0;
7769       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7770           NewMask[I] != SM1[I])
7771         return false;
7772       if (NewMask[I] == UndefMaskElem)
7773         NewMask[I] = SM1[I];
7774     }
7775     // Check if the last undefs actually change the final number of used vector
7776     // registers.
7777     return SM1.size() - LastUndefsCnt > 1 &&
7778            TTI->getNumberOfParts(SI1->getType()) ==
7779                TTI->getNumberOfParts(
7780                    FixedVectorType::get(SI1->getType()->getElementType(),
7781                                         SM1.size() - LastUndefsCnt));
7782   };
7783   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7784   // instructions. TODO: We can further optimize this scan if we split the
7785   // instructions into different buckets based on the insert lane.
7786   SmallVector<Instruction *, 16> Visited;
7787   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7788     assert(*I &&
7789            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7790            "Worklist not sorted properly!");
7791     BasicBlock *BB = (*I)->getBlock();
7792     // For all instructions in blocks containing gather sequences:
7793     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7794       if (isDeleted(&In))
7795         continue;
7796       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7797           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7798         continue;
7799 
7800       // Check if we can replace this instruction with any of the
7801       // visited instructions.
7802       bool Replaced = false;
7803       for (Instruction *&V : Visited) {
7804         SmallVector<int> NewMask;
7805         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7806             DT->dominates(V->getParent(), In.getParent())) {
7807           In.replaceAllUsesWith(V);
7808           eraseInstruction(&In);
7809           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7810             if (!NewMask.empty())
7811               SI->setShuffleMask(NewMask);
7812           Replaced = true;
7813           break;
7814         }
7815         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7816             GatherShuffleSeq.contains(V) &&
7817             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7818             DT->dominates(In.getParent(), V->getParent())) {
7819           In.moveAfter(V);
7820           V->replaceAllUsesWith(&In);
7821           eraseInstruction(V);
7822           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7823             if (!NewMask.empty())
7824               SI->setShuffleMask(NewMask);
7825           V = &In;
7826           Replaced = true;
7827           break;
7828         }
7829       }
7830       if (!Replaced) {
7831         assert(!is_contained(Visited, &In));
7832         Visited.push_back(&In);
7833       }
7834     }
7835   }
7836   CSEBlocks.clear();
7837   GatherShuffleSeq.clear();
7838 }
7839 
7840 BoUpSLP::ScheduleData *
7841 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7842   ScheduleData *Bundle = nullptr;
7843   ScheduleData *PrevInBundle = nullptr;
7844   for (Value *V : VL) {
7845     if (doesNotNeedToBeScheduled(V))
7846       continue;
7847     ScheduleData *BundleMember = getScheduleData(V);
7848     assert(BundleMember &&
7849            "no ScheduleData for bundle member "
7850            "(maybe not in same basic block)");
7851     assert(BundleMember->isSchedulingEntity() &&
7852            "bundle member already part of other bundle");
7853     if (PrevInBundle) {
7854       PrevInBundle->NextInBundle = BundleMember;
7855     } else {
7856       Bundle = BundleMember;
7857     }
7858 
7859     // Group the instructions to a bundle.
7860     BundleMember->FirstInBundle = Bundle;
7861     PrevInBundle = BundleMember;
7862   }
7863   assert(Bundle && "Failed to find schedule bundle");
7864   return Bundle;
7865 }
7866 
7867 // Groups the instructions to a bundle (which is then a single scheduling entity)
7868 // and schedules instructions until the bundle gets ready.
7869 Optional<BoUpSLP::ScheduleData *>
7870 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7871                                             const InstructionsState &S) {
7872   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7873   // instructions.
7874   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7875       doesNotNeedToSchedule(VL))
7876     return nullptr;
7877 
7878   // Initialize the instruction bundle.
7879   Instruction *OldScheduleEnd = ScheduleEnd;
7880   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7881 
7882   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7883                                                          ScheduleData *Bundle) {
7884     // The scheduling region got new instructions at the lower end (or it is a
7885     // new region for the first bundle). This makes it necessary to
7886     // recalculate all dependencies.
7887     // It is seldom that this needs to be done a second time after adding the
7888     // initial bundle to the region.
7889     if (ScheduleEnd != OldScheduleEnd) {
7890       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7891         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7892       ReSchedule = true;
7893     }
7894     if (Bundle) {
7895       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7896                         << " in block " << BB->getName() << "\n");
7897       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7898     }
7899 
7900     if (ReSchedule) {
7901       resetSchedule();
7902       initialFillReadyList(ReadyInsts);
7903     }
7904 
7905     // Now try to schedule the new bundle or (if no bundle) just calculate
7906     // dependencies. As soon as the bundle is "ready" it means that there are no
7907     // cyclic dependencies and we can schedule it. Note that's important that we
7908     // don't "schedule" the bundle yet (see cancelScheduling).
7909     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7910            !ReadyInsts.empty()) {
7911       ScheduleData *Picked = ReadyInsts.pop_back_val();
7912       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7913              "must be ready to schedule");
7914       schedule(Picked, ReadyInsts);
7915     }
7916   };
7917 
7918   // Make sure that the scheduling region contains all
7919   // instructions of the bundle.
7920   for (Value *V : VL) {
7921     if (doesNotNeedToBeScheduled(V))
7922       continue;
7923     if (!extendSchedulingRegion(V, S)) {
7924       // If the scheduling region got new instructions at the lower end (or it
7925       // is a new region for the first bundle). This makes it necessary to
7926       // recalculate all dependencies.
7927       // Otherwise the compiler may crash trying to incorrectly calculate
7928       // dependencies and emit instruction in the wrong order at the actual
7929       // scheduling.
7930       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7931       return None;
7932     }
7933   }
7934 
7935   bool ReSchedule = false;
7936   for (Value *V : VL) {
7937     if (doesNotNeedToBeScheduled(V))
7938       continue;
7939     ScheduleData *BundleMember = getScheduleData(V);
7940     assert(BundleMember &&
7941            "no ScheduleData for bundle member (maybe not in same basic block)");
7942 
7943     // Make sure we don't leave the pieces of the bundle in the ready list when
7944     // whole bundle might not be ready.
7945     ReadyInsts.remove(BundleMember);
7946 
7947     if (!BundleMember->IsScheduled)
7948       continue;
7949     // A bundle member was scheduled as single instruction before and now
7950     // needs to be scheduled as part of the bundle. We just get rid of the
7951     // existing schedule.
7952     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7953                       << " was already scheduled\n");
7954     ReSchedule = true;
7955   }
7956 
7957   auto *Bundle = buildBundle(VL);
7958   TryScheduleBundleImpl(ReSchedule, Bundle);
7959   if (!Bundle->isReady()) {
7960     cancelScheduling(VL, S.OpValue);
7961     return None;
7962   }
7963   return Bundle;
7964 }
7965 
7966 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7967                                                 Value *OpValue) {
7968   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7969       doesNotNeedToSchedule(VL))
7970     return;
7971 
7972   if (doesNotNeedToBeScheduled(OpValue))
7973     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7974   ScheduleData *Bundle = getScheduleData(OpValue);
7975   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7976   assert(!Bundle->IsScheduled &&
7977          "Can't cancel bundle which is already scheduled");
7978   assert(Bundle->isSchedulingEntity() &&
7979          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7980          "tried to unbundle something which is not a bundle");
7981 
7982   // Remove the bundle from the ready list.
7983   if (Bundle->isReady())
7984     ReadyInsts.remove(Bundle);
7985 
7986   // Un-bundle: make single instructions out of the bundle.
7987   ScheduleData *BundleMember = Bundle;
7988   while (BundleMember) {
7989     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7990     BundleMember->FirstInBundle = BundleMember;
7991     ScheduleData *Next = BundleMember->NextInBundle;
7992     BundleMember->NextInBundle = nullptr;
7993     BundleMember->TE = nullptr;
7994     if (BundleMember->unscheduledDepsInBundle() == 0) {
7995       ReadyInsts.insert(BundleMember);
7996     }
7997     BundleMember = Next;
7998   }
7999 }
8000 
8001 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
8002   // Allocate a new ScheduleData for the instruction.
8003   if (ChunkPos >= ChunkSize) {
8004     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
8005     ChunkPos = 0;
8006   }
8007   return &(ScheduleDataChunks.back()[ChunkPos++]);
8008 }
8009 
8010 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
8011                                                       const InstructionsState &S) {
8012   if (getScheduleData(V, isOneOf(S, V)))
8013     return true;
8014   Instruction *I = dyn_cast<Instruction>(V);
8015   assert(I && "bundle member must be an instruction");
8016   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
8017          !doesNotNeedToBeScheduled(I) &&
8018          "phi nodes/insertelements/extractelements/extractvalues don't need to "
8019          "be scheduled");
8020   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
8021     ScheduleData *ISD = getScheduleData(I);
8022     if (!ISD)
8023       return false;
8024     assert(isInSchedulingRegion(ISD) &&
8025            "ScheduleData not in scheduling region");
8026     ScheduleData *SD = allocateScheduleDataChunks();
8027     SD->Inst = I;
8028     SD->init(SchedulingRegionID, S.OpValue);
8029     ExtraScheduleDataMap[I][S.OpValue] = SD;
8030     return true;
8031   };
8032   if (CheckScheduleForI(I))
8033     return true;
8034   if (!ScheduleStart) {
8035     // It's the first instruction in the new region.
8036     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
8037     ScheduleStart = I;
8038     ScheduleEnd = I->getNextNode();
8039     if (isOneOf(S, I) != I)
8040       CheckScheduleForI(I);
8041     assert(ScheduleEnd && "tried to vectorize a terminator?");
8042     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
8043     return true;
8044   }
8045   // Search up and down at the same time, because we don't know if the new
8046   // instruction is above or below the existing scheduling region.
8047   BasicBlock::reverse_iterator UpIter =
8048       ++ScheduleStart->getIterator().getReverse();
8049   BasicBlock::reverse_iterator UpperEnd = BB->rend();
8050   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
8051   BasicBlock::iterator LowerEnd = BB->end();
8052   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
8053          &*DownIter != I) {
8054     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
8055       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
8056       return false;
8057     }
8058 
8059     ++UpIter;
8060     ++DownIter;
8061   }
8062   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8063     assert(I->getParent() == ScheduleStart->getParent() &&
8064            "Instruction is in wrong basic block.");
8065     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8066     ScheduleStart = I;
8067     if (isOneOf(S, I) != I)
8068       CheckScheduleForI(I);
8069     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8070                       << "\n");
8071     return true;
8072   }
8073   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8074          "Expected to reach top of the basic block or instruction down the "
8075          "lower end.");
8076   assert(I->getParent() == ScheduleEnd->getParent() &&
8077          "Instruction is in wrong basic block.");
8078   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8079                    nullptr);
8080   ScheduleEnd = I->getNextNode();
8081   if (isOneOf(S, I) != I)
8082     CheckScheduleForI(I);
8083   assert(ScheduleEnd && "tried to vectorize a terminator?");
8084   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8085   return true;
8086 }
8087 
8088 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8089                                                 Instruction *ToI,
8090                                                 ScheduleData *PrevLoadStore,
8091                                                 ScheduleData *NextLoadStore) {
8092   ScheduleData *CurrentLoadStore = PrevLoadStore;
8093   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8094     // No need to allocate data for non-schedulable instructions.
8095     if (doesNotNeedToBeScheduled(I))
8096       continue;
8097     ScheduleData *SD = ScheduleDataMap.lookup(I);
8098     if (!SD) {
8099       SD = allocateScheduleDataChunks();
8100       ScheduleDataMap[I] = SD;
8101       SD->Inst = I;
8102     }
8103     assert(!isInSchedulingRegion(SD) &&
8104            "new ScheduleData already in scheduling region");
8105     SD->init(SchedulingRegionID, I);
8106 
8107     if (I->mayReadOrWriteMemory() &&
8108         (!isa<IntrinsicInst>(I) ||
8109          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8110           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8111               Intrinsic::pseudoprobe))) {
8112       // Update the linked list of memory accessing instructions.
8113       if (CurrentLoadStore) {
8114         CurrentLoadStore->NextLoadStore = SD;
8115       } else {
8116         FirstLoadStoreInRegion = SD;
8117       }
8118       CurrentLoadStore = SD;
8119     }
8120 
8121     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8122         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8123       RegionHasStackSave = true;
8124   }
8125   if (NextLoadStore) {
8126     if (CurrentLoadStore)
8127       CurrentLoadStore->NextLoadStore = NextLoadStore;
8128   } else {
8129     LastLoadStoreInRegion = CurrentLoadStore;
8130   }
8131 }
8132 
8133 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8134                                                      bool InsertInReadyList,
8135                                                      BoUpSLP *SLP) {
8136   assert(SD->isSchedulingEntity());
8137 
8138   SmallVector<ScheduleData *, 10> WorkList;
8139   WorkList.push_back(SD);
8140 
8141   while (!WorkList.empty()) {
8142     ScheduleData *SD = WorkList.pop_back_val();
8143     for (ScheduleData *BundleMember = SD; BundleMember;
8144          BundleMember = BundleMember->NextInBundle) {
8145       assert(isInSchedulingRegion(BundleMember));
8146       if (BundleMember->hasValidDependencies())
8147         continue;
8148 
8149       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8150                  << "\n");
8151       BundleMember->Dependencies = 0;
8152       BundleMember->resetUnscheduledDeps();
8153 
8154       // Handle def-use chain dependencies.
8155       if (BundleMember->OpValue != BundleMember->Inst) {
8156         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8157           BundleMember->Dependencies++;
8158           ScheduleData *DestBundle = UseSD->FirstInBundle;
8159           if (!DestBundle->IsScheduled)
8160             BundleMember->incrementUnscheduledDeps(1);
8161           if (!DestBundle->hasValidDependencies())
8162             WorkList.push_back(DestBundle);
8163         }
8164       } else {
8165         for (User *U : BundleMember->Inst->users()) {
8166           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8167             BundleMember->Dependencies++;
8168             ScheduleData *DestBundle = UseSD->FirstInBundle;
8169             if (!DestBundle->IsScheduled)
8170               BundleMember->incrementUnscheduledDeps(1);
8171             if (!DestBundle->hasValidDependencies())
8172               WorkList.push_back(DestBundle);
8173           }
8174         }
8175       }
8176 
8177       auto makeControlDependent = [&](Instruction *I) {
8178         auto *DepDest = getScheduleData(I);
8179         assert(DepDest && "must be in schedule window");
8180         DepDest->ControlDependencies.push_back(BundleMember);
8181         BundleMember->Dependencies++;
8182         ScheduleData *DestBundle = DepDest->FirstInBundle;
8183         if (!DestBundle->IsScheduled)
8184           BundleMember->incrementUnscheduledDeps(1);
8185         if (!DestBundle->hasValidDependencies())
8186           WorkList.push_back(DestBundle);
8187       };
8188 
8189       // Any instruction which isn't safe to speculate at the begining of the
8190       // block is control dependend on any early exit or non-willreturn call
8191       // which proceeds it.
8192       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8193         for (Instruction *I = BundleMember->Inst->getNextNode();
8194              I != ScheduleEnd; I = I->getNextNode()) {
8195           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8196             continue;
8197 
8198           // Add the dependency
8199           makeControlDependent(I);
8200 
8201           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8202             // Everything past here must be control dependent on I.
8203             break;
8204         }
8205       }
8206 
8207       if (RegionHasStackSave) {
8208         // If we have an inalloc alloca instruction, it needs to be scheduled
8209         // after any preceeding stacksave.  We also need to prevent any alloca
8210         // from reordering above a preceeding stackrestore.
8211         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8212             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8213           for (Instruction *I = BundleMember->Inst->getNextNode();
8214                I != ScheduleEnd; I = I->getNextNode()) {
8215             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8216                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8217               // Any allocas past here must be control dependent on I, and I
8218               // must be memory dependend on BundleMember->Inst.
8219               break;
8220 
8221             if (!isa<AllocaInst>(I))
8222               continue;
8223 
8224             // Add the dependency
8225             makeControlDependent(I);
8226           }
8227         }
8228 
8229         // In addition to the cases handle just above, we need to prevent
8230         // allocas from moving below a stacksave.  The stackrestore case
8231         // is currently thought to be conservatism.
8232         if (isa<AllocaInst>(BundleMember->Inst)) {
8233           for (Instruction *I = BundleMember->Inst->getNextNode();
8234                I != ScheduleEnd; I = I->getNextNode()) {
8235             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8236                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8237               continue;
8238 
8239             // Add the dependency
8240             makeControlDependent(I);
8241             break;
8242           }
8243         }
8244       }
8245 
8246       // Handle the memory dependencies (if any).
8247       ScheduleData *DepDest = BundleMember->NextLoadStore;
8248       if (!DepDest)
8249         continue;
8250       Instruction *SrcInst = BundleMember->Inst;
8251       assert(SrcInst->mayReadOrWriteMemory() &&
8252              "NextLoadStore list for non memory effecting bundle?");
8253       MemoryLocation SrcLoc = getLocation(SrcInst);
8254       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8255       unsigned numAliased = 0;
8256       unsigned DistToSrc = 1;
8257 
8258       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8259         assert(isInSchedulingRegion(DepDest));
8260 
8261         // We have two limits to reduce the complexity:
8262         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8263         //    SLP->isAliased (which is the expensive part in this loop).
8264         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8265         //    the whole loop (even if the loop is fast, it's quadratic).
8266         //    It's important for the loop break condition (see below) to
8267         //    check this limit even between two read-only instructions.
8268         if (DistToSrc >= MaxMemDepDistance ||
8269             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8270              (numAliased >= AliasedCheckLimit ||
8271               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8272 
8273           // We increment the counter only if the locations are aliased
8274           // (instead of counting all alias checks). This gives a better
8275           // balance between reduced runtime and accurate dependencies.
8276           numAliased++;
8277 
8278           DepDest->MemoryDependencies.push_back(BundleMember);
8279           BundleMember->Dependencies++;
8280           ScheduleData *DestBundle = DepDest->FirstInBundle;
8281           if (!DestBundle->IsScheduled) {
8282             BundleMember->incrementUnscheduledDeps(1);
8283           }
8284           if (!DestBundle->hasValidDependencies()) {
8285             WorkList.push_back(DestBundle);
8286           }
8287         }
8288 
8289         // Example, explaining the loop break condition: Let's assume our
8290         // starting instruction is i0 and MaxMemDepDistance = 3.
8291         //
8292         //                      +--------v--v--v
8293         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8294         //             +--------^--^--^
8295         //
8296         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8297         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8298         // Previously we already added dependencies from i3 to i6,i7,i8
8299         // (because of MaxMemDepDistance). As we added a dependency from
8300         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8301         // and we can abort this loop at i6.
8302         if (DistToSrc >= 2 * MaxMemDepDistance)
8303           break;
8304         DistToSrc++;
8305       }
8306     }
8307     if (InsertInReadyList && SD->isReady()) {
8308       ReadyInsts.insert(SD);
8309       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8310                         << "\n");
8311     }
8312   }
8313 }
8314 
8315 void BoUpSLP::BlockScheduling::resetSchedule() {
8316   assert(ScheduleStart &&
8317          "tried to reset schedule on block which has not been scheduled");
8318   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8319     doForAllOpcodes(I, [&](ScheduleData *SD) {
8320       assert(isInSchedulingRegion(SD) &&
8321              "ScheduleData not in scheduling region");
8322       SD->IsScheduled = false;
8323       SD->resetUnscheduledDeps();
8324     });
8325   }
8326   ReadyInsts.clear();
8327 }
8328 
8329 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8330   if (!BS->ScheduleStart)
8331     return;
8332 
8333   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8334 
8335   // A key point - if we got here, pre-scheduling was able to find a valid
8336   // scheduling of the sub-graph of the scheduling window which consists
8337   // of all vector bundles and their transitive users.  As such, we do not
8338   // need to reschedule anything *outside of* that subgraph.
8339 
8340   BS->resetSchedule();
8341 
8342   // For the real scheduling we use a more sophisticated ready-list: it is
8343   // sorted by the original instruction location. This lets the final schedule
8344   // be as  close as possible to the original instruction order.
8345   // WARNING: If changing this order causes a correctness issue, that means
8346   // there is some missing dependence edge in the schedule data graph.
8347   struct ScheduleDataCompare {
8348     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8349       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8350     }
8351   };
8352   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8353 
8354   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8355   // and fill the ready-list with initial instructions.
8356   int Idx = 0;
8357   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8358        I = I->getNextNode()) {
8359     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8360       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8361       (void)SDTE;
8362       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8363               SD->isPartOfBundle() ==
8364                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8365              "scheduler and vectorizer bundle mismatch");
8366       SD->FirstInBundle->SchedulingPriority = Idx++;
8367 
8368       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8369         BS->calculateDependencies(SD, false, this);
8370     });
8371   }
8372   BS->initialFillReadyList(ReadyInsts);
8373 
8374   Instruction *LastScheduledInst = BS->ScheduleEnd;
8375 
8376   // Do the "real" scheduling.
8377   while (!ReadyInsts.empty()) {
8378     ScheduleData *picked = *ReadyInsts.begin();
8379     ReadyInsts.erase(ReadyInsts.begin());
8380 
8381     // Move the scheduled instruction(s) to their dedicated places, if not
8382     // there yet.
8383     for (ScheduleData *BundleMember = picked; BundleMember;
8384          BundleMember = BundleMember->NextInBundle) {
8385       Instruction *pickedInst = BundleMember->Inst;
8386       if (pickedInst->getNextNode() != LastScheduledInst)
8387         pickedInst->moveBefore(LastScheduledInst);
8388       LastScheduledInst = pickedInst;
8389     }
8390 
8391     BS->schedule(picked, ReadyInsts);
8392   }
8393 
8394   // Check that we didn't break any of our invariants.
8395 #ifdef EXPENSIVE_CHECKS
8396   BS->verify();
8397 #endif
8398 
8399 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8400   // Check that all schedulable entities got scheduled
8401   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8402     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8403       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8404         assert(SD->IsScheduled && "must be scheduled at this point");
8405       }
8406     });
8407   }
8408 #endif
8409 
8410   // Avoid duplicate scheduling of the block.
8411   BS->ScheduleStart = nullptr;
8412 }
8413 
8414 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8415   // If V is a store, just return the width of the stored value (or value
8416   // truncated just before storing) without traversing the expression tree.
8417   // This is the common case.
8418   if (auto *Store = dyn_cast<StoreInst>(V)) {
8419     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8420       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8421     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8422   }
8423 
8424   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8425     return getVectorElementSize(IEI->getOperand(1));
8426 
8427   auto E = InstrElementSize.find(V);
8428   if (E != InstrElementSize.end())
8429     return E->second;
8430 
8431   // If V is not a store, we can traverse the expression tree to find loads
8432   // that feed it. The type of the loaded value may indicate a more suitable
8433   // width than V's type. We want to base the vector element size on the width
8434   // of memory operations where possible.
8435   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8436   SmallPtrSet<Instruction *, 16> Visited;
8437   if (auto *I = dyn_cast<Instruction>(V)) {
8438     Worklist.emplace_back(I, I->getParent());
8439     Visited.insert(I);
8440   }
8441 
8442   // Traverse the expression tree in bottom-up order looking for loads. If we
8443   // encounter an instruction we don't yet handle, we give up.
8444   auto Width = 0u;
8445   while (!Worklist.empty()) {
8446     Instruction *I;
8447     BasicBlock *Parent;
8448     std::tie(I, Parent) = Worklist.pop_back_val();
8449 
8450     // We should only be looking at scalar instructions here. If the current
8451     // instruction has a vector type, skip.
8452     auto *Ty = I->getType();
8453     if (isa<VectorType>(Ty))
8454       continue;
8455 
8456     // If the current instruction is a load, update MaxWidth to reflect the
8457     // width of the loaded value.
8458     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8459         isa<ExtractValueInst>(I))
8460       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8461 
8462     // Otherwise, we need to visit the operands of the instruction. We only
8463     // handle the interesting cases from buildTree here. If an operand is an
8464     // instruction we haven't yet visited and from the same basic block as the
8465     // user or the use is a PHI node, we add it to the worklist.
8466     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8467              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8468              isa<UnaryOperator>(I)) {
8469       for (Use &U : I->operands())
8470         if (auto *J = dyn_cast<Instruction>(U.get()))
8471           if (Visited.insert(J).second &&
8472               (isa<PHINode>(I) || J->getParent() == Parent))
8473             Worklist.emplace_back(J, J->getParent());
8474     } else {
8475       break;
8476     }
8477   }
8478 
8479   // If we didn't encounter a memory access in the expression tree, or if we
8480   // gave up for some reason, just return the width of V. Otherwise, return the
8481   // maximum width we found.
8482   if (!Width) {
8483     if (auto *CI = dyn_cast<CmpInst>(V))
8484       V = CI->getOperand(0);
8485     Width = DL->getTypeSizeInBits(V->getType());
8486   }
8487 
8488   for (Instruction *I : Visited)
8489     InstrElementSize[I] = Width;
8490 
8491   return Width;
8492 }
8493 
8494 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8495 // smaller type with a truncation. We collect the values that will be demoted
8496 // in ToDemote and additional roots that require investigating in Roots.
8497 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8498                                   SmallVectorImpl<Value *> &ToDemote,
8499                                   SmallVectorImpl<Value *> &Roots) {
8500   // We can always demote constants.
8501   if (isa<Constant>(V)) {
8502     ToDemote.push_back(V);
8503     return true;
8504   }
8505 
8506   // If the value is not an instruction in the expression with only one use, it
8507   // cannot be demoted.
8508   auto *I = dyn_cast<Instruction>(V);
8509   if (!I || !I->hasOneUse() || !Expr.count(I))
8510     return false;
8511 
8512   switch (I->getOpcode()) {
8513 
8514   // We can always demote truncations and extensions. Since truncations can
8515   // seed additional demotion, we save the truncated value.
8516   case Instruction::Trunc:
8517     Roots.push_back(I->getOperand(0));
8518     break;
8519   case Instruction::ZExt:
8520   case Instruction::SExt:
8521     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8522         isa<InsertElementInst>(I->getOperand(0)))
8523       return false;
8524     break;
8525 
8526   // We can demote certain binary operations if we can demote both of their
8527   // operands.
8528   case Instruction::Add:
8529   case Instruction::Sub:
8530   case Instruction::Mul:
8531   case Instruction::And:
8532   case Instruction::Or:
8533   case Instruction::Xor:
8534     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8535         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8536       return false;
8537     break;
8538 
8539   // We can demote selects if we can demote their true and false values.
8540   case Instruction::Select: {
8541     SelectInst *SI = cast<SelectInst>(I);
8542     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8543         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8544       return false;
8545     break;
8546   }
8547 
8548   // We can demote phis if we can demote all their incoming operands. Note that
8549   // we don't need to worry about cycles since we ensure single use above.
8550   case Instruction::PHI: {
8551     PHINode *PN = cast<PHINode>(I);
8552     for (Value *IncValue : PN->incoming_values())
8553       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8554         return false;
8555     break;
8556   }
8557 
8558   // Otherwise, conservatively give up.
8559   default:
8560     return false;
8561   }
8562 
8563   // Record the value that we can demote.
8564   ToDemote.push_back(V);
8565   return true;
8566 }
8567 
8568 void BoUpSLP::computeMinimumValueSizes() {
8569   // If there are no external uses, the expression tree must be rooted by a
8570   // store. We can't demote in-memory values, so there is nothing to do here.
8571   if (ExternalUses.empty())
8572     return;
8573 
8574   // We only attempt to truncate integer expressions.
8575   auto &TreeRoot = VectorizableTree[0]->Scalars;
8576   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8577   if (!TreeRootIT)
8578     return;
8579 
8580   // If the expression is not rooted by a store, these roots should have
8581   // external uses. We will rely on InstCombine to rewrite the expression in
8582   // the narrower type. However, InstCombine only rewrites single-use values.
8583   // This means that if a tree entry other than a root is used externally, it
8584   // must have multiple uses and InstCombine will not rewrite it. The code
8585   // below ensures that only the roots are used externally.
8586   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8587   for (auto &EU : ExternalUses)
8588     if (!Expr.erase(EU.Scalar))
8589       return;
8590   if (!Expr.empty())
8591     return;
8592 
8593   // Collect the scalar values of the vectorizable expression. We will use this
8594   // context to determine which values can be demoted. If we see a truncation,
8595   // we mark it as seeding another demotion.
8596   for (auto &EntryPtr : VectorizableTree)
8597     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8598 
8599   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8600   // have a single external user that is not in the vectorizable tree.
8601   for (auto *Root : TreeRoot)
8602     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8603       return;
8604 
8605   // Conservatively determine if we can actually truncate the roots of the
8606   // expression. Collect the values that can be demoted in ToDemote and
8607   // additional roots that require investigating in Roots.
8608   SmallVector<Value *, 32> ToDemote;
8609   SmallVector<Value *, 4> Roots;
8610   for (auto *Root : TreeRoot)
8611     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8612       return;
8613 
8614   // The maximum bit width required to represent all the values that can be
8615   // demoted without loss of precision. It would be safe to truncate the roots
8616   // of the expression to this width.
8617   auto MaxBitWidth = 8u;
8618 
8619   // We first check if all the bits of the roots are demanded. If they're not,
8620   // we can truncate the roots to this narrower type.
8621   for (auto *Root : TreeRoot) {
8622     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8623     MaxBitWidth = std::max<unsigned>(
8624         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8625   }
8626 
8627   // True if the roots can be zero-extended back to their original type, rather
8628   // than sign-extended. We know that if the leading bits are not demanded, we
8629   // can safely zero-extend. So we initialize IsKnownPositive to True.
8630   bool IsKnownPositive = true;
8631 
8632   // If all the bits of the roots are demanded, we can try a little harder to
8633   // compute a narrower type. This can happen, for example, if the roots are
8634   // getelementptr indices. InstCombine promotes these indices to the pointer
8635   // width. Thus, all their bits are technically demanded even though the
8636   // address computation might be vectorized in a smaller type.
8637   //
8638   // We start by looking at each entry that can be demoted. We compute the
8639   // maximum bit width required to store the scalar by using ValueTracking to
8640   // compute the number of high-order bits we can truncate.
8641   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8642       llvm::all_of(TreeRoot, [](Value *R) {
8643         assert(R->hasOneUse() && "Root should have only one use!");
8644         return isa<GetElementPtrInst>(R->user_back());
8645       })) {
8646     MaxBitWidth = 8u;
8647 
8648     // Determine if the sign bit of all the roots is known to be zero. If not,
8649     // IsKnownPositive is set to False.
8650     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8651       KnownBits Known = computeKnownBits(R, *DL);
8652       return Known.isNonNegative();
8653     });
8654 
8655     // Determine the maximum number of bits required to store the scalar
8656     // values.
8657     for (auto *Scalar : ToDemote) {
8658       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8659       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8660       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8661     }
8662 
8663     // If we can't prove that the sign bit is zero, we must add one to the
8664     // maximum bit width to account for the unknown sign bit. This preserves
8665     // the existing sign bit so we can safely sign-extend the root back to the
8666     // original type. Otherwise, if we know the sign bit is zero, we will
8667     // zero-extend the root instead.
8668     //
8669     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8670     //        one to the maximum bit width will yield a larger-than-necessary
8671     //        type. In general, we need to add an extra bit only if we can't
8672     //        prove that the upper bit of the original type is equal to the
8673     //        upper bit of the proposed smaller type. If these two bits are the
8674     //        same (either zero or one) we know that sign-extending from the
8675     //        smaller type will result in the same value. Here, since we can't
8676     //        yet prove this, we are just making the proposed smaller type
8677     //        larger to ensure correctness.
8678     if (!IsKnownPositive)
8679       ++MaxBitWidth;
8680   }
8681 
8682   // Round MaxBitWidth up to the next power-of-two.
8683   if (!isPowerOf2_64(MaxBitWidth))
8684     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8685 
8686   // If the maximum bit width we compute is less than the with of the roots'
8687   // type, we can proceed with the narrowing. Otherwise, do nothing.
8688   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8689     return;
8690 
8691   // If we can truncate the root, we must collect additional values that might
8692   // be demoted as a result. That is, those seeded by truncations we will
8693   // modify.
8694   while (!Roots.empty())
8695     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8696 
8697   // Finally, map the values we can demote to the maximum bit with we computed.
8698   for (auto *Scalar : ToDemote)
8699     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8700 }
8701 
8702 namespace {
8703 
8704 /// The SLPVectorizer Pass.
8705 struct SLPVectorizer : public FunctionPass {
8706   SLPVectorizerPass Impl;
8707 
8708   /// Pass identification, replacement for typeid
8709   static char ID;
8710 
8711   explicit SLPVectorizer() : FunctionPass(ID) {
8712     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8713   }
8714 
8715   bool doInitialization(Module &M) override { return false; }
8716 
8717   bool runOnFunction(Function &F) override {
8718     if (skipFunction(F))
8719       return false;
8720 
8721     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8722     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8723     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8724     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8725     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8726     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8727     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8728     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8729     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8730     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8731 
8732     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8733   }
8734 
8735   void getAnalysisUsage(AnalysisUsage &AU) const override {
8736     FunctionPass::getAnalysisUsage(AU);
8737     AU.addRequired<AssumptionCacheTracker>();
8738     AU.addRequired<ScalarEvolutionWrapperPass>();
8739     AU.addRequired<AAResultsWrapperPass>();
8740     AU.addRequired<TargetTransformInfoWrapperPass>();
8741     AU.addRequired<LoopInfoWrapperPass>();
8742     AU.addRequired<DominatorTreeWrapperPass>();
8743     AU.addRequired<DemandedBitsWrapperPass>();
8744     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8745     AU.addRequired<InjectTLIMappingsLegacy>();
8746     AU.addPreserved<LoopInfoWrapperPass>();
8747     AU.addPreserved<DominatorTreeWrapperPass>();
8748     AU.addPreserved<AAResultsWrapperPass>();
8749     AU.addPreserved<GlobalsAAWrapperPass>();
8750     AU.setPreservesCFG();
8751   }
8752 };
8753 
8754 } // end anonymous namespace
8755 
8756 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8757   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8758   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8759   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8760   auto *AA = &AM.getResult<AAManager>(F);
8761   auto *LI = &AM.getResult<LoopAnalysis>(F);
8762   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8763   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8764   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8765   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8766 
8767   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8768   if (!Changed)
8769     return PreservedAnalyses::all();
8770 
8771   PreservedAnalyses PA;
8772   PA.preserveSet<CFGAnalyses>();
8773   return PA;
8774 }
8775 
8776 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8777                                 TargetTransformInfo *TTI_,
8778                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8779                                 LoopInfo *LI_, DominatorTree *DT_,
8780                                 AssumptionCache *AC_, DemandedBits *DB_,
8781                                 OptimizationRemarkEmitter *ORE_) {
8782   if (!RunSLPVectorization)
8783     return false;
8784   SE = SE_;
8785   TTI = TTI_;
8786   TLI = TLI_;
8787   AA = AA_;
8788   LI = LI_;
8789   DT = DT_;
8790   AC = AC_;
8791   DB = DB_;
8792   DL = &F.getParent()->getDataLayout();
8793 
8794   Stores.clear();
8795   GEPs.clear();
8796   bool Changed = false;
8797 
8798   // If the target claims to have no vector registers don't attempt
8799   // vectorization.
8800   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8801     LLVM_DEBUG(
8802         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8803     return false;
8804   }
8805 
8806   // Don't vectorize when the attribute NoImplicitFloat is used.
8807   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8808     return false;
8809 
8810   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8811 
8812   // Use the bottom up slp vectorizer to construct chains that start with
8813   // store instructions.
8814   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8815 
8816   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8817   // delete instructions.
8818 
8819   // Update DFS numbers now so that we can use them for ordering.
8820   DT->updateDFSNumbers();
8821 
8822   // Scan the blocks in the function in post order.
8823   for (auto BB : post_order(&F.getEntryBlock())) {
8824     collectSeedInstructions(BB);
8825 
8826     // Vectorize trees that end at stores.
8827     if (!Stores.empty()) {
8828       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8829                         << " underlying objects.\n");
8830       Changed |= vectorizeStoreChains(R);
8831     }
8832 
8833     // Vectorize trees that end at reductions.
8834     Changed |= vectorizeChainsInBlock(BB, R);
8835 
8836     // Vectorize the index computations of getelementptr instructions. This
8837     // is primarily intended to catch gather-like idioms ending at
8838     // non-consecutive loads.
8839     if (!GEPs.empty()) {
8840       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8841                         << " underlying objects.\n");
8842       Changed |= vectorizeGEPIndices(BB, R);
8843     }
8844   }
8845 
8846   if (Changed) {
8847     R.optimizeGatherSequence();
8848     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8849   }
8850   return Changed;
8851 }
8852 
8853 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8854                                             unsigned Idx) {
8855   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8856                     << "\n");
8857   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8858   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8859   unsigned VF = Chain.size();
8860 
8861   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8862     return false;
8863 
8864   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8865                     << "\n");
8866 
8867   R.buildTree(Chain);
8868   if (R.isTreeTinyAndNotFullyVectorizable())
8869     return false;
8870   if (R.isLoadCombineCandidate())
8871     return false;
8872   R.reorderTopToBottom();
8873   R.reorderBottomToTop();
8874   R.buildExternalUses();
8875 
8876   R.computeMinimumValueSizes();
8877 
8878   InstructionCost Cost = R.getTreeCost();
8879 
8880   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8881   if (Cost < -SLPCostThreshold) {
8882     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8883 
8884     using namespace ore;
8885 
8886     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8887                                         cast<StoreInst>(Chain[0]))
8888                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8889                      << " and with tree size "
8890                      << NV("TreeSize", R.getTreeSize()));
8891 
8892     R.vectorizeTree();
8893     return true;
8894   }
8895 
8896   return false;
8897 }
8898 
8899 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8900                                         BoUpSLP &R) {
8901   // We may run into multiple chains that merge into a single chain. We mark the
8902   // stores that we vectorized so that we don't visit the same store twice.
8903   BoUpSLP::ValueSet VectorizedStores;
8904   bool Changed = false;
8905 
8906   int E = Stores.size();
8907   SmallBitVector Tails(E, false);
8908   int MaxIter = MaxStoreLookup.getValue();
8909   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8910       E, std::make_pair(E, INT_MAX));
8911   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8912   int IterCnt;
8913   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8914                                   &CheckedPairs,
8915                                   &ConsecutiveChain](int K, int Idx) {
8916     if (IterCnt >= MaxIter)
8917       return true;
8918     if (CheckedPairs[Idx].test(K))
8919       return ConsecutiveChain[K].second == 1 &&
8920              ConsecutiveChain[K].first == Idx;
8921     ++IterCnt;
8922     CheckedPairs[Idx].set(K);
8923     CheckedPairs[K].set(Idx);
8924     Optional<int> Diff = getPointersDiff(
8925         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8926         Stores[Idx]->getValueOperand()->getType(),
8927         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8928     if (!Diff || *Diff == 0)
8929       return false;
8930     int Val = *Diff;
8931     if (Val < 0) {
8932       if (ConsecutiveChain[Idx].second > -Val) {
8933         Tails.set(K);
8934         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8935       }
8936       return false;
8937     }
8938     if (ConsecutiveChain[K].second <= Val)
8939       return false;
8940 
8941     Tails.set(Idx);
8942     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8943     return Val == 1;
8944   };
8945   // Do a quadratic search on all of the given stores in reverse order and find
8946   // all of the pairs of stores that follow each other.
8947   for (int Idx = E - 1; Idx >= 0; --Idx) {
8948     // If a store has multiple consecutive store candidates, search according
8949     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8950     // This is because usually pairing with immediate succeeding or preceding
8951     // candidate create the best chance to find slp vectorization opportunity.
8952     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8953     IterCnt = 0;
8954     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8955       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8956           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8957         break;
8958   }
8959 
8960   // Tracks if we tried to vectorize stores starting from the given tail
8961   // already.
8962   SmallBitVector TriedTails(E, false);
8963   // For stores that start but don't end a link in the chain:
8964   for (int Cnt = E; Cnt > 0; --Cnt) {
8965     int I = Cnt - 1;
8966     if (ConsecutiveChain[I].first == E || Tails.test(I))
8967       continue;
8968     // We found a store instr that starts a chain. Now follow the chain and try
8969     // to vectorize it.
8970     BoUpSLP::ValueList Operands;
8971     // Collect the chain into a list.
8972     while (I != E && !VectorizedStores.count(Stores[I])) {
8973       Operands.push_back(Stores[I]);
8974       Tails.set(I);
8975       if (ConsecutiveChain[I].second != 1) {
8976         // Mark the new end in the chain and go back, if required. It might be
8977         // required if the original stores come in reversed order, for example.
8978         if (ConsecutiveChain[I].first != E &&
8979             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8980             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8981           TriedTails.set(I);
8982           Tails.reset(ConsecutiveChain[I].first);
8983           if (Cnt < ConsecutiveChain[I].first + 2)
8984             Cnt = ConsecutiveChain[I].first + 2;
8985         }
8986         break;
8987       }
8988       // Move to the next value in the chain.
8989       I = ConsecutiveChain[I].first;
8990     }
8991     assert(!Operands.empty() && "Expected non-empty list of stores.");
8992 
8993     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8994     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8995     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8996 
8997     unsigned MinVF = R.getMinVF(EltSize);
8998     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8999                               MaxElts);
9000 
9001     // FIXME: Is division-by-2 the correct step? Should we assert that the
9002     // register size is a power-of-2?
9003     unsigned StartIdx = 0;
9004     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
9005       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
9006         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
9007         if (!VectorizedStores.count(Slice.front()) &&
9008             !VectorizedStores.count(Slice.back()) &&
9009             vectorizeStoreChain(Slice, R, Cnt)) {
9010           // Mark the vectorized stores so that we don't vectorize them again.
9011           VectorizedStores.insert(Slice.begin(), Slice.end());
9012           Changed = true;
9013           // If we vectorized initial block, no need to try to vectorize it
9014           // again.
9015           if (Cnt == StartIdx)
9016             StartIdx += Size;
9017           Cnt += Size;
9018           continue;
9019         }
9020         ++Cnt;
9021       }
9022       // Check if the whole array was vectorized already - exit.
9023       if (StartIdx >= Operands.size())
9024         break;
9025     }
9026   }
9027 
9028   return Changed;
9029 }
9030 
9031 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
9032   // Initialize the collections. We will make a single pass over the block.
9033   Stores.clear();
9034   GEPs.clear();
9035 
9036   // Visit the store and getelementptr instructions in BB and organize them in
9037   // Stores and GEPs according to the underlying objects of their pointer
9038   // operands.
9039   for (Instruction &I : *BB) {
9040     // Ignore store instructions that are volatile or have a pointer operand
9041     // that doesn't point to a scalar type.
9042     if (auto *SI = dyn_cast<StoreInst>(&I)) {
9043       if (!SI->isSimple())
9044         continue;
9045       if (!isValidElementType(SI->getValueOperand()->getType()))
9046         continue;
9047       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
9048     }
9049 
9050     // Ignore getelementptr instructions that have more than one index, a
9051     // constant index, or a pointer operand that doesn't point to a scalar
9052     // type.
9053     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
9054       auto Idx = GEP->idx_begin()->get();
9055       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
9056         continue;
9057       if (!isValidElementType(Idx->getType()))
9058         continue;
9059       if (GEP->getType()->isVectorTy())
9060         continue;
9061       GEPs[GEP->getPointerOperand()].push_back(GEP);
9062     }
9063   }
9064 }
9065 
9066 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9067   if (!A || !B)
9068     return false;
9069   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9070     return false;
9071   Value *VL[] = {A, B};
9072   return tryToVectorizeList(VL, R);
9073 }
9074 
9075 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9076                                            bool LimitForRegisterSize) {
9077   if (VL.size() < 2)
9078     return false;
9079 
9080   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9081                     << VL.size() << ".\n");
9082 
9083   // Check that all of the parts are instructions of the same type,
9084   // we permit an alternate opcode via InstructionsState.
9085   InstructionsState S = getSameOpcode(VL);
9086   if (!S.getOpcode())
9087     return false;
9088 
9089   Instruction *I0 = cast<Instruction>(S.OpValue);
9090   // Make sure invalid types (including vector type) are rejected before
9091   // determining vectorization factor for scalar instructions.
9092   for (Value *V : VL) {
9093     Type *Ty = V->getType();
9094     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9095       // NOTE: the following will give user internal llvm type name, which may
9096       // not be useful.
9097       R.getORE()->emit([&]() {
9098         std::string type_str;
9099         llvm::raw_string_ostream rso(type_str);
9100         Ty->print(rso);
9101         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9102                << "Cannot SLP vectorize list: type "
9103                << rso.str() + " is unsupported by vectorizer";
9104       });
9105       return false;
9106     }
9107   }
9108 
9109   unsigned Sz = R.getVectorElementSize(I0);
9110   unsigned MinVF = R.getMinVF(Sz);
9111   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9112   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9113   if (MaxVF < 2) {
9114     R.getORE()->emit([&]() {
9115       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9116              << "Cannot SLP vectorize list: vectorization factor "
9117              << "less than 2 is not supported";
9118     });
9119     return false;
9120   }
9121 
9122   bool Changed = false;
9123   bool CandidateFound = false;
9124   InstructionCost MinCost = SLPCostThreshold.getValue();
9125   Type *ScalarTy = VL[0]->getType();
9126   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9127     ScalarTy = IE->getOperand(1)->getType();
9128 
9129   unsigned NextInst = 0, MaxInst = VL.size();
9130   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9131     // No actual vectorization should happen, if number of parts is the same as
9132     // provided vectorization factor (i.e. the scalar type is used for vector
9133     // code during codegen).
9134     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9135     if (TTI->getNumberOfParts(VecTy) == VF)
9136       continue;
9137     for (unsigned I = NextInst; I < MaxInst; ++I) {
9138       unsigned OpsWidth = 0;
9139 
9140       if (I + VF > MaxInst)
9141         OpsWidth = MaxInst - I;
9142       else
9143         OpsWidth = VF;
9144 
9145       if (!isPowerOf2_32(OpsWidth))
9146         continue;
9147 
9148       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9149           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9150         break;
9151 
9152       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9153       // Check that a previous iteration of this loop did not delete the Value.
9154       if (llvm::any_of(Ops, [&R](Value *V) {
9155             auto *I = dyn_cast<Instruction>(V);
9156             return I && R.isDeleted(I);
9157           }))
9158         continue;
9159 
9160       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9161                         << "\n");
9162 
9163       R.buildTree(Ops);
9164       if (R.isTreeTinyAndNotFullyVectorizable())
9165         continue;
9166       R.reorderTopToBottom();
9167       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9168       R.buildExternalUses();
9169 
9170       R.computeMinimumValueSizes();
9171       InstructionCost Cost = R.getTreeCost();
9172       CandidateFound = true;
9173       MinCost = std::min(MinCost, Cost);
9174 
9175       if (Cost < -SLPCostThreshold) {
9176         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9177         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9178                                                     cast<Instruction>(Ops[0]))
9179                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9180                                  << " and with tree size "
9181                                  << ore::NV("TreeSize", R.getTreeSize()));
9182 
9183         R.vectorizeTree();
9184         // Move to the next bundle.
9185         I += VF - 1;
9186         NextInst = I + 1;
9187         Changed = true;
9188       }
9189     }
9190   }
9191 
9192   if (!Changed && CandidateFound) {
9193     R.getORE()->emit([&]() {
9194       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9195              << "List vectorization was possible but not beneficial with cost "
9196              << ore::NV("Cost", MinCost) << " >= "
9197              << ore::NV("Treshold", -SLPCostThreshold);
9198     });
9199   } else if (!Changed) {
9200     R.getORE()->emit([&]() {
9201       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9202              << "Cannot SLP vectorize list: vectorization was impossible"
9203              << " with available vectorization factors";
9204     });
9205   }
9206   return Changed;
9207 }
9208 
9209 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9210   if (!I)
9211     return false;
9212 
9213   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9214     return false;
9215 
9216   Value *P = I->getParent();
9217 
9218   // Vectorize in current basic block only.
9219   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9220   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9221   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9222     return false;
9223 
9224   // Try to vectorize V.
9225   if (tryToVectorizePair(Op0, Op1, R))
9226     return true;
9227 
9228   auto *A = dyn_cast<BinaryOperator>(Op0);
9229   auto *B = dyn_cast<BinaryOperator>(Op1);
9230   // Try to skip B.
9231   if (B && B->hasOneUse()) {
9232     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9233     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9234     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9235       return true;
9236     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9237       return true;
9238   }
9239 
9240   // Try to skip A.
9241   if (A && A->hasOneUse()) {
9242     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9243     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9244     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9245       return true;
9246     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9247       return true;
9248   }
9249   return false;
9250 }
9251 
9252 namespace {
9253 
9254 /// Model horizontal reductions.
9255 ///
9256 /// A horizontal reduction is a tree of reduction instructions that has values
9257 /// that can be put into a vector as its leaves. For example:
9258 ///
9259 /// mul mul mul mul
9260 ///  \  /    \  /
9261 ///   +       +
9262 ///    \     /
9263 ///       +
9264 /// This tree has "mul" as its leaf values and "+" as its reduction
9265 /// instructions. A reduction can feed into a store or a binary operation
9266 /// feeding a phi.
9267 ///    ...
9268 ///    \  /
9269 ///     +
9270 ///     |
9271 ///  phi +=
9272 ///
9273 ///  Or:
9274 ///    ...
9275 ///    \  /
9276 ///     +
9277 ///     |
9278 ///   *p =
9279 ///
9280 class HorizontalReduction {
9281   using ReductionOpsType = SmallVector<Value *, 16>;
9282   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9283   ReductionOpsListType ReductionOps;
9284   /// List of possibly reduced values.
9285   SmallVector<SmallVector<Value *>> ReducedVals;
9286   /// Maps reduced value to the corresponding reduction operation.
9287   DenseMap<Value *, Instruction *> ReducedValsToOps;
9288   // Use map vector to make stable output.
9289   MapVector<Instruction *, Value *> ExtraArgs;
9290   WeakTrackingVH ReductionRoot;
9291   /// The type of reduction operation.
9292   RecurKind RdxKind;
9293 
9294   static bool isCmpSelMinMax(Instruction *I) {
9295     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9296            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9297   }
9298 
9299   // And/or are potentially poison-safe logical patterns like:
9300   // select x, y, false
9301   // select x, true, y
9302   static bool isBoolLogicOp(Instruction *I) {
9303     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9304            match(I, m_LogicalOr(m_Value(), m_Value()));
9305   }
9306 
9307   /// Checks if instruction is associative and can be vectorized.
9308   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9309     if (Kind == RecurKind::None)
9310       return false;
9311 
9312     // Integer ops that map to select instructions or intrinsics are fine.
9313     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9314         isBoolLogicOp(I))
9315       return true;
9316 
9317     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9318       // FP min/max are associative except for NaN and -0.0. We do not
9319       // have to rule out -0.0 here because the intrinsic semantics do not
9320       // specify a fixed result for it.
9321       return I->getFastMathFlags().noNaNs();
9322     }
9323 
9324     return I->isAssociative();
9325   }
9326 
9327   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9328     // Poison-safe 'or' takes the form: select X, true, Y
9329     // To make that work with the normal operand processing, we skip the
9330     // true value operand.
9331     // TODO: Change the code and data structures to handle this without a hack.
9332     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9333       return I->getOperand(2);
9334     return I->getOperand(Index);
9335   }
9336 
9337   /// Creates reduction operation with the current opcode.
9338   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9339                          Value *RHS, const Twine &Name, bool UseSelect) {
9340     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9341     switch (Kind) {
9342     case RecurKind::Or:
9343       if (UseSelect &&
9344           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9345         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9346       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9347                                  Name);
9348     case RecurKind::And:
9349       if (UseSelect &&
9350           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9351         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9352       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9353                                  Name);
9354     case RecurKind::Add:
9355     case RecurKind::Mul:
9356     case RecurKind::Xor:
9357     case RecurKind::FAdd:
9358     case RecurKind::FMul:
9359       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9360                                  Name);
9361     case RecurKind::FMax:
9362       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9363     case RecurKind::FMin:
9364       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9365     case RecurKind::SMax:
9366       if (UseSelect) {
9367         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9368         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9369       }
9370       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9371     case RecurKind::SMin:
9372       if (UseSelect) {
9373         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9374         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9375       }
9376       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9377     case RecurKind::UMax:
9378       if (UseSelect) {
9379         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9380         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9381       }
9382       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9383     case RecurKind::UMin:
9384       if (UseSelect) {
9385         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9386         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9387       }
9388       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9389     default:
9390       llvm_unreachable("Unknown reduction operation.");
9391     }
9392   }
9393 
9394   /// Creates reduction operation with the current opcode with the IR flags
9395   /// from \p ReductionOps.
9396   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9397                          Value *RHS, const Twine &Name,
9398                          const ReductionOpsListType &ReductionOps) {
9399     bool UseSelect = ReductionOps.size() == 2 ||
9400                      // Logical or/and.
9401                      (ReductionOps.size() == 1 &&
9402                       isa<SelectInst>(ReductionOps.front().front()));
9403     assert((!UseSelect || ReductionOps.size() != 2 ||
9404             isa<SelectInst>(ReductionOps[1][0])) &&
9405            "Expected cmp + select pairs for reduction");
9406     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9407     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9408       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9409         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9410         propagateIRFlags(Op, ReductionOps[1]);
9411         return Op;
9412       }
9413     }
9414     propagateIRFlags(Op, ReductionOps[0]);
9415     return Op;
9416   }
9417 
9418   /// Creates reduction operation with the current opcode with the IR flags
9419   /// from \p I.
9420   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9421                          Value *RHS, const Twine &Name, Value *I) {
9422     auto *SelI = dyn_cast<SelectInst>(I);
9423     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9424     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9425       if (auto *Sel = dyn_cast<SelectInst>(Op))
9426         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9427     }
9428     propagateIRFlags(Op, I);
9429     return Op;
9430   }
9431 
9432   static RecurKind getRdxKind(Value *V) {
9433     auto *I = dyn_cast<Instruction>(V);
9434     if (!I)
9435       return RecurKind::None;
9436     if (match(I, m_Add(m_Value(), m_Value())))
9437       return RecurKind::Add;
9438     if (match(I, m_Mul(m_Value(), m_Value())))
9439       return RecurKind::Mul;
9440     if (match(I, m_And(m_Value(), m_Value())) ||
9441         match(I, m_LogicalAnd(m_Value(), m_Value())))
9442       return RecurKind::And;
9443     if (match(I, m_Or(m_Value(), m_Value())) ||
9444         match(I, m_LogicalOr(m_Value(), m_Value())))
9445       return RecurKind::Or;
9446     if (match(I, m_Xor(m_Value(), m_Value())))
9447       return RecurKind::Xor;
9448     if (match(I, m_FAdd(m_Value(), m_Value())))
9449       return RecurKind::FAdd;
9450     if (match(I, m_FMul(m_Value(), m_Value())))
9451       return RecurKind::FMul;
9452 
9453     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9454       return RecurKind::FMax;
9455     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9456       return RecurKind::FMin;
9457 
9458     // This matches either cmp+select or intrinsics. SLP is expected to handle
9459     // either form.
9460     // TODO: If we are canonicalizing to intrinsics, we can remove several
9461     //       special-case paths that deal with selects.
9462     if (match(I, m_SMax(m_Value(), m_Value())))
9463       return RecurKind::SMax;
9464     if (match(I, m_SMin(m_Value(), m_Value())))
9465       return RecurKind::SMin;
9466     if (match(I, m_UMax(m_Value(), m_Value())))
9467       return RecurKind::UMax;
9468     if (match(I, m_UMin(m_Value(), m_Value())))
9469       return RecurKind::UMin;
9470 
9471     if (auto *Select = dyn_cast<SelectInst>(I)) {
9472       // Try harder: look for min/max pattern based on instructions producing
9473       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9474       // During the intermediate stages of SLP, it's very common to have
9475       // pattern like this (since optimizeGatherSequence is run only once
9476       // at the end):
9477       // %1 = extractelement <2 x i32> %a, i32 0
9478       // %2 = extractelement <2 x i32> %a, i32 1
9479       // %cond = icmp sgt i32 %1, %2
9480       // %3 = extractelement <2 x i32> %a, i32 0
9481       // %4 = extractelement <2 x i32> %a, i32 1
9482       // %select = select i1 %cond, i32 %3, i32 %4
9483       CmpInst::Predicate Pred;
9484       Instruction *L1;
9485       Instruction *L2;
9486 
9487       Value *LHS = Select->getTrueValue();
9488       Value *RHS = Select->getFalseValue();
9489       Value *Cond = Select->getCondition();
9490 
9491       // TODO: Support inverse predicates.
9492       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9493         if (!isa<ExtractElementInst>(RHS) ||
9494             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9495           return RecurKind::None;
9496       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9497         if (!isa<ExtractElementInst>(LHS) ||
9498             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9499           return RecurKind::None;
9500       } else {
9501         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9502           return RecurKind::None;
9503         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9504             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9505             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9506           return RecurKind::None;
9507       }
9508 
9509       switch (Pred) {
9510       default:
9511         return RecurKind::None;
9512       case CmpInst::ICMP_SGT:
9513       case CmpInst::ICMP_SGE:
9514         return RecurKind::SMax;
9515       case CmpInst::ICMP_SLT:
9516       case CmpInst::ICMP_SLE:
9517         return RecurKind::SMin;
9518       case CmpInst::ICMP_UGT:
9519       case CmpInst::ICMP_UGE:
9520         return RecurKind::UMax;
9521       case CmpInst::ICMP_ULT:
9522       case CmpInst::ICMP_ULE:
9523         return RecurKind::UMin;
9524       }
9525     }
9526     return RecurKind::None;
9527   }
9528 
9529   /// Get the index of the first operand.
9530   static unsigned getFirstOperandIndex(Instruction *I) {
9531     return isCmpSelMinMax(I) ? 1 : 0;
9532   }
9533 
9534   /// Total number of operands in the reduction operation.
9535   static unsigned getNumberOfOperands(Instruction *I) {
9536     return isCmpSelMinMax(I) ? 3 : 2;
9537   }
9538 
9539   /// Checks if the instruction is in basic block \p BB.
9540   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9541   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9542     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9543       auto *Sel = cast<SelectInst>(I);
9544       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9545       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9546     }
9547     return I->getParent() == BB;
9548   }
9549 
9550   /// Expected number of uses for reduction operations/reduced values.
9551   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9552     if (IsCmpSelMinMax) {
9553       // SelectInst must be used twice while the condition op must have single
9554       // use only.
9555       if (auto *Sel = dyn_cast<SelectInst>(I))
9556         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9557       return I->hasNUses(2);
9558     }
9559 
9560     // Arithmetic reduction operation must be used once only.
9561     return I->hasOneUse();
9562   }
9563 
9564   /// Initializes the list of reduction operations.
9565   void initReductionOps(Instruction *I) {
9566     if (isCmpSelMinMax(I))
9567       ReductionOps.assign(2, ReductionOpsType());
9568     else
9569       ReductionOps.assign(1, ReductionOpsType());
9570   }
9571 
9572   /// Add all reduction operations for the reduction instruction \p I.
9573   void addReductionOps(Instruction *I) {
9574     if (isCmpSelMinMax(I)) {
9575       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9576       ReductionOps[1].emplace_back(I);
9577     } else {
9578       ReductionOps[0].emplace_back(I);
9579     }
9580   }
9581 
9582   static Value *getLHS(RecurKind Kind, Instruction *I) {
9583     if (Kind == RecurKind::None)
9584       return nullptr;
9585     return I->getOperand(getFirstOperandIndex(I));
9586   }
9587   static Value *getRHS(RecurKind Kind, Instruction *I) {
9588     if (Kind == RecurKind::None)
9589       return nullptr;
9590     return I->getOperand(getFirstOperandIndex(I) + 1);
9591   }
9592 
9593 public:
9594   HorizontalReduction() = default;
9595 
9596   /// Try to find a reduction tree.
9597   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
9598                                  ScalarEvolution &SE, const DataLayout &DL,
9599                                  const TargetLibraryInfo &TLI) {
9600     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9601            "Phi needs to use the binary operator");
9602     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9603             isa<IntrinsicInst>(Inst)) &&
9604            "Expected binop, select, or intrinsic for reduction matching");
9605     RdxKind = getRdxKind(Inst);
9606 
9607     // We could have a initial reductions that is not an add.
9608     //  r *= v1 + v2 + v3 + v4
9609     // In such a case start looking for a tree rooted in the first '+'.
9610     if (Phi) {
9611       if (getLHS(RdxKind, Inst) == Phi) {
9612         Phi = nullptr;
9613         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9614         if (!Inst)
9615           return false;
9616         RdxKind = getRdxKind(Inst);
9617       } else if (getRHS(RdxKind, Inst) == Phi) {
9618         Phi = nullptr;
9619         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9620         if (!Inst)
9621           return false;
9622         RdxKind = getRdxKind(Inst);
9623       }
9624     }
9625 
9626     if (!isVectorizable(RdxKind, Inst))
9627       return false;
9628 
9629     // Analyze "regular" integer/FP types for reductions - no target-specific
9630     // types or pointers.
9631     Type *Ty = Inst->getType();
9632     if (!isValidElementType(Ty) || Ty->isPointerTy())
9633       return false;
9634 
9635     // Though the ultimate reduction may have multiple uses, its condition must
9636     // have only single use.
9637     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9638       if (!Sel->getCondition()->hasOneUse())
9639         return false;
9640 
9641     ReductionRoot = Inst;
9642 
9643     // Iterate through all the operands of the possible reduction tree and
9644     // gather all the reduced values, sorting them by their value id.
9645     BasicBlock *BB = Inst->getParent();
9646     bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
9647     SmallVector<Instruction *> Worklist(1, Inst);
9648     // Checks if the operands of the \p TreeN instruction are also reduction
9649     // operations or should be treated as reduced values or an extra argument,
9650     // which is not part of the reduction.
9651     auto &&CheckOperands = [this, IsCmpSelMinMax,
9652                             BB](Instruction *TreeN,
9653                                 SmallVectorImpl<Value *> &ExtraArgs,
9654                                 SmallVectorImpl<Value *> &PossibleReducedVals,
9655                                 SmallVectorImpl<Instruction *> &ReductionOps) {
9656       for (int I = getFirstOperandIndex(TreeN),
9657                End = getNumberOfOperands(TreeN);
9658            I < End; ++I) {
9659         Value *EdgeVal = getRdxOperand(TreeN, I);
9660         ReducedValsToOps.try_emplace(EdgeVal, TreeN);
9661         auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9662         // Edge has wrong parent - mark as an extra argument.
9663         if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
9664             !hasSameParent(EdgeInst, BB)) {
9665           ExtraArgs.push_back(EdgeVal);
9666           continue;
9667         }
9668         // If the edge is not an instruction, or it is different from the main
9669         // reduction opcode or has too many uses - possible reduced value.
9670         if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
9671             !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
9672             !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
9673           PossibleReducedVals.push_back(EdgeVal);
9674           continue;
9675         }
9676         ReductionOps.push_back(EdgeInst);
9677       }
9678     };
9679     // Try to regroup reduced values so that it gets more profitable to try to
9680     // reduce them. Values are grouped by their value ids, instructions - by
9681     // instruction op id and/or alternate op id, plus do extra analysis for
9682     // loads (grouping them by the distabce between pointers) and cmp
9683     // instructions (grouping them by the predicate).
9684     MapVector<size_t, MapVector<size_t, SmallVector<Value *>>>
9685         PossibleReducedVals;
9686     initReductionOps(Inst);
9687     while (!Worklist.empty()) {
9688       Instruction *TreeN = Worklist.pop_back_val();
9689       SmallVector<Value *> Args;
9690       SmallVector<Value *> PossibleRedVals;
9691       SmallVector<Instruction *> PossibleReductionOps;
9692       CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
9693       // If too many extra args - mark the instruction itself as a reduction
9694       // value, not a reduction operation.
9695       if (Args.size() < 2) {
9696         addReductionOps(TreeN);
9697         // Add extra args.
9698         if (!Args.empty()) {
9699           assert(Args.size() == 1 && "Expected only single argument.");
9700           ExtraArgs[TreeN] = Args.front();
9701         }
9702         // Add reduction values. The values are sorted for better vectorization
9703         // results.
9704         for (Value *V : PossibleRedVals) {
9705           size_t Key, Idx;
9706           std::tie(Key, Idx) = generateKeySubkey(
9707               V, &TLI,
9708               [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9709                 for (const auto &LoadData : PossibleReducedVals[Key]) {
9710                   auto *RLI = cast<LoadInst>(LoadData.second.front());
9711                   if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9712                                       LI->getType(), LI->getPointerOperand(),
9713                                       DL, SE, /*StrictCheck=*/true))
9714                     return hash_value(RLI->getPointerOperand());
9715                 }
9716                 return hash_value(LI->getPointerOperand());
9717               },
9718               /*AllowAlternate=*/false);
9719           PossibleReducedVals[Key][Idx].push_back(V);
9720         }
9721         Worklist.append(PossibleReductionOps.begin(),
9722                         PossibleReductionOps.end());
9723       } else {
9724         size_t Key, Idx;
9725         std::tie(Key, Idx) = generateKeySubkey(
9726             TreeN, &TLI,
9727             [&PossibleReducedVals, &DL, &SE](size_t Key, LoadInst *LI) {
9728               for (const auto &LoadData : PossibleReducedVals[Key]) {
9729                 auto *RLI = cast<LoadInst>(LoadData.second.front());
9730                 if (getPointersDiff(RLI->getType(), RLI->getPointerOperand(),
9731                                     LI->getType(), LI->getPointerOperand(), DL,
9732                                     SE, /*StrictCheck=*/true))
9733                   return hash_value(RLI->getPointerOperand());
9734               }
9735               return hash_value(LI->getPointerOperand());
9736             },
9737             /*AllowAlternate=*/false);
9738         PossibleReducedVals[Key][Idx].push_back(TreeN);
9739       }
9740     }
9741     auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
9742     // Sort values by the total number of values kinds to start the reduction
9743     // from the longest possible reduced values sequences.
9744     for (auto &PossibleReducedVals : PossibleReducedValsVect) {
9745       auto PossibleRedVals = PossibleReducedVals.second.takeVector();
9746       stable_sort(PossibleRedVals, [](const auto &P1, const auto &P2) {
9747         return P1.second.size() > P2.second.size();
9748       });
9749       ReducedVals.emplace_back();
9750       for (auto &Data : PossibleRedVals)
9751         ReducedVals.back().append(Data.second.rbegin(), Data.second.rend());
9752     }
9753     // Sort the reduced values by number of same/alternate opcode and/or pointer
9754     // operand.
9755     stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
9756       return P1.size() > P2.size();
9757     });
9758     return true;
9759   }
9760 
9761   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9762   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9763     // If there are a sufficient number of reduction values, reduce
9764     // to a nearby power-of-2. We can safely generate oversized
9765     // vectors and rely on the backend to split them to legal sizes.
9766     unsigned NumReducedVals = std::accumulate(
9767         ReducedVals.begin(), ReducedVals.end(), 0,
9768         [](int Num, ArrayRef<Value *> Vals) { return Num + Vals.size(); });
9769     if (NumReducedVals < 4)
9770       return nullptr;
9771 
9772     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9773 
9774     // Track the reduced values in case if they are replaced by extractelement
9775     // because of the vectorization.
9776     DenseMap<Value *, WeakTrackingVH> TrackedVals;
9777     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9778     // The same extra argument may be used several times, so log each attempt
9779     // to use it.
9780     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9781       assert(Pair.first && "DebugLoc must be set.");
9782       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9783       TrackedVals.try_emplace(Pair.second, Pair.second);
9784     }
9785 
9786     // The compare instruction of a min/max is the insertion point for new
9787     // instructions and may be replaced with a new compare instruction.
9788     auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9789       assert(isa<SelectInst>(RdxRootInst) &&
9790              "Expected min/max reduction to have select root instruction");
9791       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9792       assert(isa<Instruction>(ScalarCond) &&
9793              "Expected min/max reduction to have compare condition");
9794       return cast<Instruction>(ScalarCond);
9795     };
9796 
9797     // The reduction root is used as the insertion point for new instructions,
9798     // so set it as externally used to prevent it from being deleted.
9799     ExternallyUsedValues[ReductionRoot];
9800     SmallVector<Value *> IgnoreList;
9801     for (ReductionOpsType &RdxOps : ReductionOps)
9802       for (Value *RdxOp : RdxOps) {
9803         if (!RdxOp)
9804           continue;
9805         IgnoreList.push_back(RdxOp);
9806       }
9807 
9808     // Need to track reduced vals, they may be changed during vectorization of
9809     // subvectors.
9810     for (ArrayRef<Value *> Candidates : ReducedVals)
9811       for (Value *V : Candidates)
9812         TrackedVals.try_emplace(V, V);
9813 
9814     DenseMap<Value *, unsigned> VectorizedVals;
9815     Value *VectorizedTree = nullptr;
9816     // Try to vectorize elements based on their type.
9817     for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
9818       ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
9819       InstructionsState S = getSameOpcode(OrigReducedVals);
9820       SmallVector<Value *> Candidates;
9821       DenseMap<Value *, Value *> TrackedToOrig;
9822       for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
9823         Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
9824         // Check if the reduction value was not overriden by the extractelement
9825         // instruction because of the vectorization and exclude it, if it is not
9826         // compatible with other values.
9827         if (auto *Inst = dyn_cast<Instruction>(RdxVal))
9828           if (isVectorLikeInstWithConstOps(Inst) &&
9829               (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
9830             continue;
9831         Candidates.push_back(RdxVal);
9832         TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
9833       }
9834       bool ShuffledExtracts = false;
9835       // Try to handle shuffled extractelements.
9836       if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
9837           I + 1 < E) {
9838         InstructionsState NextS = getSameOpcode(ReducedVals[I + 1]);
9839         if (NextS.getOpcode() == Instruction::ExtractElement &&
9840             !NextS.isAltShuffle()) {
9841           SmallVector<Value *> CommonCandidates(Candidates);
9842           for (Value *RV : ReducedVals[I + 1]) {
9843             Value *RdxVal = TrackedVals.find(RV)->second;
9844             // Check if the reduction value was not overriden by the
9845             // extractelement instruction because of the vectorization and
9846             // exclude it, if it is not compatible with other values.
9847             if (auto *Inst = dyn_cast<Instruction>(RdxVal))
9848               if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
9849                 continue;
9850             CommonCandidates.push_back(RdxVal);
9851             TrackedToOrig.try_emplace(RdxVal, RV);
9852           }
9853           SmallVector<int> Mask;
9854           if (isFixedVectorShuffle(CommonCandidates, Mask)) {
9855             ++I;
9856             Candidates.swap(CommonCandidates);
9857             ShuffledExtracts = true;
9858           }
9859         }
9860       }
9861       unsigned NumReducedVals = Candidates.size();
9862       if (NumReducedVals < 4)
9863         continue;
9864 
9865       unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9866       unsigned Start = 0;
9867       unsigned Pos = Start;
9868       // Restarts vectorization attempt with lower vector factor.
9869       auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals]() {
9870         if (ReduxWidth == 4 || Pos >= NumReducedVals - ReduxWidth + 1) {
9871           ++Start;
9872           ReduxWidth = PowerOf2Floor(NumReducedVals - Start) * 2;
9873         }
9874         Pos = Start;
9875         ReduxWidth /= 2;
9876       };
9877       while (Pos < NumReducedVals - ReduxWidth + 1 && ReduxWidth >= 4) {
9878         ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
9879         V.buildTree(VL, IgnoreList);
9880         if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
9881           AdjustReducedVals();
9882           continue;
9883         }
9884         if (V.isLoadCombineReductionCandidate(RdxKind)) {
9885           AdjustReducedVals();
9886           continue;
9887         }
9888         V.reorderTopToBottom();
9889         // No need to reorder the root node at all.
9890         V.reorderBottomToTop(/*IgnoreReorder=*/true);
9891         // Keep extracted other reduction values, if they are used in the
9892         // vectorization trees.
9893         BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
9894             ExternallyUsedValues);
9895         for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
9896           if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
9897             continue;
9898           for_each(ReducedVals[Cnt],
9899                    [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
9900                      if (isa<Instruction>(V))
9901                        LocalExternallyUsedValues[TrackedVals[V]];
9902                    });
9903         }
9904         for (unsigned Cnt = 0; Cnt < NumReducedVals; ++Cnt) {
9905           if (Cnt >= Pos && Cnt < Pos + ReduxWidth)
9906             continue;
9907           if (VectorizedVals.count(Candidates[Cnt]))
9908             continue;
9909           LocalExternallyUsedValues[Candidates[Cnt]];
9910         }
9911         V.buildExternalUses(LocalExternallyUsedValues);
9912 
9913         V.computeMinimumValueSizes();
9914 
9915         // Intersect the fast-math-flags from all reduction operations.
9916         FastMathFlags RdxFMF;
9917         RdxFMF.set();
9918         for (Value *RdxVal : VL) {
9919           if (auto *FPMO = dyn_cast<FPMathOperator>(
9920                   ReducedValsToOps.find(RdxVal)->second))
9921             RdxFMF &= FPMO->getFastMathFlags();
9922         }
9923         // Estimate cost.
9924         InstructionCost TreeCost = V.getTreeCost(VL);
9925         InstructionCost ReductionCost =
9926             getReductionCost(TTI, VL[0], ReduxWidth, RdxFMF);
9927         InstructionCost Cost = TreeCost + ReductionCost;
9928         if (!Cost.isValid()) {
9929           LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9930           return nullptr;
9931         }
9932         if (Cost >= -SLPCostThreshold) {
9933           V.getORE()->emit([&]() {
9934             return OptimizationRemarkMissed(
9935                        SV_NAME, "HorSLPNotBeneficial",
9936                        ReducedValsToOps.find(VL[0])->second)
9937                    << "Vectorizing horizontal reduction is possible"
9938                    << "but not beneficial with cost " << ore::NV("Cost", Cost)
9939                    << " and threshold "
9940                    << ore::NV("Threshold", -SLPCostThreshold);
9941           });
9942           AdjustReducedVals();
9943           continue;
9944         }
9945 
9946         LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9947                           << Cost << ". (HorRdx)\n");
9948         V.getORE()->emit([&]() {
9949           return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9950                                     ReducedValsToOps.find(VL[0])->second)
9951                  << "Vectorized horizontal reduction with cost "
9952                  << ore::NV("Cost", Cost) << " and with tree size "
9953                  << ore::NV("TreeSize", V.getTreeSize());
9954         });
9955 
9956         Builder.setFastMathFlags(RdxFMF);
9957 
9958         // Vectorize a tree.
9959         Value *VectorizedRoot = V.vectorizeTree(LocalExternallyUsedValues);
9960 
9961         // Emit a reduction. If the root is a select (min/max idiom), the insert
9962         // point is the compare condition of that select.
9963         Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9964         if (isCmpSelMinMax(RdxRootInst))
9965           Builder.SetInsertPoint(GetCmpForMinMaxReduction(RdxRootInst));
9966         else
9967           Builder.SetInsertPoint(RdxRootInst);
9968 
9969         // To prevent poison from leaking across what used to be sequential,
9970         // safe, scalar boolean logic operations, the reduction operand must be
9971         // frozen.
9972         if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9973           VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9974 
9975         Value *ReducedSubTree =
9976             emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9977 
9978         if (!VectorizedTree) {
9979           // Initialize the final value in the reduction.
9980           VectorizedTree = ReducedSubTree;
9981         } else {
9982           // Update the final value in the reduction.
9983           Builder.SetCurrentDebugLocation(
9984               cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
9985           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9986                                     ReducedSubTree, "op.rdx", ReductionOps);
9987         }
9988         // Count vectorized reduced values to exclude them from final reduction.
9989         for (Value *V : VL)
9990           ++VectorizedVals.try_emplace(TrackedToOrig.find(V)->second, 0)
9991                 .first->getSecond();
9992         Pos += ReduxWidth;
9993         Start = Pos;
9994         ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
9995       }
9996     }
9997     if (VectorizedTree) {
9998       // Finish the reduction.
9999       // Need to add extra arguments and not vectorized possible reduction
10000       // values.
10001       for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
10002         ArrayRef<Value *> Candidates = ReducedVals[I];
10003         for (Value *RdxVal : Candidates) {
10004           auto It = VectorizedVals.find(RdxVal);
10005           if (It != VectorizedVals.end()) {
10006             --It->getSecond();
10007             if (It->second == 0)
10008               VectorizedVals.erase(It);
10009             continue;
10010           }
10011           Instruction *RedOp = ReducedValsToOps.find(RdxVal)->second;
10012           Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
10013           ReductionOpsListType Ops;
10014           if (auto *Sel = dyn_cast<SelectInst>(RedOp))
10015             Ops.emplace_back().push_back(Sel->getCondition());
10016           Ops.emplace_back().push_back(RedOp);
10017           Value *StableRdxVal = RdxVal;
10018           auto TVIt = TrackedVals.find(RdxVal);
10019           if (TVIt != TrackedVals.end())
10020             StableRdxVal = TVIt->second;
10021 
10022           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10023                                     StableRdxVal, "op.rdx", RedOp);
10024         }
10025       }
10026       for (auto &Pair : ExternallyUsedValues) {
10027         // Add each externally used value to the final reduction.
10028         for (auto *I : Pair.second) {
10029           Builder.SetCurrentDebugLocation(I->getDebugLoc());
10030           ReductionOpsListType Ops;
10031           if (auto *Sel = dyn_cast<SelectInst>(I))
10032             Ops.emplace_back().push_back(Sel->getCondition());
10033           Ops.emplace_back().push_back(I);
10034           Value *StableRdxVal = Pair.first;
10035           auto TVIt = TrackedVals.find(Pair.first);
10036           if (TVIt != TrackedVals.end())
10037             StableRdxVal = TVIt->second;
10038           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
10039                                     StableRdxVal, "op.rdx", Ops);
10040         }
10041       }
10042 
10043       ReductionRoot->replaceAllUsesWith(VectorizedTree);
10044 
10045       // The original scalar reduction is expected to have no remaining
10046       // uses outside the reduction tree itself.  Assert that we got this
10047       // correct, replace internal uses with undef, and mark for eventual
10048       // deletion.
10049 #ifndef NDEBUG
10050       SmallSet<Value *, 4> IgnoreSet;
10051       IgnoreSet.insert(IgnoreList.begin(), IgnoreList.end());
10052 #endif
10053       for (auto *Ignore : IgnoreList) {
10054 #ifndef NDEBUG
10055         for (auto *U : Ignore->users()) {
10056           assert(IgnoreSet.count(U));
10057         }
10058 #endif
10059         if (!Ignore->use_empty()) {
10060           Value *Undef = UndefValue::get(Ignore->getType());
10061           Ignore->replaceAllUsesWith(Undef);
10062         }
10063         V.eraseInstruction(cast<Instruction>(Ignore));
10064       }
10065     }
10066     return VectorizedTree;
10067   }
10068 
10069   unsigned numReductionValues() const { return ReducedVals.size(); }
10070 
10071 private:
10072   /// Calculate the cost of a reduction.
10073   InstructionCost getReductionCost(TargetTransformInfo *TTI,
10074                                    Value *FirstReducedVal, unsigned ReduxWidth,
10075                                    FastMathFlags FMF) {
10076     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
10077     Type *ScalarTy = FirstReducedVal->getType();
10078     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
10079     InstructionCost VectorCost, ScalarCost;
10080     switch (RdxKind) {
10081     case RecurKind::Add:
10082     case RecurKind::Mul:
10083     case RecurKind::Or:
10084     case RecurKind::And:
10085     case RecurKind::Xor:
10086     case RecurKind::FAdd:
10087     case RecurKind::FMul: {
10088       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
10089       VectorCost =
10090           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
10091       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
10092       break;
10093     }
10094     case RecurKind::FMax:
10095     case RecurKind::FMin: {
10096       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10097       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10098       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
10099                                                /*IsUnsigned=*/false, CostKind);
10100       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10101       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
10102                                            SclCondTy, RdxPred, CostKind) +
10103                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10104                                            SclCondTy, RdxPred, CostKind);
10105       break;
10106     }
10107     case RecurKind::SMax:
10108     case RecurKind::SMin:
10109     case RecurKind::UMax:
10110     case RecurKind::UMin: {
10111       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
10112       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
10113       bool IsUnsigned =
10114           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
10115       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
10116                                                CostKind);
10117       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
10118       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
10119                                            SclCondTy, RdxPred, CostKind) +
10120                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
10121                                            SclCondTy, RdxPred, CostKind);
10122       break;
10123     }
10124     default:
10125       llvm_unreachable("Expected arithmetic or min/max reduction operation");
10126     }
10127 
10128     // Scalar cost is repeated for N-1 elements.
10129     ScalarCost *= (ReduxWidth - 1);
10130     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
10131                       << " for reduction that starts with " << *FirstReducedVal
10132                       << " (It is a splitting reduction)\n");
10133     return VectorCost - ScalarCost;
10134   }
10135 
10136   /// Emit a horizontal reduction of the vectorized value.
10137   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
10138                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
10139     assert(VectorizedValue && "Need to have a vectorized tree node");
10140     assert(isPowerOf2_32(ReduxWidth) &&
10141            "We only handle power-of-two reductions for now");
10142     assert(RdxKind != RecurKind::FMulAdd &&
10143            "A call to the llvm.fmuladd intrinsic is not handled yet");
10144 
10145     ++NumVectorInstructions;
10146     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
10147   }
10148 };
10149 
10150 } // end anonymous namespace
10151 
10152 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
10153   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
10154     return cast<FixedVectorType>(IE->getType())->getNumElements();
10155 
10156   unsigned AggregateSize = 1;
10157   auto *IV = cast<InsertValueInst>(InsertInst);
10158   Type *CurrentType = IV->getType();
10159   do {
10160     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
10161       for (auto *Elt : ST->elements())
10162         if (Elt != ST->getElementType(0)) // check homogeneity
10163           return None;
10164       AggregateSize *= ST->getNumElements();
10165       CurrentType = ST->getElementType(0);
10166     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
10167       AggregateSize *= AT->getNumElements();
10168       CurrentType = AT->getElementType();
10169     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
10170       AggregateSize *= VT->getNumElements();
10171       return AggregateSize;
10172     } else if (CurrentType->isSingleValueType()) {
10173       return AggregateSize;
10174     } else {
10175       return None;
10176     }
10177   } while (true);
10178 }
10179 
10180 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10181                                    TargetTransformInfo *TTI,
10182                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10183                                    SmallVectorImpl<Value *> &InsertElts,
10184                                    unsigned OperandOffset) {
10185   do {
10186     Value *InsertedOperand = LastInsertInst->getOperand(1);
10187     Optional<unsigned> OperandIndex =
10188         getInsertIndex(LastInsertInst, OperandOffset);
10189     if (!OperandIndex)
10190       return;
10191     if (isa<InsertElementInst>(InsertedOperand) ||
10192         isa<InsertValueInst>(InsertedOperand)) {
10193       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10194                              BuildVectorOpds, InsertElts, *OperandIndex);
10195 
10196     } else {
10197       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10198       InsertElts[*OperandIndex] = LastInsertInst;
10199     }
10200     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10201   } while (LastInsertInst != nullptr &&
10202            (isa<InsertValueInst>(LastInsertInst) ||
10203             isa<InsertElementInst>(LastInsertInst)) &&
10204            LastInsertInst->hasOneUse());
10205 }
10206 
10207 /// Recognize construction of vectors like
10208 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10209 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10210 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10211 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10212 ///  starting from the last insertelement or insertvalue instruction.
10213 ///
10214 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10215 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10216 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10217 ///
10218 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10219 ///
10220 /// \return true if it matches.
10221 static bool findBuildAggregate(Instruction *LastInsertInst,
10222                                TargetTransformInfo *TTI,
10223                                SmallVectorImpl<Value *> &BuildVectorOpds,
10224                                SmallVectorImpl<Value *> &InsertElts) {
10225 
10226   assert((isa<InsertElementInst>(LastInsertInst) ||
10227           isa<InsertValueInst>(LastInsertInst)) &&
10228          "Expected insertelement or insertvalue instruction!");
10229 
10230   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10231          "Expected empty result vectors!");
10232 
10233   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10234   if (!AggregateSize)
10235     return false;
10236   BuildVectorOpds.resize(*AggregateSize);
10237   InsertElts.resize(*AggregateSize);
10238 
10239   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10240   llvm::erase_value(BuildVectorOpds, nullptr);
10241   llvm::erase_value(InsertElts, nullptr);
10242   if (BuildVectorOpds.size() >= 2)
10243     return true;
10244 
10245   return false;
10246 }
10247 
10248 /// Try and get a reduction value from a phi node.
10249 ///
10250 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10251 /// if they come from either \p ParentBB or a containing loop latch.
10252 ///
10253 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10254 /// if not possible.
10255 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10256                                 BasicBlock *ParentBB, LoopInfo *LI) {
10257   // There are situations where the reduction value is not dominated by the
10258   // reduction phi. Vectorizing such cases has been reported to cause
10259   // miscompiles. See PR25787.
10260   auto DominatedReduxValue = [&](Value *R) {
10261     return isa<Instruction>(R) &&
10262            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10263   };
10264 
10265   Value *Rdx = nullptr;
10266 
10267   // Return the incoming value if it comes from the same BB as the phi node.
10268   if (P->getIncomingBlock(0) == ParentBB) {
10269     Rdx = P->getIncomingValue(0);
10270   } else if (P->getIncomingBlock(1) == ParentBB) {
10271     Rdx = P->getIncomingValue(1);
10272   }
10273 
10274   if (Rdx && DominatedReduxValue(Rdx))
10275     return Rdx;
10276 
10277   // Otherwise, check whether we have a loop latch to look at.
10278   Loop *BBL = LI->getLoopFor(ParentBB);
10279   if (!BBL)
10280     return nullptr;
10281   BasicBlock *BBLatch = BBL->getLoopLatch();
10282   if (!BBLatch)
10283     return nullptr;
10284 
10285   // There is a loop latch, return the incoming value if it comes from
10286   // that. This reduction pattern occasionally turns up.
10287   if (P->getIncomingBlock(0) == BBLatch) {
10288     Rdx = P->getIncomingValue(0);
10289   } else if (P->getIncomingBlock(1) == BBLatch) {
10290     Rdx = P->getIncomingValue(1);
10291   }
10292 
10293   if (Rdx && DominatedReduxValue(Rdx))
10294     return Rdx;
10295 
10296   return nullptr;
10297 }
10298 
10299 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10300   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10301     return true;
10302   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10303     return true;
10304   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10305     return true;
10306   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10307     return true;
10308   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10309     return true;
10310   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10311     return true;
10312   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10313     return true;
10314   return false;
10315 }
10316 
10317 /// Attempt to reduce a horizontal reduction.
10318 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10319 /// with reduction operators \a Root (or one of its operands) in a basic block
10320 /// \a BB, then check if it can be done. If horizontal reduction is not found
10321 /// and root instruction is a binary operation, vectorization of the operands is
10322 /// attempted.
10323 /// \returns true if a horizontal reduction was matched and reduced or operands
10324 /// of one of the binary instruction were vectorized.
10325 /// \returns false if a horizontal reduction was not matched (or not possible)
10326 /// or no vectorization of any binary operation feeding \a Root instruction was
10327 /// performed.
10328 static bool tryToVectorizeHorReductionOrInstOperands(
10329     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10330     TargetTransformInfo *TTI, ScalarEvolution &SE, const DataLayout &DL,
10331     const TargetLibraryInfo &TLI,
10332     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10333   if (!ShouldVectorizeHor)
10334     return false;
10335 
10336   if (!Root)
10337     return false;
10338 
10339   if (Root->getParent() != BB || isa<PHINode>(Root))
10340     return false;
10341   // Start analysis starting from Root instruction. If horizontal reduction is
10342   // found, try to vectorize it. If it is not a horizontal reduction or
10343   // vectorization is not possible or not effective, and currently analyzed
10344   // instruction is a binary operation, try to vectorize the operands, using
10345   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10346   // the same procedure considering each operand as a possible root of the
10347   // horizontal reduction.
10348   // Interrupt the process if the Root instruction itself was vectorized or all
10349   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10350   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10351   // CmpInsts so we can skip extra attempts in
10352   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10353   std::queue<std::pair<Instruction *, unsigned>> Stack;
10354   Stack.emplace(Root, 0);
10355   SmallPtrSet<Value *, 8> VisitedInstrs;
10356   SmallVector<WeakTrackingVH> PostponedInsts;
10357   bool Res = false;
10358   auto &&TryToReduce = [TTI, &SE, &DL, &P, &R, &TLI](Instruction *Inst,
10359                                                      Value *&B0,
10360                                                      Value *&B1) -> Value * {
10361     bool IsBinop = matchRdxBop(Inst, B0, B1);
10362     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10363     if (IsBinop || IsSelect) {
10364       HorizontalReduction HorRdx;
10365       if (HorRdx.matchAssociativeReduction(P, Inst, SE, DL, TLI))
10366         return HorRdx.tryToReduce(R, TTI);
10367     }
10368     return nullptr;
10369   };
10370   while (!Stack.empty()) {
10371     Instruction *Inst;
10372     unsigned Level;
10373     std::tie(Inst, Level) = Stack.front();
10374     Stack.pop();
10375     // Do not try to analyze instruction that has already been vectorized.
10376     // This may happen when we vectorize instruction operands on a previous
10377     // iteration while stack was populated before that happened.
10378     if (R.isDeleted(Inst))
10379       continue;
10380     Value *B0 = nullptr, *B1 = nullptr;
10381     if (Value *V = TryToReduce(Inst, B0, B1)) {
10382       Res = true;
10383       // Set P to nullptr to avoid re-analysis of phi node in
10384       // matchAssociativeReduction function unless this is the root node.
10385       P = nullptr;
10386       if (auto *I = dyn_cast<Instruction>(V)) {
10387         // Try to find another reduction.
10388         Stack.emplace(I, Level);
10389         continue;
10390       }
10391     } else {
10392       bool IsBinop = B0 && B1;
10393       if (P && IsBinop) {
10394         Inst = dyn_cast<Instruction>(B0);
10395         if (Inst == P)
10396           Inst = dyn_cast<Instruction>(B1);
10397         if (!Inst) {
10398           // Set P to nullptr to avoid re-analysis of phi node in
10399           // matchAssociativeReduction function unless this is the root node.
10400           P = nullptr;
10401           continue;
10402         }
10403       }
10404       // Set P to nullptr to avoid re-analysis of phi node in
10405       // matchAssociativeReduction function unless this is the root node.
10406       P = nullptr;
10407       // Do not try to vectorize CmpInst operands, this is done separately.
10408       // Final attempt for binop args vectorization should happen after the loop
10409       // to try to find reductions.
10410       if (!isa<CmpInst>(Inst))
10411         PostponedInsts.push_back(Inst);
10412     }
10413 
10414     // Try to vectorize operands.
10415     // Continue analysis for the instruction from the same basic block only to
10416     // save compile time.
10417     if (++Level < RecursionMaxDepth)
10418       for (auto *Op : Inst->operand_values())
10419         if (VisitedInstrs.insert(Op).second)
10420           if (auto *I = dyn_cast<Instruction>(Op))
10421             // Do not try to vectorize CmpInst operands,  this is done
10422             // separately.
10423             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10424                 I->getParent() == BB)
10425               Stack.emplace(I, Level);
10426   }
10427   // Try to vectorized binops where reductions were not found.
10428   for (Value *V : PostponedInsts)
10429     if (auto *Inst = dyn_cast<Instruction>(V))
10430       if (!R.isDeleted(Inst))
10431         Res |= Vectorize(Inst, R);
10432   return Res;
10433 }
10434 
10435 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10436                                                  BasicBlock *BB, BoUpSLP &R,
10437                                                  TargetTransformInfo *TTI) {
10438   auto *I = dyn_cast_or_null<Instruction>(V);
10439   if (!I)
10440     return false;
10441 
10442   if (!isa<BinaryOperator>(I))
10443     P = nullptr;
10444   // Try to match and vectorize a horizontal reduction.
10445   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10446     return tryToVectorize(I, R);
10447   };
10448   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI, *SE, *DL,
10449                                                   *TLI, ExtraVectorization);
10450 }
10451 
10452 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10453                                                  BasicBlock *BB, BoUpSLP &R) {
10454   const DataLayout &DL = BB->getModule()->getDataLayout();
10455   if (!R.canMapToVector(IVI->getType(), DL))
10456     return false;
10457 
10458   SmallVector<Value *, 16> BuildVectorOpds;
10459   SmallVector<Value *, 16> BuildVectorInsts;
10460   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10461     return false;
10462 
10463   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10464   // Aggregate value is unlikely to be processed in vector register.
10465   return tryToVectorizeList(BuildVectorOpds, R);
10466 }
10467 
10468 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10469                                                    BasicBlock *BB, BoUpSLP &R) {
10470   SmallVector<Value *, 16> BuildVectorInsts;
10471   SmallVector<Value *, 16> BuildVectorOpds;
10472   SmallVector<int> Mask;
10473   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10474       (llvm::all_of(
10475            BuildVectorOpds,
10476            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10477        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10478     return false;
10479 
10480   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10481   return tryToVectorizeList(BuildVectorInsts, R);
10482 }
10483 
10484 template <typename T>
10485 static bool
10486 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10487                        function_ref<unsigned(T *)> Limit,
10488                        function_ref<bool(T *, T *)> Comparator,
10489                        function_ref<bool(T *, T *)> AreCompatible,
10490                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10491                        bool LimitForRegisterSize) {
10492   bool Changed = false;
10493   // Sort by type, parent, operands.
10494   stable_sort(Incoming, Comparator);
10495 
10496   // Try to vectorize elements base on their type.
10497   SmallVector<T *> Candidates;
10498   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10499     // Look for the next elements with the same type, parent and operand
10500     // kinds.
10501     auto *SameTypeIt = IncIt;
10502     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10503       ++SameTypeIt;
10504 
10505     // Try to vectorize them.
10506     unsigned NumElts = (SameTypeIt - IncIt);
10507     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10508                       << NumElts << ")\n");
10509     // The vectorization is a 3-state attempt:
10510     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10511     // size of maximal register at first.
10512     // 2. Try to vectorize remaining instructions with the same type, if
10513     // possible. This may result in the better vectorization results rather than
10514     // if we try just to vectorize instructions with the same/alternate opcodes.
10515     // 3. Final attempt to try to vectorize all instructions with the
10516     // same/alternate ops only, this may result in some extra final
10517     // vectorization.
10518     if (NumElts > 1 &&
10519         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10520       // Success start over because instructions might have been changed.
10521       Changed = true;
10522     } else if (NumElts < Limit(*IncIt) &&
10523                (Candidates.empty() ||
10524                 Candidates.front()->getType() == (*IncIt)->getType())) {
10525       Candidates.append(IncIt, std::next(IncIt, NumElts));
10526     }
10527     // Final attempt to vectorize instructions with the same types.
10528     if (Candidates.size() > 1 &&
10529         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10530       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10531         // Success start over because instructions might have been changed.
10532         Changed = true;
10533       } else if (LimitForRegisterSize) {
10534         // Try to vectorize using small vectors.
10535         for (auto *It = Candidates.begin(), *End = Candidates.end();
10536              It != End;) {
10537           auto *SameTypeIt = It;
10538           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10539             ++SameTypeIt;
10540           unsigned NumElts = (SameTypeIt - It);
10541           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10542                                             /*LimitForRegisterSize=*/false))
10543             Changed = true;
10544           It = SameTypeIt;
10545         }
10546       }
10547       Candidates.clear();
10548     }
10549 
10550     // Start over at the next instruction of a different type (or the end).
10551     IncIt = SameTypeIt;
10552   }
10553   return Changed;
10554 }
10555 
10556 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10557 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10558 /// operands. If IsCompatibility is false, function implements strict weak
10559 /// ordering relation between two cmp instructions, returning true if the first
10560 /// instruction is "less" than the second, i.e. its predicate is less than the
10561 /// predicate of the second or the operands IDs are less than the operands IDs
10562 /// of the second cmp instruction.
10563 template <bool IsCompatibility>
10564 static bool compareCmp(Value *V, Value *V2,
10565                        function_ref<bool(Instruction *)> IsDeleted) {
10566   auto *CI1 = cast<CmpInst>(V);
10567   auto *CI2 = cast<CmpInst>(V2);
10568   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10569     return false;
10570   if (CI1->getOperand(0)->getType()->getTypeID() <
10571       CI2->getOperand(0)->getType()->getTypeID())
10572     return !IsCompatibility;
10573   if (CI1->getOperand(0)->getType()->getTypeID() >
10574       CI2->getOperand(0)->getType()->getTypeID())
10575     return false;
10576   CmpInst::Predicate Pred1 = CI1->getPredicate();
10577   CmpInst::Predicate Pred2 = CI2->getPredicate();
10578   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10579   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10580   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10581   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10582   if (BasePred1 < BasePred2)
10583     return !IsCompatibility;
10584   if (BasePred1 > BasePred2)
10585     return false;
10586   // Compare operands.
10587   bool LEPreds = Pred1 <= Pred2;
10588   bool GEPreds = Pred1 >= Pred2;
10589   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10590     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10591     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10592     if (Op1->getValueID() < Op2->getValueID())
10593       return !IsCompatibility;
10594     if (Op1->getValueID() > Op2->getValueID())
10595       return false;
10596     if (auto *I1 = dyn_cast<Instruction>(Op1))
10597       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10598         if (I1->getParent() != I2->getParent())
10599           return false;
10600         InstructionsState S = getSameOpcode({I1, I2});
10601         if (S.getOpcode())
10602           continue;
10603         return false;
10604       }
10605   }
10606   return IsCompatibility;
10607 }
10608 
10609 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10610     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10611     bool AtTerminator) {
10612   bool OpsChanged = false;
10613   SmallVector<Instruction *, 4> PostponedCmps;
10614   for (auto *I : reverse(Instructions)) {
10615     if (R.isDeleted(I))
10616       continue;
10617     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10618       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10619     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10620       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10621     else if (isa<CmpInst>(I))
10622       PostponedCmps.push_back(I);
10623   }
10624   if (AtTerminator) {
10625     // Try to find reductions first.
10626     for (Instruction *I : PostponedCmps) {
10627       if (R.isDeleted(I))
10628         continue;
10629       for (Value *Op : I->operands())
10630         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10631     }
10632     // Try to vectorize operands as vector bundles.
10633     for (Instruction *I : PostponedCmps) {
10634       if (R.isDeleted(I))
10635         continue;
10636       OpsChanged |= tryToVectorize(I, R);
10637     }
10638     // Try to vectorize list of compares.
10639     // Sort by type, compare predicate, etc.
10640     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10641       return compareCmp<false>(V, V2,
10642                                [&R](Instruction *I) { return R.isDeleted(I); });
10643     };
10644 
10645     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10646       if (V1 == V2)
10647         return true;
10648       return compareCmp<true>(V1, V2,
10649                               [&R](Instruction *I) { return R.isDeleted(I); });
10650     };
10651     auto Limit = [&R](Value *V) {
10652       unsigned EltSize = R.getVectorElementSize(V);
10653       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10654     };
10655 
10656     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10657     OpsChanged |= tryToVectorizeSequence<Value>(
10658         Vals, Limit, CompareSorter, AreCompatibleCompares,
10659         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10660           // Exclude possible reductions from other blocks.
10661           bool ArePossiblyReducedInOtherBlock =
10662               any_of(Candidates, [](Value *V) {
10663                 return any_of(V->users(), [V](User *U) {
10664                   return isa<SelectInst>(U) &&
10665                          cast<SelectInst>(U)->getParent() !=
10666                              cast<Instruction>(V)->getParent();
10667                 });
10668               });
10669           if (ArePossiblyReducedInOtherBlock)
10670             return false;
10671           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10672         },
10673         /*LimitForRegisterSize=*/true);
10674     Instructions.clear();
10675   } else {
10676     // Insert in reverse order since the PostponedCmps vector was filled in
10677     // reverse order.
10678     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10679   }
10680   return OpsChanged;
10681 }
10682 
10683 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10684   bool Changed = false;
10685   SmallVector<Value *, 4> Incoming;
10686   SmallPtrSet<Value *, 16> VisitedInstrs;
10687   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10688   // node. Allows better to identify the chains that can be vectorized in the
10689   // better way.
10690   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10691   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10692     assert(isValidElementType(V1->getType()) &&
10693            isValidElementType(V2->getType()) &&
10694            "Expected vectorizable types only.");
10695     // It is fine to compare type IDs here, since we expect only vectorizable
10696     // types, like ints, floats and pointers, we don't care about other type.
10697     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10698       return true;
10699     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10700       return false;
10701     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10702     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10703     if (Opcodes1.size() < Opcodes2.size())
10704       return true;
10705     if (Opcodes1.size() > Opcodes2.size())
10706       return false;
10707     Optional<bool> ConstOrder;
10708     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10709       // Undefs are compatible with any other value.
10710       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10711         if (!ConstOrder)
10712           ConstOrder =
10713               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10714         continue;
10715       }
10716       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10717         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10718           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10719           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10720           if (!NodeI1)
10721             return NodeI2 != nullptr;
10722           if (!NodeI2)
10723             return false;
10724           assert((NodeI1 == NodeI2) ==
10725                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10726                  "Different nodes should have different DFS numbers");
10727           if (NodeI1 != NodeI2)
10728             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10729           InstructionsState S = getSameOpcode({I1, I2});
10730           if (S.getOpcode())
10731             continue;
10732           return I1->getOpcode() < I2->getOpcode();
10733         }
10734       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10735         if (!ConstOrder)
10736           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10737         continue;
10738       }
10739       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10740         return true;
10741       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10742         return false;
10743     }
10744     return ConstOrder && *ConstOrder;
10745   };
10746   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10747     if (V1 == V2)
10748       return true;
10749     if (V1->getType() != V2->getType())
10750       return false;
10751     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10752     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10753     if (Opcodes1.size() != Opcodes2.size())
10754       return false;
10755     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10756       // Undefs are compatible with any other value.
10757       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10758         continue;
10759       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10760         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10761           if (I1->getParent() != I2->getParent())
10762             return false;
10763           InstructionsState S = getSameOpcode({I1, I2});
10764           if (S.getOpcode())
10765             continue;
10766           return false;
10767         }
10768       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10769         continue;
10770       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10771         return false;
10772     }
10773     return true;
10774   };
10775   auto Limit = [&R](Value *V) {
10776     unsigned EltSize = R.getVectorElementSize(V);
10777     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10778   };
10779 
10780   bool HaveVectorizedPhiNodes = false;
10781   do {
10782     // Collect the incoming values from the PHIs.
10783     Incoming.clear();
10784     for (Instruction &I : *BB) {
10785       PHINode *P = dyn_cast<PHINode>(&I);
10786       if (!P)
10787         break;
10788 
10789       // No need to analyze deleted, vectorized and non-vectorizable
10790       // instructions.
10791       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10792           isValidElementType(P->getType()))
10793         Incoming.push_back(P);
10794     }
10795 
10796     // Find the corresponding non-phi nodes for better matching when trying to
10797     // build the tree.
10798     for (Value *V : Incoming) {
10799       SmallVectorImpl<Value *> &Opcodes =
10800           PHIToOpcodes.try_emplace(V).first->getSecond();
10801       if (!Opcodes.empty())
10802         continue;
10803       SmallVector<Value *, 4> Nodes(1, V);
10804       SmallPtrSet<Value *, 4> Visited;
10805       while (!Nodes.empty()) {
10806         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10807         if (!Visited.insert(PHI).second)
10808           continue;
10809         for (Value *V : PHI->incoming_values()) {
10810           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10811             Nodes.push_back(PHI1);
10812             continue;
10813           }
10814           Opcodes.emplace_back(V);
10815         }
10816       }
10817     }
10818 
10819     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10820         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10821         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10822           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10823         },
10824         /*LimitForRegisterSize=*/true);
10825     Changed |= HaveVectorizedPhiNodes;
10826     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10827   } while (HaveVectorizedPhiNodes);
10828 
10829   VisitedInstrs.clear();
10830 
10831   SmallVector<Instruction *, 8> PostProcessInstructions;
10832   SmallDenseSet<Instruction *, 4> KeyNodes;
10833   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10834     // Skip instructions with scalable type. The num of elements is unknown at
10835     // compile-time for scalable type.
10836     if (isa<ScalableVectorType>(it->getType()))
10837       continue;
10838 
10839     // Skip instructions marked for the deletion.
10840     if (R.isDeleted(&*it))
10841       continue;
10842     // We may go through BB multiple times so skip the one we have checked.
10843     if (!VisitedInstrs.insert(&*it).second) {
10844       if (it->use_empty() && KeyNodes.contains(&*it) &&
10845           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10846                                       it->isTerminator())) {
10847         // We would like to start over since some instructions are deleted
10848         // and the iterator may become invalid value.
10849         Changed = true;
10850         it = BB->begin();
10851         e = BB->end();
10852       }
10853       continue;
10854     }
10855 
10856     if (isa<DbgInfoIntrinsic>(it))
10857       continue;
10858 
10859     // Try to vectorize reductions that use PHINodes.
10860     if (PHINode *P = dyn_cast<PHINode>(it)) {
10861       // Check that the PHI is a reduction PHI.
10862       if (P->getNumIncomingValues() == 2) {
10863         // Try to match and vectorize a horizontal reduction.
10864         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10865                                      TTI)) {
10866           Changed = true;
10867           it = BB->begin();
10868           e = BB->end();
10869           continue;
10870         }
10871       }
10872       // Try to vectorize the incoming values of the PHI, to catch reductions
10873       // that feed into PHIs.
10874       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10875         // Skip if the incoming block is the current BB for now. Also, bypass
10876         // unreachable IR for efficiency and to avoid crashing.
10877         // TODO: Collect the skipped incoming values and try to vectorize them
10878         // after processing BB.
10879         if (BB == P->getIncomingBlock(I) ||
10880             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10881           continue;
10882 
10883         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10884                                             P->getIncomingBlock(I), R, TTI);
10885       }
10886       continue;
10887     }
10888 
10889     // Ran into an instruction without users, like terminator, or function call
10890     // with ignored return value, store. Ignore unused instructions (basing on
10891     // instruction type, except for CallInst and InvokeInst).
10892     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10893                             isa<InvokeInst>(it))) {
10894       KeyNodes.insert(&*it);
10895       bool OpsChanged = false;
10896       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10897         for (auto *V : it->operand_values()) {
10898           // Try to match and vectorize a horizontal reduction.
10899           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10900         }
10901       }
10902       // Start vectorization of post-process list of instructions from the
10903       // top-tree instructions to try to vectorize as many instructions as
10904       // possible.
10905       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10906                                                 it->isTerminator());
10907       if (OpsChanged) {
10908         // We would like to start over since some instructions are deleted
10909         // and the iterator may become invalid value.
10910         Changed = true;
10911         it = BB->begin();
10912         e = BB->end();
10913         continue;
10914       }
10915     }
10916 
10917     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10918         isa<InsertValueInst>(it))
10919       PostProcessInstructions.push_back(&*it);
10920   }
10921 
10922   return Changed;
10923 }
10924 
10925 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10926   auto Changed = false;
10927   for (auto &Entry : GEPs) {
10928     // If the getelementptr list has fewer than two elements, there's nothing
10929     // to do.
10930     if (Entry.second.size() < 2)
10931       continue;
10932 
10933     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10934                       << Entry.second.size() << ".\n");
10935 
10936     // Process the GEP list in chunks suitable for the target's supported
10937     // vector size. If a vector register can't hold 1 element, we are done. We
10938     // are trying to vectorize the index computations, so the maximum number of
10939     // elements is based on the size of the index expression, rather than the
10940     // size of the GEP itself (the target's pointer size).
10941     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10942     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10943     if (MaxVecRegSize < EltSize)
10944       continue;
10945 
10946     unsigned MaxElts = MaxVecRegSize / EltSize;
10947     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10948       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10949       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10950 
10951       // Initialize a set a candidate getelementptrs. Note that we use a
10952       // SetVector here to preserve program order. If the index computations
10953       // are vectorizable and begin with loads, we want to minimize the chance
10954       // of having to reorder them later.
10955       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10956 
10957       // Some of the candidates may have already been vectorized after we
10958       // initially collected them. If so, they are marked as deleted, so remove
10959       // them from the set of candidates.
10960       Candidates.remove_if(
10961           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10962 
10963       // Remove from the set of candidates all pairs of getelementptrs with
10964       // constant differences. Such getelementptrs are likely not good
10965       // candidates for vectorization in a bottom-up phase since one can be
10966       // computed from the other. We also ensure all candidate getelementptr
10967       // indices are unique.
10968       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10969         auto *GEPI = GEPList[I];
10970         if (!Candidates.count(GEPI))
10971           continue;
10972         auto *SCEVI = SE->getSCEV(GEPList[I]);
10973         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10974           auto *GEPJ = GEPList[J];
10975           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10976           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10977             Candidates.remove(GEPI);
10978             Candidates.remove(GEPJ);
10979           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10980             Candidates.remove(GEPJ);
10981           }
10982         }
10983       }
10984 
10985       // We break out of the above computation as soon as we know there are
10986       // fewer than two candidates remaining.
10987       if (Candidates.size() < 2)
10988         continue;
10989 
10990       // Add the single, non-constant index of each candidate to the bundle. We
10991       // ensured the indices met these constraints when we originally collected
10992       // the getelementptrs.
10993       SmallVector<Value *, 16> Bundle(Candidates.size());
10994       auto BundleIndex = 0u;
10995       for (auto *V : Candidates) {
10996         auto *GEP = cast<GetElementPtrInst>(V);
10997         auto *GEPIdx = GEP->idx_begin()->get();
10998         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10999         Bundle[BundleIndex++] = GEPIdx;
11000       }
11001 
11002       // Try and vectorize the indices. We are currently only interested in
11003       // gather-like cases of the form:
11004       //
11005       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
11006       //
11007       // where the loads of "a", the loads of "b", and the subtractions can be
11008       // performed in parallel. It's likely that detecting this pattern in a
11009       // bottom-up phase will be simpler and less costly than building a
11010       // full-blown top-down phase beginning at the consecutive loads.
11011       Changed |= tryToVectorizeList(Bundle, R);
11012     }
11013   }
11014   return Changed;
11015 }
11016 
11017 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
11018   bool Changed = false;
11019   // Sort by type, base pointers and values operand. Value operands must be
11020   // compatible (have the same opcode, same parent), otherwise it is
11021   // definitely not profitable to try to vectorize them.
11022   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
11023     if (V->getPointerOperandType()->getTypeID() <
11024         V2->getPointerOperandType()->getTypeID())
11025       return true;
11026     if (V->getPointerOperandType()->getTypeID() >
11027         V2->getPointerOperandType()->getTypeID())
11028       return false;
11029     // UndefValues are compatible with all other values.
11030     if (isa<UndefValue>(V->getValueOperand()) ||
11031         isa<UndefValue>(V2->getValueOperand()))
11032       return false;
11033     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
11034       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11035         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
11036             DT->getNode(I1->getParent());
11037         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
11038             DT->getNode(I2->getParent());
11039         assert(NodeI1 && "Should only process reachable instructions");
11040         assert(NodeI1 && "Should only process reachable instructions");
11041         assert((NodeI1 == NodeI2) ==
11042                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
11043                "Different nodes should have different DFS numbers");
11044         if (NodeI1 != NodeI2)
11045           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
11046         InstructionsState S = getSameOpcode({I1, I2});
11047         if (S.getOpcode())
11048           return false;
11049         return I1->getOpcode() < I2->getOpcode();
11050       }
11051     if (isa<Constant>(V->getValueOperand()) &&
11052         isa<Constant>(V2->getValueOperand()))
11053       return false;
11054     return V->getValueOperand()->getValueID() <
11055            V2->getValueOperand()->getValueID();
11056   };
11057 
11058   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
11059     if (V1 == V2)
11060       return true;
11061     if (V1->getPointerOperandType() != V2->getPointerOperandType())
11062       return false;
11063     // Undefs are compatible with any other value.
11064     if (isa<UndefValue>(V1->getValueOperand()) ||
11065         isa<UndefValue>(V2->getValueOperand()))
11066       return true;
11067     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
11068       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
11069         if (I1->getParent() != I2->getParent())
11070           return false;
11071         InstructionsState S = getSameOpcode({I1, I2});
11072         return S.getOpcode() > 0;
11073       }
11074     if (isa<Constant>(V1->getValueOperand()) &&
11075         isa<Constant>(V2->getValueOperand()))
11076       return true;
11077     return V1->getValueOperand()->getValueID() ==
11078            V2->getValueOperand()->getValueID();
11079   };
11080   auto Limit = [&R, this](StoreInst *SI) {
11081     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
11082     return R.getMinVF(EltSize);
11083   };
11084 
11085   // Attempt to sort and vectorize each of the store-groups.
11086   for (auto &Pair : Stores) {
11087     if (Pair.second.size() < 2)
11088       continue;
11089 
11090     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
11091                       << Pair.second.size() << ".\n");
11092 
11093     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
11094       continue;
11095 
11096     Changed |= tryToVectorizeSequence<StoreInst>(
11097         Pair.second, Limit, StoreSorter, AreCompatibleStores,
11098         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
11099           return vectorizeStores(Candidates, R);
11100         },
11101         /*LimitForRegisterSize=*/false);
11102   }
11103   return Changed;
11104 }
11105 
11106 char SLPVectorizer::ID = 0;
11107 
11108 static const char lv_name[] = "SLP Vectorizer";
11109 
11110 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
11111 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
11112 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
11113 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
11114 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
11115 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
11116 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
11117 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
11118 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
11119 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
11120 
11121 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
11122