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/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.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 namespace slpvectorizer {
776 
777 /// Bottom Up SLP Vectorizer.
778 class BoUpSLP {
779   struct TreeEntry;
780   struct ScheduleData;
781 
782 public:
783   using ValueList = SmallVector<Value *, 8>;
784   using InstrList = SmallVector<Instruction *, 16>;
785   using ValueSet = SmallPtrSet<Value *, 16>;
786   using StoreList = SmallVector<StoreInst *, 8>;
787   using ExtraValueToDebugLocsMap =
788       MapVector<Value *, SmallVector<Instruction *, 2>>;
789   using OrdersType = SmallVector<unsigned, 4>;
790 
791   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
792           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
793           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
794           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
795       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
796         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
797     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
798     // Use the vector register size specified by the target unless overridden
799     // by a command-line option.
800     // TODO: It would be better to limit the vectorization factor based on
801     //       data type rather than just register size. For example, x86 AVX has
802     //       256-bit registers, but it does not support integer operations
803     //       at that width (that requires AVX2).
804     if (MaxVectorRegSizeOption.getNumOccurrences())
805       MaxVecRegSize = MaxVectorRegSizeOption;
806     else
807       MaxVecRegSize =
808           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
809               .getFixedSize();
810 
811     if (MinVectorRegSizeOption.getNumOccurrences())
812       MinVecRegSize = MinVectorRegSizeOption;
813     else
814       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
815   }
816 
817   /// Vectorize the tree that starts with the elements in \p VL.
818   /// Returns the vectorized root.
819   Value *vectorizeTree();
820 
821   /// Vectorize the tree but with the list of externally used values \p
822   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
823   /// generated extractvalue instructions.
824   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
825 
826   /// \returns the cost incurred by unwanted spills and fills, caused by
827   /// holding live values over call sites.
828   InstructionCost getSpillCost() const;
829 
830   /// \returns the vectorization cost of the subtree that starts at \p VL.
831   /// A negative number means that this is profitable.
832   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
833 
834   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
835   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
836   void buildTree(ArrayRef<Value *> Roots,
837                  ArrayRef<Value *> UserIgnoreLst = None);
838 
839   /// Builds external uses of the vectorized scalars, i.e. the list of
840   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
841   /// ExternallyUsedValues contains additional list of external uses to handle
842   /// vectorization of reductions.
843   void
844   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
845 
846   /// Clear the internal data structures that are created by 'buildTree'.
847   void deleteTree() {
848     VectorizableTree.clear();
849     ScalarToTreeEntry.clear();
850     MustGather.clear();
851     ExternalUses.clear();
852     for (auto &Iter : BlocksSchedules) {
853       BlockScheduling *BS = Iter.second.get();
854       BS->clear();
855     }
856     MinBWs.clear();
857     InstrElementSize.clear();
858   }
859 
860   unsigned getTreeSize() const { return VectorizableTree.size(); }
861 
862   /// Perform LICM and CSE on the newly generated gather sequences.
863   void optimizeGatherSequence();
864 
865   /// Checks if the specified gather tree entry \p TE can be represented as a
866   /// shuffled vector entry + (possibly) permutation with other gathers. It
867   /// implements the checks only for possibly ordered scalars (Loads,
868   /// ExtractElement, ExtractValue), which can be part of the graph.
869   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
870 
871   /// Gets reordering data for the given tree entry. If the entry is vectorized
872   /// - just return ReorderIndices, otherwise check if the scalars can be
873   /// reordered and return the most optimal order.
874   /// \param TopToBottom If true, include the order of vectorized stores and
875   /// insertelement nodes, otherwise skip them.
876   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
877 
878   /// Reorders the current graph to the most profitable order starting from the
879   /// root node to the leaf nodes. The best order is chosen only from the nodes
880   /// of the same size (vectorization factor). Smaller nodes are considered
881   /// parts of subgraph with smaller VF and they are reordered independently. We
882   /// can make it because we still need to extend smaller nodes to the wider VF
883   /// and we can merge reordering shuffles with the widening shuffles.
884   void reorderTopToBottom();
885 
886   /// Reorders the current graph to the most profitable order starting from
887   /// leaves to the root. It allows to rotate small subgraphs and reduce the
888   /// number of reshuffles if the leaf nodes use the same order. In this case we
889   /// can merge the orders and just shuffle user node instead of shuffling its
890   /// operands. Plus, even the leaf nodes have different orders, it allows to
891   /// sink reordering in the graph closer to the root node and merge it later
892   /// during analysis.
893   void reorderBottomToTop(bool IgnoreReorder = false);
894 
895   /// \return The vector element size in bits to use when vectorizing the
896   /// expression tree ending at \p V. If V is a store, the size is the width of
897   /// the stored value. Otherwise, the size is the width of the largest loaded
898   /// value reaching V. This method is used by the vectorizer to calculate
899   /// vectorization factors.
900   unsigned getVectorElementSize(Value *V);
901 
902   /// Compute the minimum type sizes required to represent the entries in a
903   /// vectorizable tree.
904   void computeMinimumValueSizes();
905 
906   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
907   unsigned getMaxVecRegSize() const {
908     return MaxVecRegSize;
909   }
910 
911   // \returns minimum vector register size as set by cl::opt.
912   unsigned getMinVecRegSize() const {
913     return MinVecRegSize;
914   }
915 
916   unsigned getMinVF(unsigned Sz) const {
917     return std::max(2U, getMinVecRegSize() / Sz);
918   }
919 
920   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
921     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
922       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
923     return MaxVF ? MaxVF : UINT_MAX;
924   }
925 
926   /// Check if homogeneous aggregate is isomorphic to some VectorType.
927   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
928   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
929   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
930   ///
931   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
932   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
933 
934   /// \returns True if the VectorizableTree is both tiny and not fully
935   /// vectorizable. We do not vectorize such trees.
936   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
937 
938   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
939   /// can be load combined in the backend. Load combining may not be allowed in
940   /// the IR optimizer, so we do not want to alter the pattern. For example,
941   /// partially transforming a scalar bswap() pattern into vector code is
942   /// effectively impossible for the backend to undo.
943   /// TODO: If load combining is allowed in the IR optimizer, this analysis
944   ///       may not be necessary.
945   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
946 
947   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
948   /// can be load combined in the backend. Load combining may not be allowed in
949   /// the IR optimizer, so we do not want to alter the pattern. For example,
950   /// partially transforming a scalar bswap() pattern into vector code is
951   /// effectively impossible for the backend to undo.
952   /// TODO: If load combining is allowed in the IR optimizer, this analysis
953   ///       may not be necessary.
954   bool isLoadCombineCandidate() const;
955 
956   OptimizationRemarkEmitter *getORE() { return ORE; }
957 
958   /// This structure holds any data we need about the edges being traversed
959   /// during buildTree_rec(). We keep track of:
960   /// (i) the user TreeEntry index, and
961   /// (ii) the index of the edge.
962   struct EdgeInfo {
963     EdgeInfo() = default;
964     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
965         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
966     /// The user TreeEntry.
967     TreeEntry *UserTE = nullptr;
968     /// The operand index of the use.
969     unsigned EdgeIdx = UINT_MAX;
970 #ifndef NDEBUG
971     friend inline raw_ostream &operator<<(raw_ostream &OS,
972                                           const BoUpSLP::EdgeInfo &EI) {
973       EI.dump(OS);
974       return OS;
975     }
976     /// Debug print.
977     void dump(raw_ostream &OS) const {
978       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
979          << " EdgeIdx:" << EdgeIdx << "}";
980     }
981     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
982 #endif
983   };
984 
985   /// A helper data structure to hold the operands of a vector of instructions.
986   /// This supports a fixed vector length for all operand vectors.
987   class VLOperands {
988     /// For each operand we need (i) the value, and (ii) the opcode that it
989     /// would be attached to if the expression was in a left-linearized form.
990     /// This is required to avoid illegal operand reordering.
991     /// For example:
992     /// \verbatim
993     ///                         0 Op1
994     ///                         |/
995     /// Op1 Op2   Linearized    + Op2
996     ///   \ /     ---------->   |/
997     ///    -                    -
998     ///
999     /// Op1 - Op2            (0 + Op1) - Op2
1000     /// \endverbatim
1001     ///
1002     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1003     ///
1004     /// Another way to think of this is to track all the operations across the
1005     /// path from the operand all the way to the root of the tree and to
1006     /// calculate the operation that corresponds to this path. For example, the
1007     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1008     /// corresponding operation is a '-' (which matches the one in the
1009     /// linearized tree, as shown above).
1010     ///
1011     /// For lack of a better term, we refer to this operation as Accumulated
1012     /// Path Operation (APO).
1013     struct OperandData {
1014       OperandData() = default;
1015       OperandData(Value *V, bool APO, bool IsUsed)
1016           : V(V), APO(APO), IsUsed(IsUsed) {}
1017       /// The operand value.
1018       Value *V = nullptr;
1019       /// TreeEntries only allow a single opcode, or an alternate sequence of
1020       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1021       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1022       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1023       /// (e.g., Add/Mul)
1024       bool APO = false;
1025       /// Helper data for the reordering function.
1026       bool IsUsed = false;
1027     };
1028 
1029     /// During operand reordering, we are trying to select the operand at lane
1030     /// that matches best with the operand at the neighboring lane. Our
1031     /// selection is based on the type of value we are looking for. For example,
1032     /// if the neighboring lane has a load, we need to look for a load that is
1033     /// accessing a consecutive address. These strategies are summarized in the
1034     /// 'ReorderingMode' enumerator.
1035     enum class ReorderingMode {
1036       Load,     ///< Matching loads to consecutive memory addresses
1037       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1038       Constant, ///< Matching constants
1039       Splat,    ///< Matching the same instruction multiple times (broadcast)
1040       Failed,   ///< We failed to create a vectorizable group
1041     };
1042 
1043     using OperandDataVec = SmallVector<OperandData, 2>;
1044 
1045     /// A vector of operand vectors.
1046     SmallVector<OperandDataVec, 4> OpsVec;
1047 
1048     const DataLayout &DL;
1049     ScalarEvolution &SE;
1050     const BoUpSLP &R;
1051 
1052     /// \returns the operand data at \p OpIdx and \p Lane.
1053     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1054       return OpsVec[OpIdx][Lane];
1055     }
1056 
1057     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1058     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1059       return OpsVec[OpIdx][Lane];
1060     }
1061 
1062     /// Clears the used flag for all entries.
1063     void clearUsed() {
1064       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1065            OpIdx != NumOperands; ++OpIdx)
1066         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1067              ++Lane)
1068           OpsVec[OpIdx][Lane].IsUsed = false;
1069     }
1070 
1071     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1072     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1073       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1074     }
1075 
1076     // The hard-coded scores listed here are not very important, though it shall
1077     // be higher for better matches to improve the resulting cost. When
1078     // computing the scores of matching one sub-tree with another, we are
1079     // basically counting the number of values that are matching. So even if all
1080     // scores are set to 1, we would still get a decent matching result.
1081     // However, sometimes we have to break ties. For example we may have to
1082     // choose between matching loads vs matching opcodes. This is what these
1083     // scores are helping us with: they provide the order of preference. Also,
1084     // this is important if the scalar is externally used or used in another
1085     // tree entry node in the different lane.
1086 
1087     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1088     static const int ScoreConsecutiveLoads = 4;
1089     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1090     static const int ScoreReversedLoads = 3;
1091     /// ExtractElementInst from same vector and consecutive indexes.
1092     static const int ScoreConsecutiveExtracts = 4;
1093     /// ExtractElementInst from same vector and reversed indices.
1094     static const int ScoreReversedExtracts = 3;
1095     /// Constants.
1096     static const int ScoreConstants = 2;
1097     /// Instructions with the same opcode.
1098     static const int ScoreSameOpcode = 2;
1099     /// Instructions with alt opcodes (e.g, add + sub).
1100     static const int ScoreAltOpcodes = 1;
1101     /// Identical instructions (a.k.a. splat or broadcast).
1102     static const int ScoreSplat = 1;
1103     /// Matching with an undef is preferable to failing.
1104     static const int ScoreUndef = 1;
1105     /// Score for failing to find a decent match.
1106     static const int ScoreFail = 0;
1107     /// Score if all users are vectorized.
1108     static const int ScoreAllUserVectorized = 1;
1109 
1110     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1111     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1112     /// MainAltOps.
1113     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1114                                ScalarEvolution &SE, int NumLanes,
1115                                ArrayRef<Value *> MainAltOps) {
1116       if (V1 == V2)
1117         return VLOperands::ScoreSplat;
1118 
1119       auto *LI1 = dyn_cast<LoadInst>(V1);
1120       auto *LI2 = dyn_cast<LoadInst>(V2);
1121       if (LI1 && LI2) {
1122         if (LI1->getParent() != LI2->getParent())
1123           return VLOperands::ScoreFail;
1124 
1125         Optional<int> Dist = getPointersDiff(
1126             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1127             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1128         if (!Dist || *Dist == 0)
1129           return VLOperands::ScoreFail;
1130         // The distance is too large - still may be profitable to use masked
1131         // loads/gathers.
1132         if (std::abs(*Dist) > NumLanes / 2)
1133           return VLOperands::ScoreAltOpcodes;
1134         // This still will detect consecutive loads, but we might have "holes"
1135         // in some cases. It is ok for non-power-2 vectorization and may produce
1136         // better results. It should not affect current vectorization.
1137         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1138                            : VLOperands::ScoreReversedLoads;
1139       }
1140 
1141       auto *C1 = dyn_cast<Constant>(V1);
1142       auto *C2 = dyn_cast<Constant>(V2);
1143       if (C1 && C2)
1144         return VLOperands::ScoreConstants;
1145 
1146       // Extracts from consecutive indexes of the same vector better score as
1147       // the extracts could be optimized away.
1148       Value *EV1;
1149       ConstantInt *Ex1Idx;
1150       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1151         // Undefs are always profitable for extractelements.
1152         if (isa<UndefValue>(V2))
1153           return VLOperands::ScoreConsecutiveExtracts;
1154         Value *EV2 = nullptr;
1155         ConstantInt *Ex2Idx = nullptr;
1156         if (match(V2,
1157                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1158                                                          m_Undef())))) {
1159           // Undefs are always profitable for extractelements.
1160           if (!Ex2Idx)
1161             return VLOperands::ScoreConsecutiveExtracts;
1162           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1163             return VLOperands::ScoreConsecutiveExtracts;
1164           if (EV2 == EV1) {
1165             int Idx1 = Ex1Idx->getZExtValue();
1166             int Idx2 = Ex2Idx->getZExtValue();
1167             int Dist = Idx2 - Idx1;
1168             // The distance is too large - still may be profitable to use
1169             // shuffles.
1170             if (std::abs(Dist) == 0)
1171               return VLOperands::ScoreSplat;
1172             if (std::abs(Dist) > NumLanes / 2)
1173               return VLOperands::ScoreSameOpcode;
1174             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1175                               : VLOperands::ScoreReversedExtracts;
1176           }
1177           return VLOperands::ScoreAltOpcodes;
1178         }
1179         return VLOperands::ScoreFail;
1180       }
1181 
1182       auto *I1 = dyn_cast<Instruction>(V1);
1183       auto *I2 = dyn_cast<Instruction>(V2);
1184       if (I1 && I2) {
1185         if (I1->getParent() != I2->getParent())
1186           return VLOperands::ScoreFail;
1187         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1188         Ops.push_back(I1);
1189         Ops.push_back(I2);
1190         InstructionsState S = getSameOpcode(Ops);
1191         // Note: Only consider instructions with <= 2 operands to avoid
1192         // complexity explosion.
1193         if (S.getOpcode() &&
1194             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1195              !S.isAltShuffle()) &&
1196             all_of(Ops, [&S](Value *V) {
1197               return cast<Instruction>(V)->getNumOperands() ==
1198                      S.MainOp->getNumOperands();
1199             }))
1200           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1201                                   : VLOperands::ScoreSameOpcode;
1202       }
1203 
1204       if (isa<UndefValue>(V2))
1205         return VLOperands::ScoreUndef;
1206 
1207       return VLOperands::ScoreFail;
1208     }
1209 
1210     /// \param Lane lane of the operands under analysis.
1211     /// \param OpIdx operand index in \p Lane lane we're looking the best
1212     /// candidate for.
1213     /// \param Idx operand index of the current candidate value.
1214     /// \returns The additional score due to possible broadcasting of the
1215     /// elements in the lane. It is more profitable to have power-of-2 unique
1216     /// elements in the lane, it will be vectorized with higher probability
1217     /// after removing duplicates. Currently the SLP vectorizer supports only
1218     /// vectorization of the power-of-2 number of unique scalars.
1219     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1220       Value *IdxLaneV = getData(Idx, Lane).V;
1221       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1222         return 0;
1223       SmallPtrSet<Value *, 4> Uniques;
1224       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1225         if (Ln == Lane)
1226           continue;
1227         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1228         if (!isa<Instruction>(OpIdxLnV))
1229           return 0;
1230         Uniques.insert(OpIdxLnV);
1231       }
1232       int UniquesCount = Uniques.size();
1233       int UniquesCntWithIdxLaneV =
1234           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1235       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1236       int UniquesCntWithOpIdxLaneV =
1237           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1238       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1239         return 0;
1240       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1241               UniquesCntWithOpIdxLaneV) -
1242              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1243     }
1244 
1245     /// \param Lane lane of the operands under analysis.
1246     /// \param OpIdx operand index in \p Lane lane we're looking the best
1247     /// candidate for.
1248     /// \param Idx operand index of the current candidate value.
1249     /// \returns The additional score for the scalar which users are all
1250     /// vectorized.
1251     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1252       Value *IdxLaneV = getData(Idx, Lane).V;
1253       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1254       // Do not care about number of uses for vector-like instructions
1255       // (extractelement/extractvalue with constant indices), they are extracts
1256       // themselves and already externally used. Vectorization of such
1257       // instructions does not add extra extractelement instruction, just may
1258       // remove it.
1259       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1260           isVectorLikeInstWithConstOps(OpIdxLaneV))
1261         return VLOperands::ScoreAllUserVectorized;
1262       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1263       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1264         return 0;
1265       return R.areAllUsersVectorized(IdxLaneI, None)
1266                  ? VLOperands::ScoreAllUserVectorized
1267                  : 0;
1268     }
1269 
1270     /// Go through the operands of \p LHS and \p RHS recursively until \p
1271     /// MaxLevel, and return the cummulative score. For example:
1272     /// \verbatim
1273     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1274     ///     \ /         \ /         \ /        \ /
1275     ///      +           +           +          +
1276     ///     G1          G2          G3         G4
1277     /// \endverbatim
1278     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1279     /// each level recursively, accumulating the score. It starts from matching
1280     /// the additions at level 0, then moves on to the loads (level 1). The
1281     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1282     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1283     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1284     /// Please note that the order of the operands does not matter, as we
1285     /// evaluate the score of all profitable combinations of operands. In
1286     /// other words the score of G1 and G4 is the same as G1 and G2. This
1287     /// heuristic is based on ideas described in:
1288     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1289     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1290     ///   Luís F. W. Góes
1291     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1292                            ArrayRef<Value *> MainAltOps) {
1293 
1294       // Get the shallow score of V1 and V2.
1295       int ShallowScoreAtThisLevel =
1296           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1297 
1298       // If reached MaxLevel,
1299       //  or if V1 and V2 are not instructions,
1300       //  or if they are SPLAT,
1301       //  or if they are not consecutive,
1302       //  or if profitable to vectorize loads or extractelements, early return
1303       //  the current cost.
1304       auto *I1 = dyn_cast<Instruction>(LHS);
1305       auto *I2 = dyn_cast<Instruction>(RHS);
1306       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1307           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1308           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1309             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1310             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1311            ShallowScoreAtThisLevel))
1312         return ShallowScoreAtThisLevel;
1313       assert(I1 && I2 && "Should have early exited.");
1314 
1315       // Contains the I2 operand indexes that got matched with I1 operands.
1316       SmallSet<unsigned, 4> Op2Used;
1317 
1318       // Recursion towards the operands of I1 and I2. We are trying all possible
1319       // operand pairs, and keeping track of the best score.
1320       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1321            OpIdx1 != NumOperands1; ++OpIdx1) {
1322         // Try to pair op1I with the best operand of I2.
1323         int MaxTmpScore = 0;
1324         unsigned MaxOpIdx2 = 0;
1325         bool FoundBest = false;
1326         // If I2 is commutative try all combinations.
1327         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1328         unsigned ToIdx = isCommutative(I2)
1329                              ? I2->getNumOperands()
1330                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1331         assert(FromIdx <= ToIdx && "Bad index");
1332         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1333           // Skip operands already paired with OpIdx1.
1334           if (Op2Used.count(OpIdx2))
1335             continue;
1336           // Recursively calculate the cost at each level
1337           int TmpScore =
1338               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1339                                  CurrLevel + 1, MaxLevel, None);
1340           // Look for the best score.
1341           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1342             MaxTmpScore = TmpScore;
1343             MaxOpIdx2 = OpIdx2;
1344             FoundBest = true;
1345           }
1346         }
1347         if (FoundBest) {
1348           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1349           Op2Used.insert(MaxOpIdx2);
1350           ShallowScoreAtThisLevel += MaxTmpScore;
1351         }
1352       }
1353       return ShallowScoreAtThisLevel;
1354     }
1355 
1356     /// Score scaling factor for fully compatible instructions but with
1357     /// different number of external uses. Allows better selection of the
1358     /// instructions with less external uses.
1359     static const int ScoreScaleFactor = 10;
1360 
1361     /// \Returns the look-ahead score, which tells us how much the sub-trees
1362     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1363     /// score. This helps break ties in an informed way when we cannot decide on
1364     /// the order of the operands by just considering the immediate
1365     /// predecessors.
1366     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1367                           int Lane, unsigned OpIdx, unsigned Idx,
1368                           bool &IsUsed) {
1369       int Score =
1370           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1371       if (Score) {
1372         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1373         if (Score <= -SplatScore) {
1374           // Set the minimum score for splat-like sequence to avoid setting
1375           // failed state.
1376           Score = 1;
1377         } else {
1378           Score += SplatScore;
1379           // Scale score to see the difference between different operands
1380           // and similar operands but all vectorized/not all vectorized
1381           // uses. It does not affect actual selection of the best
1382           // compatible operand in general, just allows to select the
1383           // operand with all vectorized uses.
1384           Score *= ScoreScaleFactor;
1385           Score += getExternalUseScore(Lane, OpIdx, Idx);
1386           IsUsed = true;
1387         }
1388       }
1389       return Score;
1390     }
1391 
1392     /// Best defined scores per lanes between the passes. Used to choose the
1393     /// best operand (with the highest score) between the passes.
1394     /// The key - {Operand Index, Lane}.
1395     /// The value - the best score between the passes for the lane and the
1396     /// operand.
1397     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1398         BestScoresPerLanes;
1399 
1400     // Search all operands in Ops[*][Lane] for the one that matches best
1401     // Ops[OpIdx][LastLane] and return its opreand index.
1402     // If no good match can be found, return None.
1403     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1404                                       ArrayRef<ReorderingMode> ReorderingModes,
1405                                       ArrayRef<Value *> MainAltOps) {
1406       unsigned NumOperands = getNumOperands();
1407 
1408       // The operand of the previous lane at OpIdx.
1409       Value *OpLastLane = getData(OpIdx, LastLane).V;
1410 
1411       // Our strategy mode for OpIdx.
1412       ReorderingMode RMode = ReorderingModes[OpIdx];
1413       if (RMode == ReorderingMode::Failed)
1414         return None;
1415 
1416       // The linearized opcode of the operand at OpIdx, Lane.
1417       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1418 
1419       // The best operand index and its score.
1420       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1421       // are using the score to differentiate between the two.
1422       struct BestOpData {
1423         Optional<unsigned> Idx = None;
1424         unsigned Score = 0;
1425       } BestOp;
1426       BestOp.Score =
1427           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1428               .first->second;
1429 
1430       // Track if the operand must be marked as used. If the operand is set to
1431       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1432       // want to reestimate the operands again on the following iterations).
1433       bool IsUsed =
1434           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1435       // Iterate through all unused operands and look for the best.
1436       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1437         // Get the operand at Idx and Lane.
1438         OperandData &OpData = getData(Idx, Lane);
1439         Value *Op = OpData.V;
1440         bool OpAPO = OpData.APO;
1441 
1442         // Skip already selected operands.
1443         if (OpData.IsUsed)
1444           continue;
1445 
1446         // Skip if we are trying to move the operand to a position with a
1447         // different opcode in the linearized tree form. This would break the
1448         // semantics.
1449         if (OpAPO != OpIdxAPO)
1450           continue;
1451 
1452         // Look for an operand that matches the current mode.
1453         switch (RMode) {
1454         case ReorderingMode::Load:
1455         case ReorderingMode::Constant:
1456         case ReorderingMode::Opcode: {
1457           bool LeftToRight = Lane > LastLane;
1458           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1459           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1460           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1461                                         OpIdx, Idx, IsUsed);
1462           if (Score > static_cast<int>(BestOp.Score)) {
1463             BestOp.Idx = Idx;
1464             BestOp.Score = Score;
1465             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1466           }
1467           break;
1468         }
1469         case ReorderingMode::Splat:
1470           if (Op == OpLastLane)
1471             BestOp.Idx = Idx;
1472           break;
1473         case ReorderingMode::Failed:
1474           llvm_unreachable("Not expected Failed reordering mode.");
1475         }
1476       }
1477 
1478       if (BestOp.Idx) {
1479         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1480         return BestOp.Idx;
1481       }
1482       // If we could not find a good match return None.
1483       return None;
1484     }
1485 
1486     /// Helper for reorderOperandVecs.
1487     /// \returns the lane that we should start reordering from. This is the one
1488     /// which has the least number of operands that can freely move about or
1489     /// less profitable because it already has the most optimal set of operands.
1490     unsigned getBestLaneToStartReordering() const {
1491       unsigned Min = UINT_MAX;
1492       unsigned SameOpNumber = 0;
1493       // std::pair<unsigned, unsigned> is used to implement a simple voting
1494       // algorithm and choose the lane with the least number of operands that
1495       // can freely move about or less profitable because it already has the
1496       // most optimal set of operands. The first unsigned is a counter for
1497       // voting, the second unsigned is the counter of lanes with instructions
1498       // with same/alternate opcodes and same parent basic block.
1499       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1500       // Try to be closer to the original results, if we have multiple lanes
1501       // with same cost. If 2 lanes have the same cost, use the one with the
1502       // lowest index.
1503       for (int I = getNumLanes(); I > 0; --I) {
1504         unsigned Lane = I - 1;
1505         OperandsOrderData NumFreeOpsHash =
1506             getMaxNumOperandsThatCanBeReordered(Lane);
1507         // Compare the number of operands that can move and choose the one with
1508         // the least number.
1509         if (NumFreeOpsHash.NumOfAPOs < Min) {
1510           Min = NumFreeOpsHash.NumOfAPOs;
1511           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1512           HashMap.clear();
1513           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1514         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1515                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1516           // Select the most optimal lane in terms of number of operands that
1517           // should be moved around.
1518           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1519           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1520         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1521                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1522           auto It = HashMap.find(NumFreeOpsHash.Hash);
1523           if (It == HashMap.end())
1524             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1525           else
1526             ++It->second.first;
1527         }
1528       }
1529       // Select the lane with the minimum counter.
1530       unsigned BestLane = 0;
1531       unsigned CntMin = UINT_MAX;
1532       for (const auto &Data : reverse(HashMap)) {
1533         if (Data.second.first < CntMin) {
1534           CntMin = Data.second.first;
1535           BestLane = Data.second.second;
1536         }
1537       }
1538       return BestLane;
1539     }
1540 
1541     /// Data structure that helps to reorder operands.
1542     struct OperandsOrderData {
1543       /// The best number of operands with the same APOs, which can be
1544       /// reordered.
1545       unsigned NumOfAPOs = UINT_MAX;
1546       /// Number of operands with the same/alternate instruction opcode and
1547       /// parent.
1548       unsigned NumOpsWithSameOpcodeParent = 0;
1549       /// Hash for the actual operands ordering.
1550       /// Used to count operands, actually their position id and opcode
1551       /// value. It is used in the voting mechanism to find the lane with the
1552       /// least number of operands that can freely move about or less profitable
1553       /// because it already has the most optimal set of operands. Can be
1554       /// replaced with SmallVector<unsigned> instead but hash code is faster
1555       /// and requires less memory.
1556       unsigned Hash = 0;
1557     };
1558     /// \returns the maximum number of operands that are allowed to be reordered
1559     /// for \p Lane and the number of compatible instructions(with the same
1560     /// parent/opcode). This is used as a heuristic for selecting the first lane
1561     /// to start operand reordering.
1562     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1563       unsigned CntTrue = 0;
1564       unsigned NumOperands = getNumOperands();
1565       // Operands with the same APO can be reordered. We therefore need to count
1566       // how many of them we have for each APO, like this: Cnt[APO] = x.
1567       // Since we only have two APOs, namely true and false, we can avoid using
1568       // a map. Instead we can simply count the number of operands that
1569       // correspond to one of them (in this case the 'true' APO), and calculate
1570       // the other by subtracting it from the total number of operands.
1571       // Operands with the same instruction opcode and parent are more
1572       // profitable since we don't need to move them in many cases, with a high
1573       // probability such lane already can be vectorized effectively.
1574       bool AllUndefs = true;
1575       unsigned NumOpsWithSameOpcodeParent = 0;
1576       Instruction *OpcodeI = nullptr;
1577       BasicBlock *Parent = nullptr;
1578       unsigned Hash = 0;
1579       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1580         const OperandData &OpData = getData(OpIdx, Lane);
1581         if (OpData.APO)
1582           ++CntTrue;
1583         // Use Boyer-Moore majority voting for finding the majority opcode and
1584         // the number of times it occurs.
1585         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1586           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1587               I->getParent() != Parent) {
1588             if (NumOpsWithSameOpcodeParent == 0) {
1589               NumOpsWithSameOpcodeParent = 1;
1590               OpcodeI = I;
1591               Parent = I->getParent();
1592             } else {
1593               --NumOpsWithSameOpcodeParent;
1594             }
1595           } else {
1596             ++NumOpsWithSameOpcodeParent;
1597           }
1598         }
1599         Hash = hash_combine(
1600             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1601         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1602       }
1603       if (AllUndefs)
1604         return {};
1605       OperandsOrderData Data;
1606       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1607       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1608       Data.Hash = Hash;
1609       return Data;
1610     }
1611 
1612     /// Go through the instructions in VL and append their operands.
1613     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1614       assert(!VL.empty() && "Bad VL");
1615       assert((empty() || VL.size() == getNumLanes()) &&
1616              "Expected same number of lanes");
1617       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1618       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1619       OpsVec.resize(NumOperands);
1620       unsigned NumLanes = VL.size();
1621       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1622         OpsVec[OpIdx].resize(NumLanes);
1623         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1624           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1625           // Our tree has just 3 nodes: the root and two operands.
1626           // It is therefore trivial to get the APO. We only need to check the
1627           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1628           // RHS operand. The LHS operand of both add and sub is never attached
1629           // to an inversese operation in the linearized form, therefore its APO
1630           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1631 
1632           // Since operand reordering is performed on groups of commutative
1633           // operations or alternating sequences (e.g., +, -), we can safely
1634           // tell the inverse operations by checking commutativity.
1635           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1636           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1637           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1638                                  APO, false};
1639         }
1640       }
1641     }
1642 
1643     /// \returns the number of operands.
1644     unsigned getNumOperands() const { return OpsVec.size(); }
1645 
1646     /// \returns the number of lanes.
1647     unsigned getNumLanes() const { return OpsVec[0].size(); }
1648 
1649     /// \returns the operand value at \p OpIdx and \p Lane.
1650     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1651       return getData(OpIdx, Lane).V;
1652     }
1653 
1654     /// \returns true if the data structure is empty.
1655     bool empty() const { return OpsVec.empty(); }
1656 
1657     /// Clears the data.
1658     void clear() { OpsVec.clear(); }
1659 
1660     /// \Returns true if there are enough operands identical to \p Op to fill
1661     /// the whole vector.
1662     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1663     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1664       bool OpAPO = getData(OpIdx, Lane).APO;
1665       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1666         if (Ln == Lane)
1667           continue;
1668         // This is set to true if we found a candidate for broadcast at Lane.
1669         bool FoundCandidate = false;
1670         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1671           OperandData &Data = getData(OpI, Ln);
1672           if (Data.APO != OpAPO || Data.IsUsed)
1673             continue;
1674           if (Data.V == Op) {
1675             FoundCandidate = true;
1676             Data.IsUsed = true;
1677             break;
1678           }
1679         }
1680         if (!FoundCandidate)
1681           return false;
1682       }
1683       return true;
1684     }
1685 
1686   public:
1687     /// Initialize with all the operands of the instruction vector \p RootVL.
1688     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1689                ScalarEvolution &SE, const BoUpSLP &R)
1690         : DL(DL), SE(SE), R(R) {
1691       // Append all the operands of RootVL.
1692       appendOperandsOfVL(RootVL);
1693     }
1694 
1695     /// \Returns a value vector with the operands across all lanes for the
1696     /// opearnd at \p OpIdx.
1697     ValueList getVL(unsigned OpIdx) const {
1698       ValueList OpVL(OpsVec[OpIdx].size());
1699       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1700              "Expected same num of lanes across all operands");
1701       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1702         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1703       return OpVL;
1704     }
1705 
1706     // Performs operand reordering for 2 or more operands.
1707     // The original operands are in OrigOps[OpIdx][Lane].
1708     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1709     void reorder() {
1710       unsigned NumOperands = getNumOperands();
1711       unsigned NumLanes = getNumLanes();
1712       // Each operand has its own mode. We are using this mode to help us select
1713       // the instructions for each lane, so that they match best with the ones
1714       // we have selected so far.
1715       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1716 
1717       // This is a greedy single-pass algorithm. We are going over each lane
1718       // once and deciding on the best order right away with no back-tracking.
1719       // However, in order to increase its effectiveness, we start with the lane
1720       // that has operands that can move the least. For example, given the
1721       // following lanes:
1722       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1723       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1724       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1725       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1726       // we will start at Lane 1, since the operands of the subtraction cannot
1727       // be reordered. Then we will visit the rest of the lanes in a circular
1728       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1729 
1730       // Find the first lane that we will start our search from.
1731       unsigned FirstLane = getBestLaneToStartReordering();
1732 
1733       // Initialize the modes.
1734       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1735         Value *OpLane0 = getValue(OpIdx, FirstLane);
1736         // Keep track if we have instructions with all the same opcode on one
1737         // side.
1738         if (isa<LoadInst>(OpLane0))
1739           ReorderingModes[OpIdx] = ReorderingMode::Load;
1740         else if (isa<Instruction>(OpLane0)) {
1741           // Check if OpLane0 should be broadcast.
1742           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1743             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1744           else
1745             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1746         }
1747         else if (isa<Constant>(OpLane0))
1748           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1749         else if (isa<Argument>(OpLane0))
1750           // Our best hope is a Splat. It may save some cost in some cases.
1751           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1752         else
1753           // NOTE: This should be unreachable.
1754           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1755       }
1756 
1757       // Check that we don't have same operands. No need to reorder if operands
1758       // are just perfect diamond or shuffled diamond match. Do not do it only
1759       // for possible broadcasts or non-power of 2 number of scalars (just for
1760       // now).
1761       auto &&SkipReordering = [this]() {
1762         SmallPtrSet<Value *, 4> UniqueValues;
1763         ArrayRef<OperandData> Op0 = OpsVec.front();
1764         for (const OperandData &Data : Op0)
1765           UniqueValues.insert(Data.V);
1766         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1767           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1768                 return !UniqueValues.contains(Data.V);
1769               }))
1770             return false;
1771         }
1772         // TODO: Check if we can remove a check for non-power-2 number of
1773         // scalars after full support of non-power-2 vectorization.
1774         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1775       };
1776 
1777       // If the initial strategy fails for any of the operand indexes, then we
1778       // perform reordering again in a second pass. This helps avoid assigning
1779       // high priority to the failed strategy, and should improve reordering for
1780       // the non-failed operand indexes.
1781       for (int Pass = 0; Pass != 2; ++Pass) {
1782         // Check if no need to reorder operands since they're are perfect or
1783         // shuffled diamond match.
1784         // Need to to do it to avoid extra external use cost counting for
1785         // shuffled matches, which may cause regressions.
1786         if (SkipReordering())
1787           break;
1788         // Skip the second pass if the first pass did not fail.
1789         bool StrategyFailed = false;
1790         // Mark all operand data as free to use.
1791         clearUsed();
1792         // We keep the original operand order for the FirstLane, so reorder the
1793         // rest of the lanes. We are visiting the nodes in a circular fashion,
1794         // using FirstLane as the center point and increasing the radius
1795         // distance.
1796         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1797         for (unsigned I = 0; I < NumOperands; ++I)
1798           MainAltOps[I].push_back(getData(I, FirstLane).V);
1799 
1800         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1801           // Visit the lane on the right and then the lane on the left.
1802           for (int Direction : {+1, -1}) {
1803             int Lane = FirstLane + Direction * Distance;
1804             if (Lane < 0 || Lane >= (int)NumLanes)
1805               continue;
1806             int LastLane = Lane - Direction;
1807             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1808                    "Out of bounds");
1809             // Look for a good match for each operand.
1810             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1811               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1812               Optional<unsigned> BestIdx = getBestOperand(
1813                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1814               // By not selecting a value, we allow the operands that follow to
1815               // select a better matching value. We will get a non-null value in
1816               // the next run of getBestOperand().
1817               if (BestIdx) {
1818                 // Swap the current operand with the one returned by
1819                 // getBestOperand().
1820                 swap(OpIdx, BestIdx.getValue(), Lane);
1821               } else {
1822                 // We failed to find a best operand, set mode to 'Failed'.
1823                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1824                 // Enable the second pass.
1825                 StrategyFailed = true;
1826               }
1827               // Try to get the alternate opcode and follow it during analysis.
1828               if (MainAltOps[OpIdx].size() != 2) {
1829                 OperandData &AltOp = getData(OpIdx, Lane);
1830                 InstructionsState OpS =
1831                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1832                 if (OpS.getOpcode() && OpS.isAltShuffle())
1833                   MainAltOps[OpIdx].push_back(AltOp.V);
1834               }
1835             }
1836           }
1837         }
1838         // Skip second pass if the strategy did not fail.
1839         if (!StrategyFailed)
1840           break;
1841       }
1842     }
1843 
1844 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1845     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1846       switch (RMode) {
1847       case ReorderingMode::Load:
1848         return "Load";
1849       case ReorderingMode::Opcode:
1850         return "Opcode";
1851       case ReorderingMode::Constant:
1852         return "Constant";
1853       case ReorderingMode::Splat:
1854         return "Splat";
1855       case ReorderingMode::Failed:
1856         return "Failed";
1857       }
1858       llvm_unreachable("Unimplemented Reordering Type");
1859     }
1860 
1861     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1862                                                    raw_ostream &OS) {
1863       return OS << getModeStr(RMode);
1864     }
1865 
1866     /// Debug print.
1867     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1868       printMode(RMode, dbgs());
1869     }
1870 
1871     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1872       return printMode(RMode, OS);
1873     }
1874 
1875     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1876       const unsigned Indent = 2;
1877       unsigned Cnt = 0;
1878       for (const OperandDataVec &OpDataVec : OpsVec) {
1879         OS << "Operand " << Cnt++ << "\n";
1880         for (const OperandData &OpData : OpDataVec) {
1881           OS.indent(Indent) << "{";
1882           if (Value *V = OpData.V)
1883             OS << *V;
1884           else
1885             OS << "null";
1886           OS << ", APO:" << OpData.APO << "}\n";
1887         }
1888         OS << "\n";
1889       }
1890       return OS;
1891     }
1892 
1893     /// Debug print.
1894     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1895 #endif
1896   };
1897 
1898   /// Checks if the instruction is marked for deletion.
1899   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1900 
1901   /// Marks values operands for later deletion by replacing them with Undefs.
1902   void eraseInstructions(ArrayRef<Value *> AV);
1903 
1904   ~BoUpSLP();
1905 
1906 private:
1907   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1908   /// reordering (i.e. the operands can be reordered because they have only one
1909   /// user and reordarable).
1910   /// \param NonVectorized List of all gather nodes that require reordering
1911   /// (e.g., gather of extractlements or partially vectorizable loads).
1912   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1913   /// reordering, subset of \p NonVectorized.
1914   bool
1915   canReorderOperands(TreeEntry *UserTE,
1916                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1917                      ArrayRef<TreeEntry *> ReorderableGathers,
1918                      SmallVectorImpl<TreeEntry *> &GatherOps);
1919 
1920   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1921   /// if any. If it is not vectorized (gather node), returns nullptr.
1922   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1923     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1924     TreeEntry *TE = nullptr;
1925     const auto *It = find_if(VL, [this, &TE](Value *V) {
1926       TE = getTreeEntry(V);
1927       return TE;
1928     });
1929     if (It != VL.end() && TE->isSame(VL))
1930       return TE;
1931     return nullptr;
1932   }
1933 
1934   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1935   /// if any. If it is not vectorized (gather node), returns nullptr.
1936   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
1937                                         unsigned OpIdx) const {
1938     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
1939         const_cast<TreeEntry *>(UserTE), OpIdx);
1940   }
1941 
1942   /// Checks if all users of \p I are the part of the vectorization tree.
1943   bool areAllUsersVectorized(Instruction *I,
1944                              ArrayRef<Value *> VectorizedVals) const;
1945 
1946   /// \returns the cost of the vectorizable entry.
1947   InstructionCost getEntryCost(const TreeEntry *E,
1948                                ArrayRef<Value *> VectorizedVals);
1949 
1950   /// This is the recursive part of buildTree.
1951   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1952                      const EdgeInfo &EI);
1953 
1954   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1955   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1956   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1957   /// returns false, setting \p CurrentOrder to either an empty vector or a
1958   /// non-identity permutation that allows to reuse extract instructions.
1959   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1960                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1961 
1962   /// Vectorize a single entry in the tree.
1963   Value *vectorizeTree(TreeEntry *E);
1964 
1965   /// Vectorize a single entry in the tree, starting in \p VL.
1966   Value *vectorizeTree(ArrayRef<Value *> VL);
1967 
1968   /// \returns the scalarization cost for this type. Scalarization in this
1969   /// context means the creation of vectors from a group of scalars. If \p
1970   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1971   /// vector elements.
1972   InstructionCost getGatherCost(FixedVectorType *Ty,
1973                                 const APInt &ShuffledIndices,
1974                                 bool NeedToShuffle) const;
1975 
1976   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1977   /// tree entries.
1978   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1979   /// previous tree entries. \p Mask is filled with the shuffle mask.
1980   Optional<TargetTransformInfo::ShuffleKind>
1981   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1982                         SmallVectorImpl<const TreeEntry *> &Entries);
1983 
1984   /// \returns the scalarization cost for this list of values. Assuming that
1985   /// this subtree gets vectorized, we may need to extract the values from the
1986   /// roots. This method calculates the cost of extracting the values.
1987   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1988 
1989   /// Set the Builder insert point to one after the last instruction in
1990   /// the bundle
1991   void setInsertPointAfterBundle(const TreeEntry *E);
1992 
1993   /// \returns a vector from a collection of scalars in \p VL.
1994   Value *gather(ArrayRef<Value *> VL);
1995 
1996   /// \returns whether the VectorizableTree is fully vectorizable and will
1997   /// be beneficial even the tree height is tiny.
1998   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1999 
2000   /// Reorder commutative or alt operands to get better probability of
2001   /// generating vectorized code.
2002   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2003                                              SmallVectorImpl<Value *> &Left,
2004                                              SmallVectorImpl<Value *> &Right,
2005                                              const DataLayout &DL,
2006                                              ScalarEvolution &SE,
2007                                              const BoUpSLP &R);
2008   struct TreeEntry {
2009     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2010     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2011 
2012     /// \returns true if the scalars in VL are equal to this entry.
2013     bool isSame(ArrayRef<Value *> VL) const {
2014       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2015         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2016           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2017         return VL.size() == Mask.size() &&
2018                std::equal(VL.begin(), VL.end(), Mask.begin(),
2019                           [Scalars](Value *V, int Idx) {
2020                             return (isa<UndefValue>(V) &&
2021                                     Idx == UndefMaskElem) ||
2022                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2023                           });
2024       };
2025       if (!ReorderIndices.empty()) {
2026         // TODO: implement matching if the nodes are just reordered, still can
2027         // treat the vector as the same if the list of scalars matches VL
2028         // directly, without reordering.
2029         SmallVector<int> Mask;
2030         inversePermutation(ReorderIndices, Mask);
2031         if (VL.size() == Scalars.size())
2032           return IsSame(Scalars, Mask);
2033         if (VL.size() == ReuseShuffleIndices.size()) {
2034           ::addMask(Mask, ReuseShuffleIndices);
2035           return IsSame(Scalars, Mask);
2036         }
2037         return false;
2038       }
2039       return IsSame(Scalars, ReuseShuffleIndices);
2040     }
2041 
2042     /// \returns true if current entry has same operands as \p TE.
2043     bool hasEqualOperands(const TreeEntry &TE) const {
2044       if (TE.getNumOperands() != getNumOperands())
2045         return false;
2046       SmallBitVector Used(getNumOperands());
2047       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2048         unsigned PrevCount = Used.count();
2049         for (unsigned K = 0; K < E; ++K) {
2050           if (Used.test(K))
2051             continue;
2052           if (getOperand(K) == TE.getOperand(I)) {
2053             Used.set(K);
2054             break;
2055           }
2056         }
2057         // Check if we actually found the matching operand.
2058         if (PrevCount == Used.count())
2059           return false;
2060       }
2061       return true;
2062     }
2063 
2064     /// \return Final vectorization factor for the node. Defined by the total
2065     /// number of vectorized scalars, including those, used several times in the
2066     /// entry and counted in the \a ReuseShuffleIndices, if any.
2067     unsigned getVectorFactor() const {
2068       if (!ReuseShuffleIndices.empty())
2069         return ReuseShuffleIndices.size();
2070       return Scalars.size();
2071     };
2072 
2073     /// A vector of scalars.
2074     ValueList Scalars;
2075 
2076     /// The Scalars are vectorized into this value. It is initialized to Null.
2077     Value *VectorizedValue = nullptr;
2078 
2079     /// Do we need to gather this sequence or vectorize it
2080     /// (either with vector instruction or with scatter/gather
2081     /// intrinsics for store/load)?
2082     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2083     EntryState State;
2084 
2085     /// Does this sequence require some shuffling?
2086     SmallVector<int, 4> ReuseShuffleIndices;
2087 
2088     /// Does this entry require reordering?
2089     SmallVector<unsigned, 4> ReorderIndices;
2090 
2091     /// Points back to the VectorizableTree.
2092     ///
2093     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2094     /// to be a pointer and needs to be able to initialize the child iterator.
2095     /// Thus we need a reference back to the container to translate the indices
2096     /// to entries.
2097     VecTreeTy &Container;
2098 
2099     /// The TreeEntry index containing the user of this entry.  We can actually
2100     /// have multiple users so the data structure is not truly a tree.
2101     SmallVector<EdgeInfo, 1> UserTreeIndices;
2102 
2103     /// The index of this treeEntry in VectorizableTree.
2104     int Idx = -1;
2105 
2106   private:
2107     /// The operands of each instruction in each lane Operands[op_index][lane].
2108     /// Note: This helps avoid the replication of the code that performs the
2109     /// reordering of operands during buildTree_rec() and vectorizeTree().
2110     SmallVector<ValueList, 2> Operands;
2111 
2112     /// The main/alternate instruction.
2113     Instruction *MainOp = nullptr;
2114     Instruction *AltOp = nullptr;
2115 
2116   public:
2117     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2118     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2119       if (Operands.size() < OpIdx + 1)
2120         Operands.resize(OpIdx + 1);
2121       assert(Operands[OpIdx].empty() && "Already resized?");
2122       assert(OpVL.size() <= Scalars.size() &&
2123              "Number of operands is greater than the number of scalars.");
2124       Operands[OpIdx].resize(OpVL.size());
2125       copy(OpVL, Operands[OpIdx].begin());
2126     }
2127 
2128     /// Set the operands of this bundle in their original order.
2129     void setOperandsInOrder() {
2130       assert(Operands.empty() && "Already initialized?");
2131       auto *I0 = cast<Instruction>(Scalars[0]);
2132       Operands.resize(I0->getNumOperands());
2133       unsigned NumLanes = Scalars.size();
2134       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2135            OpIdx != NumOperands; ++OpIdx) {
2136         Operands[OpIdx].resize(NumLanes);
2137         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2138           auto *I = cast<Instruction>(Scalars[Lane]);
2139           assert(I->getNumOperands() == NumOperands &&
2140                  "Expected same number of operands");
2141           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2142         }
2143       }
2144     }
2145 
2146     /// Reorders operands of the node to the given mask \p Mask.
2147     void reorderOperands(ArrayRef<int> Mask) {
2148       for (ValueList &Operand : Operands)
2149         reorderScalars(Operand, Mask);
2150     }
2151 
2152     /// \returns the \p OpIdx operand of this TreeEntry.
2153     ValueList &getOperand(unsigned OpIdx) {
2154       assert(OpIdx < Operands.size() && "Off bounds");
2155       return Operands[OpIdx];
2156     }
2157 
2158     /// \returns the \p OpIdx operand of this TreeEntry.
2159     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2160       assert(OpIdx < Operands.size() && "Off bounds");
2161       return Operands[OpIdx];
2162     }
2163 
2164     /// \returns the number of operands.
2165     unsigned getNumOperands() const { return Operands.size(); }
2166 
2167     /// \return the single \p OpIdx operand.
2168     Value *getSingleOperand(unsigned OpIdx) const {
2169       assert(OpIdx < Operands.size() && "Off bounds");
2170       assert(!Operands[OpIdx].empty() && "No operand available");
2171       return Operands[OpIdx][0];
2172     }
2173 
2174     /// Some of the instructions in the list have alternate opcodes.
2175     bool isAltShuffle() const { return MainOp != AltOp; }
2176 
2177     bool isOpcodeOrAlt(Instruction *I) const {
2178       unsigned CheckedOpcode = I->getOpcode();
2179       return (getOpcode() == CheckedOpcode ||
2180               getAltOpcode() == CheckedOpcode);
2181     }
2182 
2183     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2184     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2185     /// \p OpValue.
2186     Value *isOneOf(Value *Op) const {
2187       auto *I = dyn_cast<Instruction>(Op);
2188       if (I && isOpcodeOrAlt(I))
2189         return Op;
2190       return MainOp;
2191     }
2192 
2193     void setOperations(const InstructionsState &S) {
2194       MainOp = S.MainOp;
2195       AltOp = S.AltOp;
2196     }
2197 
2198     Instruction *getMainOp() const {
2199       return MainOp;
2200     }
2201 
2202     Instruction *getAltOp() const {
2203       return AltOp;
2204     }
2205 
2206     /// The main/alternate opcodes for the list of instructions.
2207     unsigned getOpcode() const {
2208       return MainOp ? MainOp->getOpcode() : 0;
2209     }
2210 
2211     unsigned getAltOpcode() const {
2212       return AltOp ? AltOp->getOpcode() : 0;
2213     }
2214 
2215     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2216     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2217     int findLaneForValue(Value *V) const {
2218       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2219       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2220       if (!ReorderIndices.empty())
2221         FoundLane = ReorderIndices[FoundLane];
2222       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2223       if (!ReuseShuffleIndices.empty()) {
2224         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2225                                   find(ReuseShuffleIndices, FoundLane));
2226       }
2227       return FoundLane;
2228     }
2229 
2230 #ifndef NDEBUG
2231     /// Debug printer.
2232     LLVM_DUMP_METHOD void dump() const {
2233       dbgs() << Idx << ".\n";
2234       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2235         dbgs() << "Operand " << OpI << ":\n";
2236         for (const Value *V : Operands[OpI])
2237           dbgs().indent(2) << *V << "\n";
2238       }
2239       dbgs() << "Scalars: \n";
2240       for (Value *V : Scalars)
2241         dbgs().indent(2) << *V << "\n";
2242       dbgs() << "State: ";
2243       switch (State) {
2244       case Vectorize:
2245         dbgs() << "Vectorize\n";
2246         break;
2247       case ScatterVectorize:
2248         dbgs() << "ScatterVectorize\n";
2249         break;
2250       case NeedToGather:
2251         dbgs() << "NeedToGather\n";
2252         break;
2253       }
2254       dbgs() << "MainOp: ";
2255       if (MainOp)
2256         dbgs() << *MainOp << "\n";
2257       else
2258         dbgs() << "NULL\n";
2259       dbgs() << "AltOp: ";
2260       if (AltOp)
2261         dbgs() << *AltOp << "\n";
2262       else
2263         dbgs() << "NULL\n";
2264       dbgs() << "VectorizedValue: ";
2265       if (VectorizedValue)
2266         dbgs() << *VectorizedValue << "\n";
2267       else
2268         dbgs() << "NULL\n";
2269       dbgs() << "ReuseShuffleIndices: ";
2270       if (ReuseShuffleIndices.empty())
2271         dbgs() << "Empty";
2272       else
2273         for (int ReuseIdx : ReuseShuffleIndices)
2274           dbgs() << ReuseIdx << ", ";
2275       dbgs() << "\n";
2276       dbgs() << "ReorderIndices: ";
2277       for (unsigned ReorderIdx : ReorderIndices)
2278         dbgs() << ReorderIdx << ", ";
2279       dbgs() << "\n";
2280       dbgs() << "UserTreeIndices: ";
2281       for (const auto &EInfo : UserTreeIndices)
2282         dbgs() << EInfo << ", ";
2283       dbgs() << "\n";
2284     }
2285 #endif
2286   };
2287 
2288 #ifndef NDEBUG
2289   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2290                      InstructionCost VecCost,
2291                      InstructionCost ScalarCost) const {
2292     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2293     dbgs() << "SLP: Costs:\n";
2294     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2295     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2296     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2297     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2298                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2299   }
2300 #endif
2301 
2302   /// Create a new VectorizableTree entry.
2303   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2304                           const InstructionsState &S,
2305                           const EdgeInfo &UserTreeIdx,
2306                           ArrayRef<int> ReuseShuffleIndices = None,
2307                           ArrayRef<unsigned> ReorderIndices = None) {
2308     TreeEntry::EntryState EntryState =
2309         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2310     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2311                         ReuseShuffleIndices, ReorderIndices);
2312   }
2313 
2314   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2315                           TreeEntry::EntryState EntryState,
2316                           Optional<ScheduleData *> Bundle,
2317                           const InstructionsState &S,
2318                           const EdgeInfo &UserTreeIdx,
2319                           ArrayRef<int> ReuseShuffleIndices = None,
2320                           ArrayRef<unsigned> ReorderIndices = None) {
2321     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2322             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2323            "Need to vectorize gather entry?");
2324     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2325     TreeEntry *Last = VectorizableTree.back().get();
2326     Last->Idx = VectorizableTree.size() - 1;
2327     Last->State = EntryState;
2328     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2329                                      ReuseShuffleIndices.end());
2330     if (ReorderIndices.empty()) {
2331       Last->Scalars.assign(VL.begin(), VL.end());
2332       Last->setOperations(S);
2333     } else {
2334       // Reorder scalars and build final mask.
2335       Last->Scalars.assign(VL.size(), nullptr);
2336       transform(ReorderIndices, Last->Scalars.begin(),
2337                 [VL](unsigned Idx) -> Value * {
2338                   if (Idx >= VL.size())
2339                     return UndefValue::get(VL.front()->getType());
2340                   return VL[Idx];
2341                 });
2342       InstructionsState S = getSameOpcode(Last->Scalars);
2343       Last->setOperations(S);
2344       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2345     }
2346     if (Last->State != TreeEntry::NeedToGather) {
2347       for (Value *V : VL) {
2348         assert(!getTreeEntry(V) && "Scalar already in tree!");
2349         ScalarToTreeEntry[V] = Last;
2350       }
2351       // Update the scheduler bundle to point to this TreeEntry.
2352       unsigned Lane = 0;
2353       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2354            BundleMember = BundleMember->NextInBundle) {
2355         BundleMember->TE = Last;
2356         BundleMember->Lane = Lane;
2357         ++Lane;
2358       }
2359       assert((!Bundle.getValue() || Lane == VL.size()) &&
2360              "Bundle and VL out of sync");
2361     } else {
2362       MustGather.insert(VL.begin(), VL.end());
2363     }
2364 
2365     if (UserTreeIdx.UserTE)
2366       Last->UserTreeIndices.push_back(UserTreeIdx);
2367 
2368     return Last;
2369   }
2370 
2371   /// -- Vectorization State --
2372   /// Holds all of the tree entries.
2373   TreeEntry::VecTreeTy VectorizableTree;
2374 
2375 #ifndef NDEBUG
2376   /// Debug printer.
2377   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2378     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2379       VectorizableTree[Id]->dump();
2380       dbgs() << "\n";
2381     }
2382   }
2383 #endif
2384 
2385   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2386 
2387   const TreeEntry *getTreeEntry(Value *V) const {
2388     return ScalarToTreeEntry.lookup(V);
2389   }
2390 
2391   /// Maps a specific scalar to its tree entry.
2392   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2393 
2394   /// Maps a value to the proposed vectorizable size.
2395   SmallDenseMap<Value *, unsigned> InstrElementSize;
2396 
2397   /// A list of scalars that we found that we need to keep as scalars.
2398   ValueSet MustGather;
2399 
2400   /// This POD struct describes one external user in the vectorized tree.
2401   struct ExternalUser {
2402     ExternalUser(Value *S, llvm::User *U, int L)
2403         : Scalar(S), User(U), Lane(L) {}
2404 
2405     // Which scalar in our function.
2406     Value *Scalar;
2407 
2408     // Which user that uses the scalar.
2409     llvm::User *User;
2410 
2411     // Which lane does the scalar belong to.
2412     int Lane;
2413   };
2414   using UserList = SmallVector<ExternalUser, 16>;
2415 
2416   /// Checks if two instructions may access the same memory.
2417   ///
2418   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2419   /// is invariant in the calling loop.
2420   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2421                  Instruction *Inst2) {
2422     // First check if the result is already in the cache.
2423     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2424     Optional<bool> &result = AliasCache[key];
2425     if (result.hasValue()) {
2426       return result.getValue();
2427     }
2428     bool aliased = true;
2429     if (Loc1.Ptr && isSimple(Inst1))
2430       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2431     // Store the result in the cache.
2432     result = aliased;
2433     return aliased;
2434   }
2435 
2436   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2437 
2438   /// Cache for alias results.
2439   /// TODO: consider moving this to the AliasAnalysis itself.
2440   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2441 
2442   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2443   // globally through SLP because we don't perform any action which
2444   // invalidates capture results.
2445   BatchAAResults BatchAA;
2446 
2447   /// Removes an instruction from its block and eventually deletes it.
2448   /// It's like Instruction::eraseFromParent() except that the actual deletion
2449   /// is delayed until BoUpSLP is destructed.
2450   /// This is required to ensure that there are no incorrect collisions in the
2451   /// AliasCache, which can happen if a new instruction is allocated at the
2452   /// same address as a previously deleted instruction.
2453   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2454     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2455     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2456   }
2457 
2458   /// Temporary store for deleted instructions. Instructions will be deleted
2459   /// eventually when the BoUpSLP is destructed.
2460   DenseMap<Instruction *, bool> DeletedInstructions;
2461 
2462   /// A list of values that need to extracted out of the tree.
2463   /// This list holds pairs of (Internal Scalar : External User). External User
2464   /// can be nullptr, it means that this Internal Scalar will be used later,
2465   /// after vectorization.
2466   UserList ExternalUses;
2467 
2468   /// Values used only by @llvm.assume calls.
2469   SmallPtrSet<const Value *, 32> EphValues;
2470 
2471   /// Holds all of the instructions that we gathered.
2472   SetVector<Instruction *> GatherShuffleSeq;
2473 
2474   /// A list of blocks that we are going to CSE.
2475   SetVector<BasicBlock *> CSEBlocks;
2476 
2477   /// Contains all scheduling relevant data for an instruction.
2478   /// A ScheduleData either represents a single instruction or a member of an
2479   /// instruction bundle (= a group of instructions which is combined into a
2480   /// vector instruction).
2481   struct ScheduleData {
2482     // The initial value for the dependency counters. It means that the
2483     // dependencies are not calculated yet.
2484     enum { InvalidDeps = -1 };
2485 
2486     ScheduleData() = default;
2487 
2488     void init(int BlockSchedulingRegionID, Value *OpVal) {
2489       FirstInBundle = this;
2490       NextInBundle = nullptr;
2491       NextLoadStore = nullptr;
2492       IsScheduled = false;
2493       SchedulingRegionID = BlockSchedulingRegionID;
2494       clearDependencies();
2495       OpValue = OpVal;
2496       TE = nullptr;
2497       Lane = -1;
2498     }
2499 
2500     /// Verify basic self consistency properties
2501     void verify() {
2502       if (hasValidDependencies()) {
2503         assert(UnscheduledDeps <= Dependencies && "invariant");
2504       } else {
2505         assert(UnscheduledDeps == Dependencies && "invariant");
2506       }
2507 
2508       if (IsScheduled) {
2509         assert(isSchedulingEntity() &&
2510                 "unexpected scheduled state");
2511         for (const ScheduleData *BundleMember = this; BundleMember;
2512              BundleMember = BundleMember->NextInBundle) {
2513           assert(BundleMember->hasValidDependencies() &&
2514                  BundleMember->UnscheduledDeps == 0 &&
2515                  "unexpected scheduled state");
2516           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2517                  "only bundle is marked scheduled");
2518         }
2519       }
2520     }
2521 
2522     /// Returns true if the dependency information has been calculated.
2523     /// Note that depenendency validity can vary between instructions within
2524     /// a single bundle.
2525     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2526 
2527     /// Returns true for single instructions and for bundle representatives
2528     /// (= the head of a bundle).
2529     bool isSchedulingEntity() const { return FirstInBundle == this; }
2530 
2531     /// Returns true if it represents an instruction bundle and not only a
2532     /// single instruction.
2533     bool isPartOfBundle() const {
2534       return NextInBundle != nullptr || FirstInBundle != this;
2535     }
2536 
2537     /// Returns true if it is ready for scheduling, i.e. it has no more
2538     /// unscheduled depending instructions/bundles.
2539     bool isReady() const {
2540       assert(isSchedulingEntity() &&
2541              "can't consider non-scheduling entity for ready list");
2542       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2543     }
2544 
2545     /// Modifies the number of unscheduled dependencies for this instruction,
2546     /// and returns the number of remaining dependencies for the containing
2547     /// bundle.
2548     int incrementUnscheduledDeps(int Incr) {
2549       assert(hasValidDependencies() &&
2550              "increment of unscheduled deps would be meaningless");
2551       UnscheduledDeps += Incr;
2552       return FirstInBundle->unscheduledDepsInBundle();
2553     }
2554 
2555     /// Sets the number of unscheduled dependencies to the number of
2556     /// dependencies.
2557     void resetUnscheduledDeps() {
2558       UnscheduledDeps = Dependencies;
2559     }
2560 
2561     /// Clears all dependency information.
2562     void clearDependencies() {
2563       Dependencies = InvalidDeps;
2564       resetUnscheduledDeps();
2565       MemoryDependencies.clear();
2566     }
2567 
2568     int unscheduledDepsInBundle() const {
2569       assert(isSchedulingEntity() && "only meaningful on the bundle");
2570       int Sum = 0;
2571       for (const ScheduleData *BundleMember = this; BundleMember;
2572            BundleMember = BundleMember->NextInBundle) {
2573         if (BundleMember->UnscheduledDeps == InvalidDeps)
2574           return InvalidDeps;
2575         Sum += BundleMember->UnscheduledDeps;
2576       }
2577       return Sum;
2578     }
2579 
2580     void dump(raw_ostream &os) const {
2581       if (!isSchedulingEntity()) {
2582         os << "/ " << *Inst;
2583       } else if (NextInBundle) {
2584         os << '[' << *Inst;
2585         ScheduleData *SD = NextInBundle;
2586         while (SD) {
2587           os << ';' << *SD->Inst;
2588           SD = SD->NextInBundle;
2589         }
2590         os << ']';
2591       } else {
2592         os << *Inst;
2593       }
2594     }
2595 
2596     Instruction *Inst = nullptr;
2597 
2598     /// Opcode of the current instruction in the schedule data.
2599     Value *OpValue = nullptr;
2600 
2601     /// The TreeEntry that this instruction corresponds to.
2602     TreeEntry *TE = nullptr;
2603 
2604     /// Points to the head in an instruction bundle (and always to this for
2605     /// single instructions).
2606     ScheduleData *FirstInBundle = nullptr;
2607 
2608     /// Single linked list of all instructions in a bundle. Null if it is a
2609     /// single instruction.
2610     ScheduleData *NextInBundle = nullptr;
2611 
2612     /// Single linked list of all memory instructions (e.g. load, store, call)
2613     /// in the block - until the end of the scheduling region.
2614     ScheduleData *NextLoadStore = nullptr;
2615 
2616     /// The dependent memory instructions.
2617     /// This list is derived on demand in calculateDependencies().
2618     SmallVector<ScheduleData *, 4> MemoryDependencies;
2619 
2620     /// This ScheduleData is in the current scheduling region if this matches
2621     /// the current SchedulingRegionID of BlockScheduling.
2622     int SchedulingRegionID = 0;
2623 
2624     /// The number of dependencies. Constitutes of the number of users of the
2625     /// instruction plus the number of dependent memory instructions (if any).
2626     /// This value is calculated on demand.
2627     /// If InvalidDeps, the number of dependencies is not calculated yet.
2628     int Dependencies = InvalidDeps;
2629 
2630     /// The number of dependencies minus the number of dependencies of scheduled
2631     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2632     /// for scheduling.
2633     /// Note that this is negative as long as Dependencies is not calculated.
2634     int UnscheduledDeps = InvalidDeps;
2635 
2636     /// The lane of this node in the TreeEntry.
2637     int Lane = -1;
2638 
2639     /// True if this instruction is scheduled (or considered as scheduled in the
2640     /// dry-run).
2641     bool IsScheduled = false;
2642   };
2643 
2644 #ifndef NDEBUG
2645   friend inline raw_ostream &operator<<(raw_ostream &os,
2646                                         const BoUpSLP::ScheduleData &SD) {
2647     SD.dump(os);
2648     return os;
2649   }
2650 #endif
2651 
2652   friend struct GraphTraits<BoUpSLP *>;
2653   friend struct DOTGraphTraits<BoUpSLP *>;
2654 
2655   /// Contains all scheduling data for a basic block.
2656   struct BlockScheduling {
2657     BlockScheduling(BasicBlock *BB)
2658         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2659 
2660     void clear() {
2661       ReadyInsts.clear();
2662       ScheduleStart = nullptr;
2663       ScheduleEnd = nullptr;
2664       FirstLoadStoreInRegion = nullptr;
2665       LastLoadStoreInRegion = nullptr;
2666 
2667       // Reduce the maximum schedule region size by the size of the
2668       // previous scheduling run.
2669       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2670       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2671         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2672       ScheduleRegionSize = 0;
2673 
2674       // Make a new scheduling region, i.e. all existing ScheduleData is not
2675       // in the new region yet.
2676       ++SchedulingRegionID;
2677     }
2678 
2679     ScheduleData *getScheduleData(Instruction *I) {
2680       if (BB != I->getParent())
2681         // Avoid lookup if can't possibly be in map.
2682         return nullptr;
2683       ScheduleData *SD = ScheduleDataMap[I];
2684       if (SD && isInSchedulingRegion(SD))
2685         return SD;
2686       return nullptr;
2687     }
2688 
2689     ScheduleData *getScheduleData(Value *V) {
2690       if (auto *I = dyn_cast<Instruction>(V))
2691         return getScheduleData(I);
2692       return nullptr;
2693     }
2694 
2695     ScheduleData *getScheduleData(Value *V, Value *Key) {
2696       if (V == Key)
2697         return getScheduleData(V);
2698       auto I = ExtraScheduleDataMap.find(V);
2699       if (I != ExtraScheduleDataMap.end()) {
2700         ScheduleData *SD = I->second[Key];
2701         if (SD && isInSchedulingRegion(SD))
2702           return SD;
2703       }
2704       return nullptr;
2705     }
2706 
2707     bool isInSchedulingRegion(ScheduleData *SD) const {
2708       return SD->SchedulingRegionID == SchedulingRegionID;
2709     }
2710 
2711     /// Marks an instruction as scheduled and puts all dependent ready
2712     /// instructions into the ready-list.
2713     template <typename ReadyListType>
2714     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2715       SD->IsScheduled = true;
2716       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2717 
2718       for (ScheduleData *BundleMember = SD; BundleMember;
2719            BundleMember = BundleMember->NextInBundle) {
2720         if (BundleMember->Inst != BundleMember->OpValue)
2721           continue;
2722 
2723         // Handle the def-use chain dependencies.
2724 
2725         // Decrement the unscheduled counter and insert to ready list if ready.
2726         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2727           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2728             if (OpDef && OpDef->hasValidDependencies() &&
2729                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2730               // There are no more unscheduled dependencies after
2731               // decrementing, so we can put the dependent instruction
2732               // into the ready list.
2733               ScheduleData *DepBundle = OpDef->FirstInBundle;
2734               assert(!DepBundle->IsScheduled &&
2735                      "already scheduled bundle gets ready");
2736               ReadyList.insert(DepBundle);
2737               LLVM_DEBUG(dbgs()
2738                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2739             }
2740           });
2741         };
2742 
2743         // If BundleMember is a vector bundle, its operands may have been
2744         // reordered during buildTree(). We therefore need to get its operands
2745         // through the TreeEntry.
2746         if (TreeEntry *TE = BundleMember->TE) {
2747           int Lane = BundleMember->Lane;
2748           assert(Lane >= 0 && "Lane not set");
2749 
2750           // Since vectorization tree is being built recursively this assertion
2751           // ensures that the tree entry has all operands set before reaching
2752           // this code. Couple of exceptions known at the moment are extracts
2753           // where their second (immediate) operand is not added. Since
2754           // immediates do not affect scheduler behavior this is considered
2755           // okay.
2756           auto *In = TE->getMainOp();
2757           assert(In &&
2758                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2759                   In->getNumOperands() == TE->getNumOperands()) &&
2760                  "Missed TreeEntry operands?");
2761           (void)In; // fake use to avoid build failure when assertions disabled
2762 
2763           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2764                OpIdx != NumOperands; ++OpIdx)
2765             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2766               DecrUnsched(I);
2767         } else {
2768           // If BundleMember is a stand-alone instruction, no operand reordering
2769           // has taken place, so we directly access its operands.
2770           for (Use &U : BundleMember->Inst->operands())
2771             if (auto *I = dyn_cast<Instruction>(U.get()))
2772               DecrUnsched(I);
2773         }
2774         // Handle the memory dependencies.
2775         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2776           if (MemoryDepSD->hasValidDependencies() &&
2777               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2778             // There are no more unscheduled dependencies after decrementing,
2779             // so we can put the dependent instruction into the ready list.
2780             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2781             assert(!DepBundle->IsScheduled &&
2782                    "already scheduled bundle gets ready");
2783             ReadyList.insert(DepBundle);
2784             LLVM_DEBUG(dbgs()
2785                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2786           }
2787         }
2788       }
2789     }
2790 
2791     /// Verify basic self consistency properties of the data structure.
2792     void verify() {
2793       if (!ScheduleStart)
2794         return;
2795 
2796       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2797              ScheduleStart->comesBefore(ScheduleEnd) &&
2798              "Not a valid scheduling region?");
2799 
2800       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2801         auto *SD = getScheduleData(I);
2802         assert(SD && "primary scheduledata must exist in window");
2803         assert(isInSchedulingRegion(SD) &&
2804                "primary schedule data not in window?");
2805         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2806                "entire bundle in window!");
2807         (void)SD;
2808         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2809       }
2810 
2811       for (auto *SD : ReadyInsts) {
2812         assert(SD->isSchedulingEntity() && SD->isReady() &&
2813                "item in ready list not ready?");
2814         (void)SD;
2815       }
2816     }
2817 
2818     void doForAllOpcodes(Value *V,
2819                          function_ref<void(ScheduleData *SD)> Action) {
2820       if (ScheduleData *SD = getScheduleData(V))
2821         Action(SD);
2822       auto I = ExtraScheduleDataMap.find(V);
2823       if (I != ExtraScheduleDataMap.end())
2824         for (auto &P : I->second)
2825           if (isInSchedulingRegion(P.second))
2826             Action(P.second);
2827     }
2828 
2829     /// Put all instructions into the ReadyList which are ready for scheduling.
2830     template <typename ReadyListType>
2831     void initialFillReadyList(ReadyListType &ReadyList) {
2832       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2833         doForAllOpcodes(I, [&](ScheduleData *SD) {
2834           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
2835               SD->isReady()) {
2836             ReadyList.insert(SD);
2837             LLVM_DEBUG(dbgs()
2838                        << "SLP:    initially in ready list: " << *SD << "\n");
2839           }
2840         });
2841       }
2842     }
2843 
2844     /// Build a bundle from the ScheduleData nodes corresponding to the
2845     /// scalar instruction for each lane.
2846     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2847 
2848     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2849     /// cyclic dependencies. This is only a dry-run, no instructions are
2850     /// actually moved at this stage.
2851     /// \returns the scheduling bundle. The returned Optional value is non-None
2852     /// if \p VL is allowed to be scheduled.
2853     Optional<ScheduleData *>
2854     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2855                       const InstructionsState &S);
2856 
2857     /// Un-bundles a group of instructions.
2858     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2859 
2860     /// Allocates schedule data chunk.
2861     ScheduleData *allocateScheduleDataChunks();
2862 
2863     /// Extends the scheduling region so that V is inside the region.
2864     /// \returns true if the region size is within the limit.
2865     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2866 
2867     /// Initialize the ScheduleData structures for new instructions in the
2868     /// scheduling region.
2869     void initScheduleData(Instruction *FromI, Instruction *ToI,
2870                           ScheduleData *PrevLoadStore,
2871                           ScheduleData *NextLoadStore);
2872 
2873     /// Updates the dependency information of a bundle and of all instructions/
2874     /// bundles which depend on the original bundle.
2875     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2876                                BoUpSLP *SLP);
2877 
2878     /// Sets all instruction in the scheduling region to un-scheduled.
2879     void resetSchedule();
2880 
2881     BasicBlock *BB;
2882 
2883     /// Simple memory allocation for ScheduleData.
2884     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2885 
2886     /// The size of a ScheduleData array in ScheduleDataChunks.
2887     int ChunkSize;
2888 
2889     /// The allocator position in the current chunk, which is the last entry
2890     /// of ScheduleDataChunks.
2891     int ChunkPos;
2892 
2893     /// Attaches ScheduleData to Instruction.
2894     /// Note that the mapping survives during all vectorization iterations, i.e.
2895     /// ScheduleData structures are recycled.
2896     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
2897 
2898     /// Attaches ScheduleData to Instruction with the leading key.
2899     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2900         ExtraScheduleDataMap;
2901 
2902     /// The ready-list for scheduling (only used for the dry-run).
2903     SetVector<ScheduleData *> ReadyInsts;
2904 
2905     /// The first instruction of the scheduling region.
2906     Instruction *ScheduleStart = nullptr;
2907 
2908     /// The first instruction _after_ the scheduling region.
2909     Instruction *ScheduleEnd = nullptr;
2910 
2911     /// The first memory accessing instruction in the scheduling region
2912     /// (can be null).
2913     ScheduleData *FirstLoadStoreInRegion = nullptr;
2914 
2915     /// The last memory accessing instruction in the scheduling region
2916     /// (can be null).
2917     ScheduleData *LastLoadStoreInRegion = nullptr;
2918 
2919     /// The current size of the scheduling region.
2920     int ScheduleRegionSize = 0;
2921 
2922     /// The maximum size allowed for the scheduling region.
2923     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2924 
2925     /// The ID of the scheduling region. For a new vectorization iteration this
2926     /// is incremented which "removes" all ScheduleData from the region.
2927     /// Make sure that the initial SchedulingRegionID is greater than the
2928     /// initial SchedulingRegionID in ScheduleData (which is 0).
2929     int SchedulingRegionID = 1;
2930   };
2931 
2932   /// Attaches the BlockScheduling structures to basic blocks.
2933   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2934 
2935   /// Performs the "real" scheduling. Done before vectorization is actually
2936   /// performed in a basic block.
2937   void scheduleBlock(BlockScheduling *BS);
2938 
2939   /// List of users to ignore during scheduling and that don't need extracting.
2940   ArrayRef<Value *> UserIgnoreList;
2941 
2942   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2943   /// sorted SmallVectors of unsigned.
2944   struct OrdersTypeDenseMapInfo {
2945     static OrdersType getEmptyKey() {
2946       OrdersType V;
2947       V.push_back(~1U);
2948       return V;
2949     }
2950 
2951     static OrdersType getTombstoneKey() {
2952       OrdersType V;
2953       V.push_back(~2U);
2954       return V;
2955     }
2956 
2957     static unsigned getHashValue(const OrdersType &V) {
2958       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2959     }
2960 
2961     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2962       return LHS == RHS;
2963     }
2964   };
2965 
2966   // Analysis and block reference.
2967   Function *F;
2968   ScalarEvolution *SE;
2969   TargetTransformInfo *TTI;
2970   TargetLibraryInfo *TLI;
2971   LoopInfo *LI;
2972   DominatorTree *DT;
2973   AssumptionCache *AC;
2974   DemandedBits *DB;
2975   const DataLayout *DL;
2976   OptimizationRemarkEmitter *ORE;
2977 
2978   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2979   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2980 
2981   /// Instruction builder to construct the vectorized tree.
2982   IRBuilder<> Builder;
2983 
2984   /// A map of scalar integer values to the smallest bit width with which they
2985   /// can legally be represented. The values map to (width, signed) pairs,
2986   /// where "width" indicates the minimum bit width and "signed" is True if the
2987   /// value must be signed-extended, rather than zero-extended, back to its
2988   /// original width.
2989   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2990 };
2991 
2992 } // end namespace slpvectorizer
2993 
2994 template <> struct GraphTraits<BoUpSLP *> {
2995   using TreeEntry = BoUpSLP::TreeEntry;
2996 
2997   /// NodeRef has to be a pointer per the GraphWriter.
2998   using NodeRef = TreeEntry *;
2999 
3000   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3001 
3002   /// Add the VectorizableTree to the index iterator to be able to return
3003   /// TreeEntry pointers.
3004   struct ChildIteratorType
3005       : public iterator_adaptor_base<
3006             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3007     ContainerTy &VectorizableTree;
3008 
3009     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3010                       ContainerTy &VT)
3011         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3012 
3013     NodeRef operator*() { return I->UserTE; }
3014   };
3015 
3016   static NodeRef getEntryNode(BoUpSLP &R) {
3017     return R.VectorizableTree[0].get();
3018   }
3019 
3020   static ChildIteratorType child_begin(NodeRef N) {
3021     return {N->UserTreeIndices.begin(), N->Container};
3022   }
3023 
3024   static ChildIteratorType child_end(NodeRef N) {
3025     return {N->UserTreeIndices.end(), N->Container};
3026   }
3027 
3028   /// For the node iterator we just need to turn the TreeEntry iterator into a
3029   /// TreeEntry* iterator so that it dereferences to NodeRef.
3030   class nodes_iterator {
3031     using ItTy = ContainerTy::iterator;
3032     ItTy It;
3033 
3034   public:
3035     nodes_iterator(const ItTy &It2) : It(It2) {}
3036     NodeRef operator*() { return It->get(); }
3037     nodes_iterator operator++() {
3038       ++It;
3039       return *this;
3040     }
3041     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3042   };
3043 
3044   static nodes_iterator nodes_begin(BoUpSLP *R) {
3045     return nodes_iterator(R->VectorizableTree.begin());
3046   }
3047 
3048   static nodes_iterator nodes_end(BoUpSLP *R) {
3049     return nodes_iterator(R->VectorizableTree.end());
3050   }
3051 
3052   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3053 };
3054 
3055 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3056   using TreeEntry = BoUpSLP::TreeEntry;
3057 
3058   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3059 
3060   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3061     std::string Str;
3062     raw_string_ostream OS(Str);
3063     if (isSplat(Entry->Scalars))
3064       OS << "<splat> ";
3065     for (auto V : Entry->Scalars) {
3066       OS << *V;
3067       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3068             return EU.Scalar == V;
3069           }))
3070         OS << " <extract>";
3071       OS << "\n";
3072     }
3073     return Str;
3074   }
3075 
3076   static std::string getNodeAttributes(const TreeEntry *Entry,
3077                                        const BoUpSLP *) {
3078     if (Entry->State == TreeEntry::NeedToGather)
3079       return "color=red";
3080     return "";
3081   }
3082 };
3083 
3084 } // end namespace llvm
3085 
3086 BoUpSLP::~BoUpSLP() {
3087   for (const auto &Pair : DeletedInstructions) {
3088     // Replace operands of ignored instructions with Undefs in case if they were
3089     // marked for deletion.
3090     if (Pair.getSecond()) {
3091       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3092       Pair.getFirst()->replaceAllUsesWith(Undef);
3093     }
3094     Pair.getFirst()->dropAllReferences();
3095   }
3096   for (const auto &Pair : DeletedInstructions) {
3097     assert(Pair.getFirst()->use_empty() &&
3098            "trying to erase instruction with users.");
3099     Pair.getFirst()->eraseFromParent();
3100   }
3101 #ifdef EXPENSIVE_CHECKS
3102   // If we could guarantee that this call is not extremely slow, we could
3103   // remove the ifdef limitation (see PR47712).
3104   assert(!verifyFunction(*F, &dbgs()));
3105 #endif
3106 }
3107 
3108 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3109   for (auto *V : AV) {
3110     if (auto *I = dyn_cast<Instruction>(V))
3111       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3112   };
3113 }
3114 
3115 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3116 /// contains original mask for the scalars reused in the node. Procedure
3117 /// transform this mask in accordance with the given \p Mask.
3118 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3119   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3120          "Expected non-empty mask.");
3121   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3122   Prev.swap(Reuses);
3123   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3124     if (Mask[I] != UndefMaskElem)
3125       Reuses[Mask[I]] = Prev[I];
3126 }
3127 
3128 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3129 /// the original order of the scalars. Procedure transforms the provided order
3130 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3131 /// identity order, \p Order is cleared.
3132 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3133   assert(!Mask.empty() && "Expected non-empty mask.");
3134   SmallVector<int> MaskOrder;
3135   if (Order.empty()) {
3136     MaskOrder.resize(Mask.size());
3137     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3138   } else {
3139     inversePermutation(Order, MaskOrder);
3140   }
3141   reorderReuses(MaskOrder, Mask);
3142   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3143     Order.clear();
3144     return;
3145   }
3146   Order.assign(Mask.size(), Mask.size());
3147   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3148     if (MaskOrder[I] != UndefMaskElem)
3149       Order[MaskOrder[I]] = I;
3150   fixupOrderingIndices(Order);
3151 }
3152 
3153 Optional<BoUpSLP::OrdersType>
3154 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3155   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3156   unsigned NumScalars = TE.Scalars.size();
3157   OrdersType CurrentOrder(NumScalars, NumScalars);
3158   SmallVector<int> Positions;
3159   SmallBitVector UsedPositions(NumScalars);
3160   const TreeEntry *STE = nullptr;
3161   // Try to find all gathered scalars that are gets vectorized in other
3162   // vectorize node. Here we can have only one single tree vector node to
3163   // correctly identify order of the gathered scalars.
3164   for (unsigned I = 0; I < NumScalars; ++I) {
3165     Value *V = TE.Scalars[I];
3166     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3167       continue;
3168     if (const auto *LocalSTE = getTreeEntry(V)) {
3169       if (!STE)
3170         STE = LocalSTE;
3171       else if (STE != LocalSTE)
3172         // Take the order only from the single vector node.
3173         return None;
3174       unsigned Lane =
3175           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3176       if (Lane >= NumScalars)
3177         return None;
3178       if (CurrentOrder[Lane] != NumScalars) {
3179         if (Lane != I)
3180           continue;
3181         UsedPositions.reset(CurrentOrder[Lane]);
3182       }
3183       // The partial identity (where only some elements of the gather node are
3184       // in the identity order) is good.
3185       CurrentOrder[Lane] = I;
3186       UsedPositions.set(I);
3187     }
3188   }
3189   // Need to keep the order if we have a vector entry and at least 2 scalars or
3190   // the vectorized entry has just 2 scalars.
3191   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3192     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3193       for (unsigned I = 0; I < NumScalars; ++I)
3194         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3195           return false;
3196       return true;
3197     };
3198     if (IsIdentityOrder(CurrentOrder)) {
3199       CurrentOrder.clear();
3200       return CurrentOrder;
3201     }
3202     auto *It = CurrentOrder.begin();
3203     for (unsigned I = 0; I < NumScalars;) {
3204       if (UsedPositions.test(I)) {
3205         ++I;
3206         continue;
3207       }
3208       if (*It == NumScalars) {
3209         *It = I;
3210         ++I;
3211       }
3212       ++It;
3213     }
3214     return CurrentOrder;
3215   }
3216   return None;
3217 }
3218 
3219 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3220                                                          bool TopToBottom) {
3221   // No need to reorder if need to shuffle reuses, still need to shuffle the
3222   // node.
3223   if (!TE.ReuseShuffleIndices.empty())
3224     return None;
3225   if (TE.State == TreeEntry::Vectorize &&
3226       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3227        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3228       !TE.isAltShuffle())
3229     return TE.ReorderIndices;
3230   if (TE.State == TreeEntry::NeedToGather) {
3231     // TODO: add analysis of other gather nodes with extractelement
3232     // instructions and other values/instructions, not only undefs.
3233     if (((TE.getOpcode() == Instruction::ExtractElement &&
3234           !TE.isAltShuffle()) ||
3235          (all_of(TE.Scalars,
3236                  [](Value *V) {
3237                    return isa<UndefValue, ExtractElementInst>(V);
3238                  }) &&
3239           any_of(TE.Scalars,
3240                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3241         all_of(TE.Scalars,
3242                [](Value *V) {
3243                  auto *EE = dyn_cast<ExtractElementInst>(V);
3244                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3245                }) &&
3246         allSameType(TE.Scalars)) {
3247       // Check that gather of extractelements can be represented as
3248       // just a shuffle of a single vector.
3249       OrdersType CurrentOrder;
3250       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3251       if (Reuse || !CurrentOrder.empty()) {
3252         if (!CurrentOrder.empty())
3253           fixupOrderingIndices(CurrentOrder);
3254         return CurrentOrder;
3255       }
3256     }
3257     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3258       return CurrentOrder;
3259   }
3260   return None;
3261 }
3262 
3263 void BoUpSLP::reorderTopToBottom() {
3264   // Maps VF to the graph nodes.
3265   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3266   // ExtractElement gather nodes which can be vectorized and need to handle
3267   // their ordering.
3268   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3269   // Find all reorderable nodes with the given VF.
3270   // Currently the are vectorized stores,loads,extracts + some gathering of
3271   // extracts.
3272   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3273                                  const std::unique_ptr<TreeEntry> &TE) {
3274     if (Optional<OrdersType> CurrentOrder =
3275             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3276       // Do not include ordering for nodes used in the alt opcode vectorization,
3277       // better to reorder them during bottom-to-top stage. If follow the order
3278       // here, it causes reordering of the whole graph though actually it is
3279       // profitable just to reorder the subgraph that starts from the alternate
3280       // opcode vectorization node. Such nodes already end-up with the shuffle
3281       // instruction and it is just enough to change this shuffle rather than
3282       // rotate the scalars for the whole graph.
3283       unsigned Cnt = 0;
3284       const TreeEntry *UserTE = TE.get();
3285       while (UserTE && Cnt < RecursionMaxDepth) {
3286         if (UserTE->UserTreeIndices.size() != 1)
3287           break;
3288         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3289               return EI.UserTE->State == TreeEntry::Vectorize &&
3290                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3291             }))
3292           return;
3293         if (UserTE->UserTreeIndices.empty())
3294           UserTE = nullptr;
3295         else
3296           UserTE = UserTE->UserTreeIndices.back().UserTE;
3297         ++Cnt;
3298       }
3299       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3300       if (TE->State != TreeEntry::Vectorize)
3301         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3302     }
3303   });
3304 
3305   // Reorder the graph nodes according to their vectorization factor.
3306   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3307        VF /= 2) {
3308     auto It = VFToOrderedEntries.find(VF);
3309     if (It == VFToOrderedEntries.end())
3310       continue;
3311     // Try to find the most profitable order. We just are looking for the most
3312     // used order and reorder scalar elements in the nodes according to this
3313     // mostly used order.
3314     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3315     // All operands are reordered and used only in this node - propagate the
3316     // most used order to the user node.
3317     MapVector<OrdersType, unsigned,
3318               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3319         OrdersUses;
3320     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3321     for (const TreeEntry *OpTE : OrderedEntries) {
3322       // No need to reorder this nodes, still need to extend and to use shuffle,
3323       // just need to merge reordering shuffle and the reuse shuffle.
3324       if (!OpTE->ReuseShuffleIndices.empty())
3325         continue;
3326       // Count number of orders uses.
3327       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3328         if (OpTE->State == TreeEntry::NeedToGather)
3329           return GathersToOrders.find(OpTE)->second;
3330         return OpTE->ReorderIndices;
3331       }();
3332       // Stores actually store the mask, not the order, need to invert.
3333       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3334           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3335         SmallVector<int> Mask;
3336         inversePermutation(Order, Mask);
3337         unsigned E = Order.size();
3338         OrdersType CurrentOrder(E, E);
3339         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3340           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3341         });
3342         fixupOrderingIndices(CurrentOrder);
3343         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3344       } else {
3345         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3346       }
3347     }
3348     // Set order of the user node.
3349     if (OrdersUses.empty())
3350       continue;
3351     // Choose the most used order.
3352     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3353     unsigned Cnt = OrdersUses.front().second;
3354     for (const auto &Pair : drop_begin(OrdersUses)) {
3355       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3356         BestOrder = Pair.first;
3357         Cnt = Pair.second;
3358       }
3359     }
3360     // Set order of the user node.
3361     if (BestOrder.empty())
3362       continue;
3363     SmallVector<int> Mask;
3364     inversePermutation(BestOrder, Mask);
3365     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3366     unsigned E = BestOrder.size();
3367     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3368       return I < E ? static_cast<int>(I) : UndefMaskElem;
3369     });
3370     // Do an actual reordering, if profitable.
3371     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3372       // Just do the reordering for the nodes with the given VF.
3373       if (TE->Scalars.size() != VF) {
3374         if (TE->ReuseShuffleIndices.size() == VF) {
3375           // Need to reorder the reuses masks of the operands with smaller VF to
3376           // be able to find the match between the graph nodes and scalar
3377           // operands of the given node during vectorization/cost estimation.
3378           assert(all_of(TE->UserTreeIndices,
3379                         [VF, &TE](const EdgeInfo &EI) {
3380                           return EI.UserTE->Scalars.size() == VF ||
3381                                  EI.UserTE->Scalars.size() ==
3382                                      TE->Scalars.size();
3383                         }) &&
3384                  "All users must be of VF size.");
3385           // Update ordering of the operands with the smaller VF than the given
3386           // one.
3387           reorderReuses(TE->ReuseShuffleIndices, Mask);
3388         }
3389         continue;
3390       }
3391       if (TE->State == TreeEntry::Vectorize &&
3392           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3393               InsertElementInst>(TE->getMainOp()) &&
3394           !TE->isAltShuffle()) {
3395         // Build correct orders for extract{element,value}, loads and
3396         // stores.
3397         reorderOrder(TE->ReorderIndices, Mask);
3398         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3399           TE->reorderOperands(Mask);
3400       } else {
3401         // Reorder the node and its operands.
3402         TE->reorderOperands(Mask);
3403         assert(TE->ReorderIndices.empty() &&
3404                "Expected empty reorder sequence.");
3405         reorderScalars(TE->Scalars, Mask);
3406       }
3407       if (!TE->ReuseShuffleIndices.empty()) {
3408         // Apply reversed order to keep the original ordering of the reused
3409         // elements to avoid extra reorder indices shuffling.
3410         OrdersType CurrentOrder;
3411         reorderOrder(CurrentOrder, MaskOrder);
3412         SmallVector<int> NewReuses;
3413         inversePermutation(CurrentOrder, NewReuses);
3414         addMask(NewReuses, TE->ReuseShuffleIndices);
3415         TE->ReuseShuffleIndices.swap(NewReuses);
3416       }
3417     }
3418   }
3419 }
3420 
3421 bool BoUpSLP::canReorderOperands(
3422     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3423     ArrayRef<TreeEntry *> ReorderableGathers,
3424     SmallVectorImpl<TreeEntry *> &GatherOps) {
3425   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3426     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3427           return OpData.first == I &&
3428                  OpData.second->State == TreeEntry::Vectorize;
3429         }))
3430       continue;
3431     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3432       // Do not reorder if operand node is used by many user nodes.
3433       if (any_of(TE->UserTreeIndices,
3434                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3435         return false;
3436       // Add the node to the list of the ordered nodes with the identity
3437       // order.
3438       Edges.emplace_back(I, TE);
3439       continue;
3440     }
3441     ArrayRef<Value *> VL = UserTE->getOperand(I);
3442     TreeEntry *Gather = nullptr;
3443     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3444           assert(TE->State != TreeEntry::Vectorize &&
3445                  "Only non-vectorized nodes are expected.");
3446           if (TE->isSame(VL)) {
3447             Gather = TE;
3448             return true;
3449           }
3450           return false;
3451         }) > 1)
3452       return false;
3453     if (Gather)
3454       GatherOps.push_back(Gather);
3455   }
3456   return true;
3457 }
3458 
3459 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3460   SetVector<TreeEntry *> OrderedEntries;
3461   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3462   // Find all reorderable leaf nodes with the given VF.
3463   // Currently the are vectorized loads,extracts without alternate operands +
3464   // some gathering of extracts.
3465   SmallVector<TreeEntry *> NonVectorized;
3466   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3467                               &NonVectorized](
3468                                  const std::unique_ptr<TreeEntry> &TE) {
3469     if (TE->State != TreeEntry::Vectorize)
3470       NonVectorized.push_back(TE.get());
3471     if (Optional<OrdersType> CurrentOrder =
3472             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3473       OrderedEntries.insert(TE.get());
3474       if (TE->State != TreeEntry::Vectorize)
3475         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3476     }
3477   });
3478 
3479   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3480   // I.e., if the node has operands, that are reordered, try to make at least
3481   // one operand order in the natural order and reorder others + reorder the
3482   // user node itself.
3483   SmallPtrSet<const TreeEntry *, 4> Visited;
3484   while (!OrderedEntries.empty()) {
3485     // 1. Filter out only reordered nodes.
3486     // 2. If the entry has multiple uses - skip it and jump to the next node.
3487     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3488     SmallVector<TreeEntry *> Filtered;
3489     for (TreeEntry *TE : OrderedEntries) {
3490       if (!(TE->State == TreeEntry::Vectorize ||
3491             (TE->State == TreeEntry::NeedToGather &&
3492              GathersToOrders.count(TE))) ||
3493           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3494           !all_of(drop_begin(TE->UserTreeIndices),
3495                   [TE](const EdgeInfo &EI) {
3496                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3497                   }) ||
3498           !Visited.insert(TE).second) {
3499         Filtered.push_back(TE);
3500         continue;
3501       }
3502       // Build a map between user nodes and their operands order to speedup
3503       // search. The graph currently does not provide this dependency directly.
3504       for (EdgeInfo &EI : TE->UserTreeIndices) {
3505         TreeEntry *UserTE = EI.UserTE;
3506         auto It = Users.find(UserTE);
3507         if (It == Users.end())
3508           It = Users.insert({UserTE, {}}).first;
3509         It->second.emplace_back(EI.EdgeIdx, TE);
3510       }
3511     }
3512     // Erase filtered entries.
3513     for_each(Filtered,
3514              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3515     for (auto &Data : Users) {
3516       // Check that operands are used only in the User node.
3517       SmallVector<TreeEntry *> GatherOps;
3518       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3519                               GatherOps)) {
3520         for_each(Data.second,
3521                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3522                    OrderedEntries.remove(Op.second);
3523                  });
3524         continue;
3525       }
3526       // All operands are reordered and used only in this node - propagate the
3527       // most used order to the user node.
3528       MapVector<OrdersType, unsigned,
3529                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3530           OrdersUses;
3531       // Do the analysis for each tree entry only once, otherwise the order of
3532       // the same node my be considered several times, though might be not
3533       // profitable.
3534       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3535       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3536       for (const auto &Op : Data.second) {
3537         TreeEntry *OpTE = Op.second;
3538         if (!VisitedOps.insert(OpTE).second)
3539           continue;
3540         if (!OpTE->ReuseShuffleIndices.empty() ||
3541             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3542           continue;
3543         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3544           if (OpTE->State == TreeEntry::NeedToGather)
3545             return GathersToOrders.find(OpTE)->second;
3546           return OpTE->ReorderIndices;
3547         }();
3548         unsigned NumOps = count_if(
3549             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3550               return P.second == OpTE;
3551             });
3552         // Stores actually store the mask, not the order, need to invert.
3553         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3554             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3555           SmallVector<int> Mask;
3556           inversePermutation(Order, Mask);
3557           unsigned E = Order.size();
3558           OrdersType CurrentOrder(E, E);
3559           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3560             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3561           });
3562           fixupOrderingIndices(CurrentOrder);
3563           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3564               NumOps;
3565         } else {
3566           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3567         }
3568         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3569         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3570                                             const TreeEntry *TE) {
3571           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3572               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3573               (IgnoreReorder && TE->Idx == 0))
3574             return true;
3575           if (TE->State == TreeEntry::NeedToGather) {
3576             auto It = GathersToOrders.find(TE);
3577             if (It != GathersToOrders.end())
3578               return !It->second.empty();
3579             return true;
3580           }
3581           return false;
3582         };
3583         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3584           TreeEntry *UserTE = EI.UserTE;
3585           if (!VisitedUsers.insert(UserTE).second)
3586             continue;
3587           // May reorder user node if it requires reordering, has reused
3588           // scalars, is an alternate op vectorize node or its op nodes require
3589           // reordering.
3590           if (AllowsReordering(UserTE))
3591             continue;
3592           // Check if users allow reordering.
3593           // Currently look up just 1 level of operands to avoid increase of
3594           // the compile time.
3595           // Profitable to reorder if definitely more operands allow
3596           // reordering rather than those with natural order.
3597           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3598           if (static_cast<unsigned>(count_if(
3599                   Ops, [UserTE, &AllowsReordering](
3600                            const std::pair<unsigned, TreeEntry *> &Op) {
3601                     return AllowsReordering(Op.second) &&
3602                            all_of(Op.second->UserTreeIndices,
3603                                   [UserTE](const EdgeInfo &EI) {
3604                                     return EI.UserTE == UserTE;
3605                                   });
3606                   })) <= Ops.size() / 2)
3607             ++Res.first->second;
3608         }
3609       }
3610       // If no orders - skip current nodes and jump to the next one, if any.
3611       if (OrdersUses.empty()) {
3612         for_each(Data.second,
3613                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3614                    OrderedEntries.remove(Op.second);
3615                  });
3616         continue;
3617       }
3618       // Choose the best order.
3619       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3620       unsigned Cnt = OrdersUses.front().second;
3621       for (const auto &Pair : drop_begin(OrdersUses)) {
3622         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3623           BestOrder = Pair.first;
3624           Cnt = Pair.second;
3625         }
3626       }
3627       // Set order of the user node (reordering of operands and user nodes).
3628       if (BestOrder.empty()) {
3629         for_each(Data.second,
3630                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3631                    OrderedEntries.remove(Op.second);
3632                  });
3633         continue;
3634       }
3635       // Erase operands from OrderedEntries list and adjust their orders.
3636       VisitedOps.clear();
3637       SmallVector<int> Mask;
3638       inversePermutation(BestOrder, Mask);
3639       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3640       unsigned E = BestOrder.size();
3641       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3642         return I < E ? static_cast<int>(I) : UndefMaskElem;
3643       });
3644       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3645         TreeEntry *TE = Op.second;
3646         OrderedEntries.remove(TE);
3647         if (!VisitedOps.insert(TE).second)
3648           continue;
3649         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3650           // Just reorder reuses indices.
3651           reorderReuses(TE->ReuseShuffleIndices, Mask);
3652           continue;
3653         }
3654         // Gathers are processed separately.
3655         if (TE->State != TreeEntry::Vectorize)
3656           continue;
3657         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3658                 TE->ReorderIndices.empty()) &&
3659                "Non-matching sizes of user/operand entries.");
3660         reorderOrder(TE->ReorderIndices, Mask);
3661       }
3662       // For gathers just need to reorder its scalars.
3663       for (TreeEntry *Gather : GatherOps) {
3664         assert(Gather->ReorderIndices.empty() &&
3665                "Unexpected reordering of gathers.");
3666         if (!Gather->ReuseShuffleIndices.empty()) {
3667           // Just reorder reuses indices.
3668           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3669           continue;
3670         }
3671         reorderScalars(Gather->Scalars, Mask);
3672         OrderedEntries.remove(Gather);
3673       }
3674       // Reorder operands of the user node and set the ordering for the user
3675       // node itself.
3676       if (Data.first->State != TreeEntry::Vectorize ||
3677           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3678               Data.first->getMainOp()) ||
3679           Data.first->isAltShuffle())
3680         Data.first->reorderOperands(Mask);
3681       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3682           Data.first->isAltShuffle()) {
3683         reorderScalars(Data.first->Scalars, Mask);
3684         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3685         if (Data.first->ReuseShuffleIndices.empty() &&
3686             !Data.first->ReorderIndices.empty() &&
3687             !Data.first->isAltShuffle()) {
3688           // Insert user node to the list to try to sink reordering deeper in
3689           // the graph.
3690           OrderedEntries.insert(Data.first);
3691         }
3692       } else {
3693         reorderOrder(Data.first->ReorderIndices, Mask);
3694       }
3695     }
3696   }
3697   // If the reordering is unnecessary, just remove the reorder.
3698   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3699       VectorizableTree.front()->ReuseShuffleIndices.empty())
3700     VectorizableTree.front()->ReorderIndices.clear();
3701 }
3702 
3703 void BoUpSLP::buildExternalUses(
3704     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3705   // Collect the values that we need to extract from the tree.
3706   for (auto &TEPtr : VectorizableTree) {
3707     TreeEntry *Entry = TEPtr.get();
3708 
3709     // No need to handle users of gathered values.
3710     if (Entry->State == TreeEntry::NeedToGather)
3711       continue;
3712 
3713     // For each lane:
3714     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3715       Value *Scalar = Entry->Scalars[Lane];
3716       int FoundLane = Entry->findLaneForValue(Scalar);
3717 
3718       // Check if the scalar is externally used as an extra arg.
3719       auto ExtI = ExternallyUsedValues.find(Scalar);
3720       if (ExtI != ExternallyUsedValues.end()) {
3721         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3722                           << Lane << " from " << *Scalar << ".\n");
3723         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3724       }
3725       for (User *U : Scalar->users()) {
3726         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3727 
3728         Instruction *UserInst = dyn_cast<Instruction>(U);
3729         if (!UserInst)
3730           continue;
3731 
3732         if (isDeleted(UserInst))
3733           continue;
3734 
3735         // Skip in-tree scalars that become vectors
3736         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3737           Value *UseScalar = UseEntry->Scalars[0];
3738           // Some in-tree scalars will remain as scalar in vectorized
3739           // instructions. If that is the case, the one in Lane 0 will
3740           // be used.
3741           if (UseScalar != U ||
3742               UseEntry->State == TreeEntry::ScatterVectorize ||
3743               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3744             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3745                               << ".\n");
3746             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3747             continue;
3748           }
3749         }
3750 
3751         // Ignore users in the user ignore list.
3752         if (is_contained(UserIgnoreList, UserInst))
3753           continue;
3754 
3755         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3756                           << Lane << " from " << *Scalar << ".\n");
3757         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3758       }
3759     }
3760   }
3761 }
3762 
3763 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3764                         ArrayRef<Value *> UserIgnoreLst) {
3765   deleteTree();
3766   UserIgnoreList = UserIgnoreLst;
3767   if (!allSameType(Roots))
3768     return;
3769   buildTree_rec(Roots, 0, EdgeInfo());
3770 }
3771 
3772 namespace {
3773 /// Tracks the state we can represent the loads in the given sequence.
3774 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3775 } // anonymous namespace
3776 
3777 /// Checks if the given array of loads can be represented as a vectorized,
3778 /// scatter or just simple gather.
3779 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3780                                     const TargetTransformInfo &TTI,
3781                                     const DataLayout &DL, ScalarEvolution &SE,
3782                                     SmallVectorImpl<unsigned> &Order,
3783                                     SmallVectorImpl<Value *> &PointerOps) {
3784   // Check that a vectorized load would load the same memory as a scalar
3785   // load. For example, we don't want to vectorize loads that are smaller
3786   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3787   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3788   // from such a struct, we read/write packed bits disagreeing with the
3789   // unvectorized version.
3790   Type *ScalarTy = VL0->getType();
3791 
3792   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3793     return LoadsState::Gather;
3794 
3795   // Make sure all loads in the bundle are simple - we can't vectorize
3796   // atomic or volatile loads.
3797   PointerOps.clear();
3798   PointerOps.resize(VL.size());
3799   auto *POIter = PointerOps.begin();
3800   for (Value *V : VL) {
3801     auto *L = cast<LoadInst>(V);
3802     if (!L->isSimple())
3803       return LoadsState::Gather;
3804     *POIter = L->getPointerOperand();
3805     ++POIter;
3806   }
3807 
3808   Order.clear();
3809   // Check the order of pointer operands.
3810   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3811     Value *Ptr0;
3812     Value *PtrN;
3813     if (Order.empty()) {
3814       Ptr0 = PointerOps.front();
3815       PtrN = PointerOps.back();
3816     } else {
3817       Ptr0 = PointerOps[Order.front()];
3818       PtrN = PointerOps[Order.back()];
3819     }
3820     Optional<int> Diff =
3821         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3822     // Check that the sorted loads are consecutive.
3823     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3824       return LoadsState::Vectorize;
3825     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3826     for (Value *V : VL)
3827       CommonAlignment =
3828           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3829     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3830                                 CommonAlignment))
3831       return LoadsState::ScatterVectorize;
3832   }
3833 
3834   return LoadsState::Gather;
3835 }
3836 
3837 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3838                             const EdgeInfo &UserTreeIdx) {
3839   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3840 
3841   SmallVector<int> ReuseShuffleIndicies;
3842   SmallVector<Value *> UniqueValues;
3843   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3844                                 &UserTreeIdx,
3845                                 this](const InstructionsState &S) {
3846     // Check that every instruction appears once in this bundle.
3847     DenseMap<Value *, unsigned> UniquePositions;
3848     for (Value *V : VL) {
3849       if (isConstant(V)) {
3850         ReuseShuffleIndicies.emplace_back(
3851             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3852         UniqueValues.emplace_back(V);
3853         continue;
3854       }
3855       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3856       ReuseShuffleIndicies.emplace_back(Res.first->second);
3857       if (Res.second)
3858         UniqueValues.emplace_back(V);
3859     }
3860     size_t NumUniqueScalarValues = UniqueValues.size();
3861     if (NumUniqueScalarValues == VL.size()) {
3862       ReuseShuffleIndicies.clear();
3863     } else {
3864       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3865       if (NumUniqueScalarValues <= 1 ||
3866           (UniquePositions.size() == 1 && all_of(UniqueValues,
3867                                                  [](Value *V) {
3868                                                    return isa<UndefValue>(V) ||
3869                                                           !isConstant(V);
3870                                                  })) ||
3871           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3872         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3873         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3874         return false;
3875       }
3876       VL = UniqueValues;
3877     }
3878     return true;
3879   };
3880 
3881   InstructionsState S = getSameOpcode(VL);
3882   if (Depth == RecursionMaxDepth) {
3883     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3884     if (TryToFindDuplicates(S))
3885       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3886                    ReuseShuffleIndicies);
3887     return;
3888   }
3889 
3890   // Don't handle scalable vectors
3891   if (S.getOpcode() == Instruction::ExtractElement &&
3892       isa<ScalableVectorType>(
3893           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3894     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3895     if (TryToFindDuplicates(S))
3896       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3897                    ReuseShuffleIndicies);
3898     return;
3899   }
3900 
3901   // Don't handle vectors.
3902   if (S.OpValue->getType()->isVectorTy() &&
3903       !isa<InsertElementInst>(S.OpValue)) {
3904     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3905     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3906     return;
3907   }
3908 
3909   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3910     if (SI->getValueOperand()->getType()->isVectorTy()) {
3911       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3912       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3913       return;
3914     }
3915 
3916   // If all of the operands are identical or constant we have a simple solution.
3917   // If we deal with insert/extract instructions, they all must have constant
3918   // indices, otherwise we should gather them, not try to vectorize.
3919   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3920       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3921        !all_of(VL, isVectorLikeInstWithConstOps))) {
3922     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3923     if (TryToFindDuplicates(S))
3924       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3925                    ReuseShuffleIndicies);
3926     return;
3927   }
3928 
3929   // We now know that this is a vector of instructions of the same type from
3930   // the same block.
3931 
3932   // Don't vectorize ephemeral values.
3933   for (Value *V : VL) {
3934     if (EphValues.count(V)) {
3935       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3936                         << ") is ephemeral.\n");
3937       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3938       return;
3939     }
3940   }
3941 
3942   // Check if this is a duplicate of another entry.
3943   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3944     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3945     if (!E->isSame(VL)) {
3946       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3947       if (TryToFindDuplicates(S))
3948         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3949                      ReuseShuffleIndicies);
3950       return;
3951     }
3952     // Record the reuse of the tree node.  FIXME, currently this is only used to
3953     // properly draw the graph rather than for the actual vectorization.
3954     E->UserTreeIndices.push_back(UserTreeIdx);
3955     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3956                       << ".\n");
3957     return;
3958   }
3959 
3960   // Check that none of the instructions in the bundle are already in the tree.
3961   for (Value *V : VL) {
3962     auto *I = dyn_cast<Instruction>(V);
3963     if (!I)
3964       continue;
3965     if (getTreeEntry(I)) {
3966       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3967                         << ") is already in tree.\n");
3968       if (TryToFindDuplicates(S))
3969         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3970                      ReuseShuffleIndicies);
3971       return;
3972     }
3973   }
3974 
3975   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3976   for (Value *V : VL) {
3977     if (is_contained(UserIgnoreList, V)) {
3978       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3979       if (TryToFindDuplicates(S))
3980         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3981                      ReuseShuffleIndicies);
3982       return;
3983     }
3984   }
3985 
3986   // Check that all of the users of the scalars that we want to vectorize are
3987   // schedulable.
3988   auto *VL0 = cast<Instruction>(S.OpValue);
3989   BasicBlock *BB = VL0->getParent();
3990 
3991   if (!DT->isReachableFromEntry(BB)) {
3992     // Don't go into unreachable blocks. They may contain instructions with
3993     // dependency cycles which confuse the final scheduling.
3994     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3995     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3996     return;
3997   }
3998 
3999   // Check that every instruction appears once in this bundle.
4000   if (!TryToFindDuplicates(S))
4001     return;
4002 
4003   auto &BSRef = BlocksSchedules[BB];
4004   if (!BSRef)
4005     BSRef = std::make_unique<BlockScheduling>(BB);
4006 
4007   BlockScheduling &BS = *BSRef.get();
4008 
4009   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4010 #ifdef EXPENSIVE_CHECKS
4011   // Make sure we didn't break any internal invariants
4012   BS.verify();
4013 #endif
4014   if (!Bundle) {
4015     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4016     assert((!BS.getScheduleData(VL0) ||
4017             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4018            "tryScheduleBundle should cancelScheduling on failure");
4019     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4020                  ReuseShuffleIndicies);
4021     return;
4022   }
4023   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4024 
4025   unsigned ShuffleOrOp = S.isAltShuffle() ?
4026                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4027   switch (ShuffleOrOp) {
4028     case Instruction::PHI: {
4029       auto *PH = cast<PHINode>(VL0);
4030 
4031       // Check for terminator values (e.g. invoke).
4032       for (Value *V : VL)
4033         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4034           Instruction *Term = dyn_cast<Instruction>(
4035               cast<PHINode>(V)->getIncomingValueForBlock(
4036                   PH->getIncomingBlock(I)));
4037           if (Term && Term->isTerminator()) {
4038             LLVM_DEBUG(dbgs()
4039                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4040             BS.cancelScheduling(VL, VL0);
4041             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4042                          ReuseShuffleIndicies);
4043             return;
4044           }
4045         }
4046 
4047       TreeEntry *TE =
4048           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4049       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4050 
4051       // Keeps the reordered operands to avoid code duplication.
4052       SmallVector<ValueList, 2> OperandsVec;
4053       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4054         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4055           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4056           TE->setOperand(I, Operands);
4057           OperandsVec.push_back(Operands);
4058           continue;
4059         }
4060         ValueList Operands;
4061         // Prepare the operand vector.
4062         for (Value *V : VL)
4063           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4064               PH->getIncomingBlock(I)));
4065         TE->setOperand(I, Operands);
4066         OperandsVec.push_back(Operands);
4067       }
4068       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4069         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4070       return;
4071     }
4072     case Instruction::ExtractValue:
4073     case Instruction::ExtractElement: {
4074       OrdersType CurrentOrder;
4075       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4076       if (Reuse) {
4077         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4078         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4079                      ReuseShuffleIndicies);
4080         // This is a special case, as it does not gather, but at the same time
4081         // we are not extending buildTree_rec() towards the operands.
4082         ValueList Op0;
4083         Op0.assign(VL.size(), VL0->getOperand(0));
4084         VectorizableTree.back()->setOperand(0, Op0);
4085         return;
4086       }
4087       if (!CurrentOrder.empty()) {
4088         LLVM_DEBUG({
4089           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4090                     "with order";
4091           for (unsigned Idx : CurrentOrder)
4092             dbgs() << " " << Idx;
4093           dbgs() << "\n";
4094         });
4095         fixupOrderingIndices(CurrentOrder);
4096         // Insert new order with initial value 0, if it does not exist,
4097         // otherwise return the iterator to the existing one.
4098         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4099                      ReuseShuffleIndicies, CurrentOrder);
4100         // This is a special case, as it does not gather, but at the same time
4101         // we are not extending buildTree_rec() towards the operands.
4102         ValueList Op0;
4103         Op0.assign(VL.size(), VL0->getOperand(0));
4104         VectorizableTree.back()->setOperand(0, Op0);
4105         return;
4106       }
4107       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4108       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4109                    ReuseShuffleIndicies);
4110       BS.cancelScheduling(VL, VL0);
4111       return;
4112     }
4113     case Instruction::InsertElement: {
4114       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4115 
4116       // Check that we have a buildvector and not a shuffle of 2 or more
4117       // different vectors.
4118       ValueSet SourceVectors;
4119       for (Value *V : VL) {
4120         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4121         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4122       }
4123 
4124       if (count_if(VL, [&SourceVectors](Value *V) {
4125             return !SourceVectors.contains(V);
4126           }) >= 2) {
4127         // Found 2nd source vector - cancel.
4128         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4129                              "different source vectors.\n");
4130         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4131         BS.cancelScheduling(VL, VL0);
4132         return;
4133       }
4134 
4135       auto OrdCompare = [](const std::pair<int, int> &P1,
4136                            const std::pair<int, int> &P2) {
4137         return P1.first > P2.first;
4138       };
4139       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4140                     decltype(OrdCompare)>
4141           Indices(OrdCompare);
4142       for (int I = 0, E = VL.size(); I < E; ++I) {
4143         unsigned Idx = *getInsertIndex(VL[I]);
4144         Indices.emplace(Idx, I);
4145       }
4146       OrdersType CurrentOrder(VL.size(), VL.size());
4147       bool IsIdentity = true;
4148       for (int I = 0, E = VL.size(); I < E; ++I) {
4149         CurrentOrder[Indices.top().second] = I;
4150         IsIdentity &= Indices.top().second == I;
4151         Indices.pop();
4152       }
4153       if (IsIdentity)
4154         CurrentOrder.clear();
4155       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4156                                    None, CurrentOrder);
4157       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4158 
4159       constexpr int NumOps = 2;
4160       ValueList VectorOperands[NumOps];
4161       for (int I = 0; I < NumOps; ++I) {
4162         for (Value *V : VL)
4163           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4164 
4165         TE->setOperand(I, VectorOperands[I]);
4166       }
4167       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4168       return;
4169     }
4170     case Instruction::Load: {
4171       // Check that a vectorized load would load the same memory as a scalar
4172       // load. For example, we don't want to vectorize loads that are smaller
4173       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4174       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4175       // from such a struct, we read/write packed bits disagreeing with the
4176       // unvectorized version.
4177       SmallVector<Value *> PointerOps;
4178       OrdersType CurrentOrder;
4179       TreeEntry *TE = nullptr;
4180       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4181                                 PointerOps)) {
4182       case LoadsState::Vectorize:
4183         if (CurrentOrder.empty()) {
4184           // Original loads are consecutive and does not require reordering.
4185           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4186                             ReuseShuffleIndicies);
4187           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4188         } else {
4189           fixupOrderingIndices(CurrentOrder);
4190           // Need to reorder.
4191           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4192                             ReuseShuffleIndicies, CurrentOrder);
4193           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4194         }
4195         TE->setOperandsInOrder();
4196         break;
4197       case LoadsState::ScatterVectorize:
4198         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4199         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4200                           UserTreeIdx, ReuseShuffleIndicies);
4201         TE->setOperandsInOrder();
4202         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4203         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4204         break;
4205       case LoadsState::Gather:
4206         BS.cancelScheduling(VL, VL0);
4207         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4208                      ReuseShuffleIndicies);
4209 #ifndef NDEBUG
4210         Type *ScalarTy = VL0->getType();
4211         if (DL->getTypeSizeInBits(ScalarTy) !=
4212             DL->getTypeAllocSizeInBits(ScalarTy))
4213           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4214         else if (any_of(VL, [](Value *V) {
4215                    return !cast<LoadInst>(V)->isSimple();
4216                  }))
4217           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4218         else
4219           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4220 #endif // NDEBUG
4221         break;
4222       }
4223       return;
4224     }
4225     case Instruction::ZExt:
4226     case Instruction::SExt:
4227     case Instruction::FPToUI:
4228     case Instruction::FPToSI:
4229     case Instruction::FPExt:
4230     case Instruction::PtrToInt:
4231     case Instruction::IntToPtr:
4232     case Instruction::SIToFP:
4233     case Instruction::UIToFP:
4234     case Instruction::Trunc:
4235     case Instruction::FPTrunc:
4236     case Instruction::BitCast: {
4237       Type *SrcTy = VL0->getOperand(0)->getType();
4238       for (Value *V : VL) {
4239         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4240         if (Ty != SrcTy || !isValidElementType(Ty)) {
4241           BS.cancelScheduling(VL, VL0);
4242           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4243                        ReuseShuffleIndicies);
4244           LLVM_DEBUG(dbgs()
4245                      << "SLP: Gathering casts with different src types.\n");
4246           return;
4247         }
4248       }
4249       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4250                                    ReuseShuffleIndicies);
4251       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4252 
4253       TE->setOperandsInOrder();
4254       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4255         ValueList Operands;
4256         // Prepare the operand vector.
4257         for (Value *V : VL)
4258           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4259 
4260         buildTree_rec(Operands, Depth + 1, {TE, i});
4261       }
4262       return;
4263     }
4264     case Instruction::ICmp:
4265     case Instruction::FCmp: {
4266       // Check that all of the compares have the same predicate.
4267       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4268       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4269       Type *ComparedTy = VL0->getOperand(0)->getType();
4270       for (Value *V : VL) {
4271         CmpInst *Cmp = cast<CmpInst>(V);
4272         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4273             Cmp->getOperand(0)->getType() != ComparedTy) {
4274           BS.cancelScheduling(VL, VL0);
4275           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4276                        ReuseShuffleIndicies);
4277           LLVM_DEBUG(dbgs()
4278                      << "SLP: Gathering cmp with different predicate.\n");
4279           return;
4280         }
4281       }
4282 
4283       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4284                                    ReuseShuffleIndicies);
4285       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4286 
4287       ValueList Left, Right;
4288       if (cast<CmpInst>(VL0)->isCommutative()) {
4289         // Commutative predicate - collect + sort operands of the instructions
4290         // so that each side is more likely to have the same opcode.
4291         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4292         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4293       } else {
4294         // Collect operands - commute if it uses the swapped predicate.
4295         for (Value *V : VL) {
4296           auto *Cmp = cast<CmpInst>(V);
4297           Value *LHS = Cmp->getOperand(0);
4298           Value *RHS = Cmp->getOperand(1);
4299           if (Cmp->getPredicate() != P0)
4300             std::swap(LHS, RHS);
4301           Left.push_back(LHS);
4302           Right.push_back(RHS);
4303         }
4304       }
4305       TE->setOperand(0, Left);
4306       TE->setOperand(1, Right);
4307       buildTree_rec(Left, Depth + 1, {TE, 0});
4308       buildTree_rec(Right, Depth + 1, {TE, 1});
4309       return;
4310     }
4311     case Instruction::Select:
4312     case Instruction::FNeg:
4313     case Instruction::Add:
4314     case Instruction::FAdd:
4315     case Instruction::Sub:
4316     case Instruction::FSub:
4317     case Instruction::Mul:
4318     case Instruction::FMul:
4319     case Instruction::UDiv:
4320     case Instruction::SDiv:
4321     case Instruction::FDiv:
4322     case Instruction::URem:
4323     case Instruction::SRem:
4324     case Instruction::FRem:
4325     case Instruction::Shl:
4326     case Instruction::LShr:
4327     case Instruction::AShr:
4328     case Instruction::And:
4329     case Instruction::Or:
4330     case Instruction::Xor: {
4331       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4332                                    ReuseShuffleIndicies);
4333       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4334 
4335       // Sort operands of the instructions so that each side is more likely to
4336       // have the same opcode.
4337       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4338         ValueList Left, Right;
4339         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4340         TE->setOperand(0, Left);
4341         TE->setOperand(1, Right);
4342         buildTree_rec(Left, Depth + 1, {TE, 0});
4343         buildTree_rec(Right, Depth + 1, {TE, 1});
4344         return;
4345       }
4346 
4347       TE->setOperandsInOrder();
4348       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4349         ValueList Operands;
4350         // Prepare the operand vector.
4351         for (Value *V : VL)
4352           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4353 
4354         buildTree_rec(Operands, Depth + 1, {TE, i});
4355       }
4356       return;
4357     }
4358     case Instruction::GetElementPtr: {
4359       // We don't combine GEPs with complicated (nested) indexing.
4360       for (Value *V : VL) {
4361         if (cast<Instruction>(V)->getNumOperands() != 2) {
4362           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4363           BS.cancelScheduling(VL, VL0);
4364           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4365                        ReuseShuffleIndicies);
4366           return;
4367         }
4368       }
4369 
4370       // We can't combine several GEPs into one vector if they operate on
4371       // different types.
4372       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4373       for (Value *V : VL) {
4374         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4375         if (Ty0 != CurTy) {
4376           LLVM_DEBUG(dbgs()
4377                      << "SLP: not-vectorizable GEP (different types).\n");
4378           BS.cancelScheduling(VL, VL0);
4379           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4380                        ReuseShuffleIndicies);
4381           return;
4382         }
4383       }
4384 
4385       // We don't combine GEPs with non-constant indexes.
4386       Type *Ty1 = VL0->getOperand(1)->getType();
4387       for (Value *V : VL) {
4388         auto Op = cast<Instruction>(V)->getOperand(1);
4389         if (!isa<ConstantInt>(Op) ||
4390             (Op->getType() != Ty1 &&
4391              Op->getType()->getScalarSizeInBits() >
4392                  DL->getIndexSizeInBits(
4393                      V->getType()->getPointerAddressSpace()))) {
4394           LLVM_DEBUG(dbgs()
4395                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4396           BS.cancelScheduling(VL, VL0);
4397           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4398                        ReuseShuffleIndicies);
4399           return;
4400         }
4401       }
4402 
4403       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4404                                    ReuseShuffleIndicies);
4405       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4406       SmallVector<ValueList, 2> Operands(2);
4407       // Prepare the operand vector for pointer operands.
4408       for (Value *V : VL)
4409         Operands.front().push_back(
4410             cast<GetElementPtrInst>(V)->getPointerOperand());
4411       TE->setOperand(0, Operands.front());
4412       // Need to cast all indices to the same type before vectorization to
4413       // avoid crash.
4414       // Required to be able to find correct matches between different gather
4415       // nodes and reuse the vectorized values rather than trying to gather them
4416       // again.
4417       int IndexIdx = 1;
4418       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4419       Type *Ty = all_of(VL,
4420                         [VL0Ty, IndexIdx](Value *V) {
4421                           return VL0Ty == cast<GetElementPtrInst>(V)
4422                                               ->getOperand(IndexIdx)
4423                                               ->getType();
4424                         })
4425                      ? VL0Ty
4426                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4427                                             ->getPointerOperandType()
4428                                             ->getScalarType());
4429       // Prepare the operand vector.
4430       for (Value *V : VL) {
4431         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4432         auto *CI = cast<ConstantInt>(Op);
4433         Operands.back().push_back(ConstantExpr::getIntegerCast(
4434             CI, Ty, CI->getValue().isSignBitSet()));
4435       }
4436       TE->setOperand(IndexIdx, Operands.back());
4437 
4438       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4439         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4440       return;
4441     }
4442     case Instruction::Store: {
4443       // Check if the stores are consecutive or if we need to swizzle them.
4444       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4445       // Avoid types that are padded when being allocated as scalars, while
4446       // being packed together in a vector (such as i1).
4447       if (DL->getTypeSizeInBits(ScalarTy) !=
4448           DL->getTypeAllocSizeInBits(ScalarTy)) {
4449         BS.cancelScheduling(VL, VL0);
4450         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4451                      ReuseShuffleIndicies);
4452         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4453         return;
4454       }
4455       // Make sure all stores in the bundle are simple - we can't vectorize
4456       // atomic or volatile stores.
4457       SmallVector<Value *, 4> PointerOps(VL.size());
4458       ValueList Operands(VL.size());
4459       auto POIter = PointerOps.begin();
4460       auto OIter = Operands.begin();
4461       for (Value *V : VL) {
4462         auto *SI = cast<StoreInst>(V);
4463         if (!SI->isSimple()) {
4464           BS.cancelScheduling(VL, VL0);
4465           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4466                        ReuseShuffleIndicies);
4467           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4468           return;
4469         }
4470         *POIter = SI->getPointerOperand();
4471         *OIter = SI->getValueOperand();
4472         ++POIter;
4473         ++OIter;
4474       }
4475 
4476       OrdersType CurrentOrder;
4477       // Check the order of pointer operands.
4478       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4479         Value *Ptr0;
4480         Value *PtrN;
4481         if (CurrentOrder.empty()) {
4482           Ptr0 = PointerOps.front();
4483           PtrN = PointerOps.back();
4484         } else {
4485           Ptr0 = PointerOps[CurrentOrder.front()];
4486           PtrN = PointerOps[CurrentOrder.back()];
4487         }
4488         Optional<int> Dist =
4489             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4490         // Check that the sorted pointer operands are consecutive.
4491         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4492           if (CurrentOrder.empty()) {
4493             // Original stores are consecutive and does not require reordering.
4494             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4495                                          UserTreeIdx, ReuseShuffleIndicies);
4496             TE->setOperandsInOrder();
4497             buildTree_rec(Operands, Depth + 1, {TE, 0});
4498             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4499           } else {
4500             fixupOrderingIndices(CurrentOrder);
4501             TreeEntry *TE =
4502                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4503                              ReuseShuffleIndicies, CurrentOrder);
4504             TE->setOperandsInOrder();
4505             buildTree_rec(Operands, Depth + 1, {TE, 0});
4506             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4507           }
4508           return;
4509         }
4510       }
4511 
4512       BS.cancelScheduling(VL, VL0);
4513       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4514                    ReuseShuffleIndicies);
4515       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4516       return;
4517     }
4518     case Instruction::Call: {
4519       // Check if the calls are all to the same vectorizable intrinsic or
4520       // library function.
4521       CallInst *CI = cast<CallInst>(VL0);
4522       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4523 
4524       VFShape Shape = VFShape::get(
4525           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4526           false /*HasGlobalPred*/);
4527       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4528 
4529       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4530         BS.cancelScheduling(VL, VL0);
4531         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4532                      ReuseShuffleIndicies);
4533         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4534         return;
4535       }
4536       Function *F = CI->getCalledFunction();
4537       unsigned NumArgs = CI->arg_size();
4538       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4539       for (unsigned j = 0; j != NumArgs; ++j)
4540         if (hasVectorInstrinsicScalarOpd(ID, j))
4541           ScalarArgs[j] = CI->getArgOperand(j);
4542       for (Value *V : VL) {
4543         CallInst *CI2 = dyn_cast<CallInst>(V);
4544         if (!CI2 || CI2->getCalledFunction() != F ||
4545             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4546             (VecFunc &&
4547              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4548             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4549           BS.cancelScheduling(VL, VL0);
4550           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4551                        ReuseShuffleIndicies);
4552           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4553                             << "\n");
4554           return;
4555         }
4556         // Some intrinsics have scalar arguments and should be same in order for
4557         // them to be vectorized.
4558         for (unsigned j = 0; j != NumArgs; ++j) {
4559           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4560             Value *A1J = CI2->getArgOperand(j);
4561             if (ScalarArgs[j] != A1J) {
4562               BS.cancelScheduling(VL, VL0);
4563               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4564                            ReuseShuffleIndicies);
4565               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4566                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4567                                 << "\n");
4568               return;
4569             }
4570           }
4571         }
4572         // Verify that the bundle operands are identical between the two calls.
4573         if (CI->hasOperandBundles() &&
4574             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4575                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4576                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4577           BS.cancelScheduling(VL, VL0);
4578           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4579                        ReuseShuffleIndicies);
4580           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4581                             << *CI << "!=" << *V << '\n');
4582           return;
4583         }
4584       }
4585 
4586       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4587                                    ReuseShuffleIndicies);
4588       TE->setOperandsInOrder();
4589       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4590         // For scalar operands no need to to create an entry since no need to
4591         // vectorize it.
4592         if (hasVectorInstrinsicScalarOpd(ID, i))
4593           continue;
4594         ValueList Operands;
4595         // Prepare the operand vector.
4596         for (Value *V : VL) {
4597           auto *CI2 = cast<CallInst>(V);
4598           Operands.push_back(CI2->getArgOperand(i));
4599         }
4600         buildTree_rec(Operands, Depth + 1, {TE, i});
4601       }
4602       return;
4603     }
4604     case Instruction::ShuffleVector: {
4605       // If this is not an alternate sequence of opcode like add-sub
4606       // then do not vectorize this instruction.
4607       if (!S.isAltShuffle()) {
4608         BS.cancelScheduling(VL, VL0);
4609         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4610                      ReuseShuffleIndicies);
4611         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4612         return;
4613       }
4614       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4615                                    ReuseShuffleIndicies);
4616       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4617 
4618       // Reorder operands if reordering would enable vectorization.
4619       auto *CI = dyn_cast<CmpInst>(VL0);
4620       if (isa<BinaryOperator>(VL0) || CI) {
4621         ValueList Left, Right;
4622         if (!CI || all_of(VL, [](Value *V) {
4623               return cast<CmpInst>(V)->isCommutative();
4624             })) {
4625           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4626         } else {
4627           CmpInst::Predicate P0 = CI->getPredicate();
4628           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4629           assert(P0 != AltP0 &&
4630                  "Expected different main/alternate predicates.");
4631           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4632           Value *BaseOp0 = VL0->getOperand(0);
4633           Value *BaseOp1 = VL0->getOperand(1);
4634           // Collect operands - commute if it uses the swapped predicate or
4635           // alternate operation.
4636           for (Value *V : VL) {
4637             auto *Cmp = cast<CmpInst>(V);
4638             Value *LHS = Cmp->getOperand(0);
4639             Value *RHS = Cmp->getOperand(1);
4640             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4641             if (P0 == AltP0Swapped) {
4642               if (CI != Cmp && S.AltOp != Cmp &&
4643                   ((P0 == CurrentPred &&
4644                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4645                    (AltP0 == CurrentPred &&
4646                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4647                 std::swap(LHS, RHS);
4648             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4649               std::swap(LHS, RHS);
4650             }
4651             Left.push_back(LHS);
4652             Right.push_back(RHS);
4653           }
4654         }
4655         TE->setOperand(0, Left);
4656         TE->setOperand(1, Right);
4657         buildTree_rec(Left, Depth + 1, {TE, 0});
4658         buildTree_rec(Right, Depth + 1, {TE, 1});
4659         return;
4660       }
4661 
4662       TE->setOperandsInOrder();
4663       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4664         ValueList Operands;
4665         // Prepare the operand vector.
4666         for (Value *V : VL)
4667           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4668 
4669         buildTree_rec(Operands, Depth + 1, {TE, i});
4670       }
4671       return;
4672     }
4673     default:
4674       BS.cancelScheduling(VL, VL0);
4675       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4676                    ReuseShuffleIndicies);
4677       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4678       return;
4679   }
4680 }
4681 
4682 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4683   unsigned N = 1;
4684   Type *EltTy = T;
4685 
4686   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4687          isa<VectorType>(EltTy)) {
4688     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4689       // Check that struct is homogeneous.
4690       for (const auto *Ty : ST->elements())
4691         if (Ty != *ST->element_begin())
4692           return 0;
4693       N *= ST->getNumElements();
4694       EltTy = *ST->element_begin();
4695     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4696       N *= AT->getNumElements();
4697       EltTy = AT->getElementType();
4698     } else {
4699       auto *VT = cast<FixedVectorType>(EltTy);
4700       N *= VT->getNumElements();
4701       EltTy = VT->getElementType();
4702     }
4703   }
4704 
4705   if (!isValidElementType(EltTy))
4706     return 0;
4707   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4708   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4709     return 0;
4710   return N;
4711 }
4712 
4713 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4714                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4715   const auto *It = find_if(VL, [](Value *V) {
4716     return isa<ExtractElementInst, ExtractValueInst>(V);
4717   });
4718   assert(It != VL.end() && "Expected at least one extract instruction.");
4719   auto *E0 = cast<Instruction>(*It);
4720   assert(all_of(VL,
4721                 [](Value *V) {
4722                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4723                       V);
4724                 }) &&
4725          "Invalid opcode");
4726   // Check if all of the extracts come from the same vector and from the
4727   // correct offset.
4728   Value *Vec = E0->getOperand(0);
4729 
4730   CurrentOrder.clear();
4731 
4732   // We have to extract from a vector/aggregate with the same number of elements.
4733   unsigned NElts;
4734   if (E0->getOpcode() == Instruction::ExtractValue) {
4735     const DataLayout &DL = E0->getModule()->getDataLayout();
4736     NElts = canMapToVector(Vec->getType(), DL);
4737     if (!NElts)
4738       return false;
4739     // Check if load can be rewritten as load of vector.
4740     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4741     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4742       return false;
4743   } else {
4744     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4745   }
4746 
4747   if (NElts != VL.size())
4748     return false;
4749 
4750   // Check that all of the indices extract from the correct offset.
4751   bool ShouldKeepOrder = true;
4752   unsigned E = VL.size();
4753   // Assign to all items the initial value E + 1 so we can check if the extract
4754   // instruction index was used already.
4755   // Also, later we can check that all the indices are used and we have a
4756   // consecutive access in the extract instructions, by checking that no
4757   // element of CurrentOrder still has value E + 1.
4758   CurrentOrder.assign(E, E);
4759   unsigned I = 0;
4760   for (; I < E; ++I) {
4761     auto *Inst = dyn_cast<Instruction>(VL[I]);
4762     if (!Inst)
4763       continue;
4764     if (Inst->getOperand(0) != Vec)
4765       break;
4766     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4767       if (isa<UndefValue>(EE->getIndexOperand()))
4768         continue;
4769     Optional<unsigned> Idx = getExtractIndex(Inst);
4770     if (!Idx)
4771       break;
4772     const unsigned ExtIdx = *Idx;
4773     if (ExtIdx != I) {
4774       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4775         break;
4776       ShouldKeepOrder = false;
4777       CurrentOrder[ExtIdx] = I;
4778     } else {
4779       if (CurrentOrder[I] != E)
4780         break;
4781       CurrentOrder[I] = I;
4782     }
4783   }
4784   if (I < E) {
4785     CurrentOrder.clear();
4786     return false;
4787   }
4788   if (ShouldKeepOrder)
4789     CurrentOrder.clear();
4790 
4791   return ShouldKeepOrder;
4792 }
4793 
4794 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4795                                     ArrayRef<Value *> VectorizedVals) const {
4796   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4797          all_of(I->users(), [this](User *U) {
4798            return ScalarToTreeEntry.count(U) > 0 ||
4799                   isVectorLikeInstWithConstOps(U) ||
4800                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4801          });
4802 }
4803 
4804 static std::pair<InstructionCost, InstructionCost>
4805 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4806                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4807   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4808 
4809   // Calculate the cost of the scalar and vector calls.
4810   SmallVector<Type *, 4> VecTys;
4811   for (Use &Arg : CI->args())
4812     VecTys.push_back(
4813         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4814   FastMathFlags FMF;
4815   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4816     FMF = FPCI->getFastMathFlags();
4817   SmallVector<const Value *> Arguments(CI->args());
4818   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4819                                     dyn_cast<IntrinsicInst>(CI));
4820   auto IntrinsicCost =
4821     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4822 
4823   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4824                                      VecTy->getNumElements())),
4825                             false /*HasGlobalPred*/);
4826   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4827   auto LibCost = IntrinsicCost;
4828   if (!CI->isNoBuiltin() && VecFunc) {
4829     // Calculate the cost of the vector library call.
4830     // If the corresponding vector call is cheaper, return its cost.
4831     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4832                                     TTI::TCK_RecipThroughput);
4833   }
4834   return {IntrinsicCost, LibCost};
4835 }
4836 
4837 /// Compute the cost of creating a vector of type \p VecTy containing the
4838 /// extracted values from \p VL.
4839 static InstructionCost
4840 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4841                    TargetTransformInfo::ShuffleKind ShuffleKind,
4842                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4843   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4844 
4845   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4846       VecTy->getNumElements() < NumOfParts)
4847     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4848 
4849   bool AllConsecutive = true;
4850   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4851   unsigned Idx = -1;
4852   InstructionCost Cost = 0;
4853 
4854   // Process extracts in blocks of EltsPerVector to check if the source vector
4855   // operand can be re-used directly. If not, add the cost of creating a shuffle
4856   // to extract the values into a vector register.
4857   for (auto *V : VL) {
4858     ++Idx;
4859 
4860     // Need to exclude undefs from analysis.
4861     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4862       continue;
4863 
4864     // Reached the start of a new vector registers.
4865     if (Idx % EltsPerVector == 0) {
4866       AllConsecutive = true;
4867       continue;
4868     }
4869 
4870     // Check all extracts for a vector register on the target directly
4871     // extract values in order.
4872     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4873     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4874       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4875       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4876                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4877     }
4878 
4879     if (AllConsecutive)
4880       continue;
4881 
4882     // Skip all indices, except for the last index per vector block.
4883     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4884       continue;
4885 
4886     // If we have a series of extracts which are not consecutive and hence
4887     // cannot re-use the source vector register directly, compute the shuffle
4888     // cost to extract the a vector with EltsPerVector elements.
4889     Cost += TTI.getShuffleCost(
4890         TargetTransformInfo::SK_PermuteSingleSrc,
4891         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4892   }
4893   return Cost;
4894 }
4895 
4896 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4897 /// operations operands.
4898 static void
4899 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4900                       ArrayRef<int> ReusesIndices,
4901                       const function_ref<bool(Instruction *)> IsAltOp,
4902                       SmallVectorImpl<int> &Mask,
4903                       SmallVectorImpl<Value *> *OpScalars = nullptr,
4904                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
4905   unsigned Sz = VL.size();
4906   Mask.assign(Sz, UndefMaskElem);
4907   SmallVector<int> OrderMask;
4908   if (!ReorderIndices.empty())
4909     inversePermutation(ReorderIndices, OrderMask);
4910   for (unsigned I = 0; I < Sz; ++I) {
4911     unsigned Idx = I;
4912     if (!ReorderIndices.empty())
4913       Idx = OrderMask[I];
4914     auto *OpInst = cast<Instruction>(VL[Idx]);
4915     if (IsAltOp(OpInst)) {
4916       Mask[I] = Sz + Idx;
4917       if (AltScalars)
4918         AltScalars->push_back(OpInst);
4919     } else {
4920       Mask[I] = Idx;
4921       if (OpScalars)
4922         OpScalars->push_back(OpInst);
4923     }
4924   }
4925   if (!ReusesIndices.empty()) {
4926     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4927     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4928       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4929     });
4930     Mask.swap(NewMask);
4931   }
4932 }
4933 
4934 /// Checks if the specified instruction \p I is an alternate operation for the
4935 /// given \p MainOp and \p AltOp instructions.
4936 static bool isAlternateInstruction(const Instruction *I,
4937                                    const Instruction *MainOp,
4938                                    const Instruction *AltOp) {
4939   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
4940     auto *AltCI0 = cast<CmpInst>(AltOp);
4941     auto *CI = cast<CmpInst>(I);
4942     CmpInst::Predicate P0 = CI0->getPredicate();
4943     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
4944     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
4945     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4946     CmpInst::Predicate CurrentPred = CI->getPredicate();
4947     if (P0 == AltP0Swapped)
4948       return I == AltCI0 ||
4949              (I != MainOp &&
4950               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
4951                                    CI->getOperand(0), CI->getOperand(1)));
4952     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
4953   }
4954   return I->getOpcode() == AltOp->getOpcode();
4955 }
4956 
4957 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4958                                       ArrayRef<Value *> VectorizedVals) {
4959   ArrayRef<Value*> VL = E->Scalars;
4960 
4961   Type *ScalarTy = VL[0]->getType();
4962   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4963     ScalarTy = SI->getValueOperand()->getType();
4964   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4965     ScalarTy = CI->getOperand(0)->getType();
4966   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4967     ScalarTy = IE->getOperand(1)->getType();
4968   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4969   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4970 
4971   // If we have computed a smaller type for the expression, update VecTy so
4972   // that the costs will be accurate.
4973   if (MinBWs.count(VL[0]))
4974     VecTy = FixedVectorType::get(
4975         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4976   unsigned EntryVF = E->getVectorFactor();
4977   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4978 
4979   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4980   // FIXME: it tries to fix a problem with MSVC buildbots.
4981   TargetTransformInfo &TTIRef = *TTI;
4982   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4983                                VectorizedVals, E](InstructionCost &Cost) {
4984     DenseMap<Value *, int> ExtractVectorsTys;
4985     SmallPtrSet<Value *, 4> CheckedExtracts;
4986     for (auto *V : VL) {
4987       if (isa<UndefValue>(V))
4988         continue;
4989       // If all users of instruction are going to be vectorized and this
4990       // instruction itself is not going to be vectorized, consider this
4991       // instruction as dead and remove its cost from the final cost of the
4992       // vectorized tree.
4993       // Also, avoid adjusting the cost for extractelements with multiple uses
4994       // in different graph entries.
4995       const TreeEntry *VE = getTreeEntry(V);
4996       if (!CheckedExtracts.insert(V).second ||
4997           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4998           (VE && VE != E))
4999         continue;
5000       auto *EE = cast<ExtractElementInst>(V);
5001       Optional<unsigned> EEIdx = getExtractIndex(EE);
5002       if (!EEIdx)
5003         continue;
5004       unsigned Idx = *EEIdx;
5005       if (TTIRef.getNumberOfParts(VecTy) !=
5006           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5007         auto It =
5008             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5009         It->getSecond() = std::min<int>(It->second, Idx);
5010       }
5011       // Take credit for instruction that will become dead.
5012       if (EE->hasOneUse()) {
5013         Instruction *Ext = EE->user_back();
5014         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5015             all_of(Ext->users(),
5016                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5017           // Use getExtractWithExtendCost() to calculate the cost of
5018           // extractelement/ext pair.
5019           Cost -=
5020               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5021                                               EE->getVectorOperandType(), Idx);
5022           // Add back the cost of s|zext which is subtracted separately.
5023           Cost += TTIRef.getCastInstrCost(
5024               Ext->getOpcode(), Ext->getType(), EE->getType(),
5025               TTI::getCastContextHint(Ext), CostKind, Ext);
5026           continue;
5027         }
5028       }
5029       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5030                                         EE->getVectorOperandType(), Idx);
5031     }
5032     // Add a cost for subvector extracts/inserts if required.
5033     for (const auto &Data : ExtractVectorsTys) {
5034       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5035       unsigned NumElts = VecTy->getNumElements();
5036       if (Data.second % NumElts == 0)
5037         continue;
5038       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5039         unsigned Idx = (Data.second / NumElts) * NumElts;
5040         unsigned EENumElts = EEVTy->getNumElements();
5041         if (Idx + NumElts <= EENumElts) {
5042           Cost +=
5043               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5044                                     EEVTy, None, Idx, VecTy);
5045         } else {
5046           // Need to round up the subvector type vectorization factor to avoid a
5047           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5048           // <= EENumElts.
5049           auto *SubVT =
5050               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5051           Cost +=
5052               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5053                                     EEVTy, None, Idx, SubVT);
5054         }
5055       } else {
5056         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5057                                       VecTy, None, 0, EEVTy);
5058       }
5059     }
5060   };
5061   if (E->State == TreeEntry::NeedToGather) {
5062     if (allConstant(VL))
5063       return 0;
5064     if (isa<InsertElementInst>(VL[0]))
5065       return InstructionCost::getInvalid();
5066     SmallVector<int> Mask;
5067     SmallVector<const TreeEntry *> Entries;
5068     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5069         isGatherShuffledEntry(E, Mask, Entries);
5070     if (Shuffle.hasValue()) {
5071       InstructionCost GatherCost = 0;
5072       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5073         // Perfect match in the graph, will reuse the previously vectorized
5074         // node. Cost is 0.
5075         LLVM_DEBUG(
5076             dbgs()
5077             << "SLP: perfect diamond match for gather bundle that starts with "
5078             << *VL.front() << ".\n");
5079         if (NeedToShuffleReuses)
5080           GatherCost =
5081               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5082                                   FinalVecTy, E->ReuseShuffleIndices);
5083       } else {
5084         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5085                           << " entries for bundle that starts with "
5086                           << *VL.front() << ".\n");
5087         // Detected that instead of gather we can emit a shuffle of single/two
5088         // previously vectorized nodes. Add the cost of the permutation rather
5089         // than gather.
5090         ::addMask(Mask, E->ReuseShuffleIndices);
5091         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5092       }
5093       return GatherCost;
5094     }
5095     if ((E->getOpcode() == Instruction::ExtractElement ||
5096          all_of(E->Scalars,
5097                 [](Value *V) {
5098                   return isa<ExtractElementInst, UndefValue>(V);
5099                 })) &&
5100         allSameType(VL)) {
5101       // Check that gather of extractelements can be represented as just a
5102       // shuffle of a single/two vectors the scalars are extracted from.
5103       SmallVector<int> Mask;
5104       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5105           isFixedVectorShuffle(VL, Mask);
5106       if (ShuffleKind.hasValue()) {
5107         // Found the bunch of extractelement instructions that must be gathered
5108         // into a vector and can be represented as a permutation elements in a
5109         // single input vector or of 2 input vectors.
5110         InstructionCost Cost =
5111             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5112         AdjustExtractsCost(Cost);
5113         if (NeedToShuffleReuses)
5114           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5115                                       FinalVecTy, E->ReuseShuffleIndices);
5116         return Cost;
5117       }
5118     }
5119     if (isSplat(VL)) {
5120       // Found the broadcasting of the single scalar, calculate the cost as the
5121       // broadcast.
5122       assert(VecTy == FinalVecTy &&
5123              "No reused scalars expected for broadcast.");
5124       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
5125     }
5126     InstructionCost ReuseShuffleCost = 0;
5127     if (NeedToShuffleReuses)
5128       ReuseShuffleCost = TTI->getShuffleCost(
5129           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5130     // Improve gather cost for gather of loads, if we can group some of the
5131     // loads into vector loads.
5132     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5133         !E->isAltShuffle()) {
5134       BoUpSLP::ValueSet VectorizedLoads;
5135       unsigned StartIdx = 0;
5136       unsigned VF = VL.size() / 2;
5137       unsigned VectorizedCnt = 0;
5138       unsigned ScatterVectorizeCnt = 0;
5139       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5140       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5141         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5142              Cnt += VF) {
5143           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5144           if (!VectorizedLoads.count(Slice.front()) &&
5145               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5146             SmallVector<Value *> PointerOps;
5147             OrdersType CurrentOrder;
5148             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5149                                               *SE, CurrentOrder, PointerOps);
5150             switch (LS) {
5151             case LoadsState::Vectorize:
5152             case LoadsState::ScatterVectorize:
5153               // Mark the vectorized loads so that we don't vectorize them
5154               // again.
5155               if (LS == LoadsState::Vectorize)
5156                 ++VectorizedCnt;
5157               else
5158                 ++ScatterVectorizeCnt;
5159               VectorizedLoads.insert(Slice.begin(), Slice.end());
5160               // If we vectorized initial block, no need to try to vectorize it
5161               // again.
5162               if (Cnt == StartIdx)
5163                 StartIdx += VF;
5164               break;
5165             case LoadsState::Gather:
5166               break;
5167             }
5168           }
5169         }
5170         // Check if the whole array was vectorized already - exit.
5171         if (StartIdx >= VL.size())
5172           break;
5173         // Found vectorizable parts - exit.
5174         if (!VectorizedLoads.empty())
5175           break;
5176       }
5177       if (!VectorizedLoads.empty()) {
5178         InstructionCost GatherCost = 0;
5179         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5180         bool NeedInsertSubvectorAnalysis =
5181             !NumParts || (VL.size() / VF) > NumParts;
5182         // Get the cost for gathered loads.
5183         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5184           if (VectorizedLoads.contains(VL[I]))
5185             continue;
5186           GatherCost += getGatherCost(VL.slice(I, VF));
5187         }
5188         // The cost for vectorized loads.
5189         InstructionCost ScalarsCost = 0;
5190         for (Value *V : VectorizedLoads) {
5191           auto *LI = cast<LoadInst>(V);
5192           ScalarsCost += TTI->getMemoryOpCost(
5193               Instruction::Load, LI->getType(), LI->getAlign(),
5194               LI->getPointerAddressSpace(), CostKind, LI);
5195         }
5196         auto *LI = cast<LoadInst>(E->getMainOp());
5197         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5198         Align Alignment = LI->getAlign();
5199         GatherCost +=
5200             VectorizedCnt *
5201             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5202                                  LI->getPointerAddressSpace(), CostKind, LI);
5203         GatherCost += ScatterVectorizeCnt *
5204                       TTI->getGatherScatterOpCost(
5205                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5206                           /*VariableMask=*/false, Alignment, CostKind, LI);
5207         if (NeedInsertSubvectorAnalysis) {
5208           // Add the cost for the subvectors insert.
5209           for (int I = VF, E = VL.size(); I < E; I += VF)
5210             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5211                                               None, I, LoadTy);
5212         }
5213         return ReuseShuffleCost + GatherCost - ScalarsCost;
5214       }
5215     }
5216     return ReuseShuffleCost + getGatherCost(VL);
5217   }
5218   InstructionCost CommonCost = 0;
5219   SmallVector<int> Mask;
5220   if (!E->ReorderIndices.empty()) {
5221     SmallVector<int> NewMask;
5222     if (E->getOpcode() == Instruction::Store) {
5223       // For stores the order is actually a mask.
5224       NewMask.resize(E->ReorderIndices.size());
5225       copy(E->ReorderIndices, NewMask.begin());
5226     } else {
5227       inversePermutation(E->ReorderIndices, NewMask);
5228     }
5229     ::addMask(Mask, NewMask);
5230   }
5231   if (NeedToShuffleReuses)
5232     ::addMask(Mask, E->ReuseShuffleIndices);
5233   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5234     CommonCost =
5235         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5236   assert((E->State == TreeEntry::Vectorize ||
5237           E->State == TreeEntry::ScatterVectorize) &&
5238          "Unhandled state");
5239   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5240   Instruction *VL0 = E->getMainOp();
5241   unsigned ShuffleOrOp =
5242       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5243   switch (ShuffleOrOp) {
5244     case Instruction::PHI:
5245       return 0;
5246 
5247     case Instruction::ExtractValue:
5248     case Instruction::ExtractElement: {
5249       // The common cost of removal ExtractElement/ExtractValue instructions +
5250       // the cost of shuffles, if required to resuffle the original vector.
5251       if (NeedToShuffleReuses) {
5252         unsigned Idx = 0;
5253         for (unsigned I : E->ReuseShuffleIndices) {
5254           if (ShuffleOrOp == Instruction::ExtractElement) {
5255             auto *EE = cast<ExtractElementInst>(VL[I]);
5256             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5257                                                   EE->getVectorOperandType(),
5258                                                   *getExtractIndex(EE));
5259           } else {
5260             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5261                                                   VecTy, Idx);
5262             ++Idx;
5263           }
5264         }
5265         Idx = EntryVF;
5266         for (Value *V : VL) {
5267           if (ShuffleOrOp == Instruction::ExtractElement) {
5268             auto *EE = cast<ExtractElementInst>(V);
5269             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5270                                                   EE->getVectorOperandType(),
5271                                                   *getExtractIndex(EE));
5272           } else {
5273             --Idx;
5274             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5275                                                   VecTy, Idx);
5276           }
5277         }
5278       }
5279       if (ShuffleOrOp == Instruction::ExtractValue) {
5280         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5281           auto *EI = cast<Instruction>(VL[I]);
5282           // Take credit for instruction that will become dead.
5283           if (EI->hasOneUse()) {
5284             Instruction *Ext = EI->user_back();
5285             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5286                 all_of(Ext->users(),
5287                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5288               // Use getExtractWithExtendCost() to calculate the cost of
5289               // extractelement/ext pair.
5290               CommonCost -= TTI->getExtractWithExtendCost(
5291                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5292               // Add back the cost of s|zext which is subtracted separately.
5293               CommonCost += TTI->getCastInstrCost(
5294                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5295                   TTI::getCastContextHint(Ext), CostKind, Ext);
5296               continue;
5297             }
5298           }
5299           CommonCost -=
5300               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5301         }
5302       } else {
5303         AdjustExtractsCost(CommonCost);
5304       }
5305       return CommonCost;
5306     }
5307     case Instruction::InsertElement: {
5308       assert(E->ReuseShuffleIndices.empty() &&
5309              "Unique insertelements only are expected.");
5310       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5311 
5312       unsigned const NumElts = SrcVecTy->getNumElements();
5313       unsigned const NumScalars = VL.size();
5314       APInt DemandedElts = APInt::getZero(NumElts);
5315       // TODO: Add support for Instruction::InsertValue.
5316       SmallVector<int> Mask;
5317       if (!E->ReorderIndices.empty()) {
5318         inversePermutation(E->ReorderIndices, Mask);
5319         Mask.append(NumElts - NumScalars, UndefMaskElem);
5320       } else {
5321         Mask.assign(NumElts, UndefMaskElem);
5322         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5323       }
5324       unsigned Offset = *getInsertIndex(VL0);
5325       bool IsIdentity = true;
5326       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5327       Mask.swap(PrevMask);
5328       for (unsigned I = 0; I < NumScalars; ++I) {
5329         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5330         DemandedElts.setBit(InsertIdx);
5331         IsIdentity &= InsertIdx - Offset == I;
5332         Mask[InsertIdx - Offset] = I;
5333       }
5334       assert(Offset < NumElts && "Failed to find vector index offset");
5335 
5336       InstructionCost Cost = 0;
5337       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5338                                             /*Insert*/ true, /*Extract*/ false);
5339 
5340       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5341         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5342         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5343         Cost += TTI->getShuffleCost(
5344             TargetTransformInfo::SK_PermuteSingleSrc,
5345             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5346       } else if (!IsIdentity) {
5347         auto *FirstInsert =
5348             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5349               return !is_contained(E->Scalars,
5350                                    cast<Instruction>(V)->getOperand(0));
5351             }));
5352         if (isUndefVector(FirstInsert->getOperand(0))) {
5353           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5354         } else {
5355           SmallVector<int> InsertMask(NumElts);
5356           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5357           for (unsigned I = 0; I < NumElts; I++) {
5358             if (Mask[I] != UndefMaskElem)
5359               InsertMask[Offset + I] = NumElts + I;
5360           }
5361           Cost +=
5362               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5363         }
5364       }
5365 
5366       return Cost;
5367     }
5368     case Instruction::ZExt:
5369     case Instruction::SExt:
5370     case Instruction::FPToUI:
5371     case Instruction::FPToSI:
5372     case Instruction::FPExt:
5373     case Instruction::PtrToInt:
5374     case Instruction::IntToPtr:
5375     case Instruction::SIToFP:
5376     case Instruction::UIToFP:
5377     case Instruction::Trunc:
5378     case Instruction::FPTrunc:
5379     case Instruction::BitCast: {
5380       Type *SrcTy = VL0->getOperand(0)->getType();
5381       InstructionCost ScalarEltCost =
5382           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5383                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5384       if (NeedToShuffleReuses) {
5385         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5386       }
5387 
5388       // Calculate the cost of this instruction.
5389       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5390 
5391       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5392       InstructionCost VecCost = 0;
5393       // Check if the values are candidates to demote.
5394       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5395         VecCost = CommonCost + TTI->getCastInstrCost(
5396                                    E->getOpcode(), VecTy, SrcVecTy,
5397                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5398       }
5399       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5400       return VecCost - ScalarCost;
5401     }
5402     case Instruction::FCmp:
5403     case Instruction::ICmp:
5404     case Instruction::Select: {
5405       // Calculate the cost of this instruction.
5406       InstructionCost ScalarEltCost =
5407           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5408                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5409       if (NeedToShuffleReuses) {
5410         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5411       }
5412       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5413       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5414 
5415       // Check if all entries in VL are either compares or selects with compares
5416       // as condition that have the same predicates.
5417       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5418       bool First = true;
5419       for (auto *V : VL) {
5420         CmpInst::Predicate CurrentPred;
5421         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5422         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5423              !match(V, MatchCmp)) ||
5424             (!First && VecPred != CurrentPred)) {
5425           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5426           break;
5427         }
5428         First = false;
5429         VecPred = CurrentPred;
5430       }
5431 
5432       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5433           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5434       // Check if it is possible and profitable to use min/max for selects in
5435       // VL.
5436       //
5437       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5438       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5439         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5440                                           {VecTy, VecTy});
5441         InstructionCost IntrinsicCost =
5442             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5443         // If the selects are the only uses of the compares, they will be dead
5444         // and we can adjust the cost by removing their cost.
5445         if (IntrinsicAndUse.second)
5446           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5447                                                    MaskTy, VecPred, CostKind);
5448         VecCost = std::min(VecCost, IntrinsicCost);
5449       }
5450       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5451       return CommonCost + VecCost - ScalarCost;
5452     }
5453     case Instruction::FNeg:
5454     case Instruction::Add:
5455     case Instruction::FAdd:
5456     case Instruction::Sub:
5457     case Instruction::FSub:
5458     case Instruction::Mul:
5459     case Instruction::FMul:
5460     case Instruction::UDiv:
5461     case Instruction::SDiv:
5462     case Instruction::FDiv:
5463     case Instruction::URem:
5464     case Instruction::SRem:
5465     case Instruction::FRem:
5466     case Instruction::Shl:
5467     case Instruction::LShr:
5468     case Instruction::AShr:
5469     case Instruction::And:
5470     case Instruction::Or:
5471     case Instruction::Xor: {
5472       // Certain instructions can be cheaper to vectorize if they have a
5473       // constant second vector operand.
5474       TargetTransformInfo::OperandValueKind Op1VK =
5475           TargetTransformInfo::OK_AnyValue;
5476       TargetTransformInfo::OperandValueKind Op2VK =
5477           TargetTransformInfo::OK_UniformConstantValue;
5478       TargetTransformInfo::OperandValueProperties Op1VP =
5479           TargetTransformInfo::OP_None;
5480       TargetTransformInfo::OperandValueProperties Op2VP =
5481           TargetTransformInfo::OP_PowerOf2;
5482 
5483       // If all operands are exactly the same ConstantInt then set the
5484       // operand kind to OK_UniformConstantValue.
5485       // If instead not all operands are constants, then set the operand kind
5486       // to OK_AnyValue. If all operands are constants but not the same,
5487       // then set the operand kind to OK_NonUniformConstantValue.
5488       ConstantInt *CInt0 = nullptr;
5489       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5490         const Instruction *I = cast<Instruction>(VL[i]);
5491         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5492         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5493         if (!CInt) {
5494           Op2VK = TargetTransformInfo::OK_AnyValue;
5495           Op2VP = TargetTransformInfo::OP_None;
5496           break;
5497         }
5498         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5499             !CInt->getValue().isPowerOf2())
5500           Op2VP = TargetTransformInfo::OP_None;
5501         if (i == 0) {
5502           CInt0 = CInt;
5503           continue;
5504         }
5505         if (CInt0 != CInt)
5506           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5507       }
5508 
5509       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5510       InstructionCost ScalarEltCost =
5511           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5512                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5513       if (NeedToShuffleReuses) {
5514         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5515       }
5516       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5517       InstructionCost VecCost =
5518           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5519                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5520       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5521       return CommonCost + VecCost - ScalarCost;
5522     }
5523     case Instruction::GetElementPtr: {
5524       TargetTransformInfo::OperandValueKind Op1VK =
5525           TargetTransformInfo::OK_AnyValue;
5526       TargetTransformInfo::OperandValueKind Op2VK =
5527           TargetTransformInfo::OK_UniformConstantValue;
5528 
5529       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5530           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5531       if (NeedToShuffleReuses) {
5532         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5533       }
5534       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5535       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5536           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5537       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5538       return CommonCost + VecCost - ScalarCost;
5539     }
5540     case Instruction::Load: {
5541       // Cost of wide load - cost of scalar loads.
5542       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5543       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5544           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5545       if (NeedToShuffleReuses) {
5546         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5547       }
5548       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5549       InstructionCost VecLdCost;
5550       if (E->State == TreeEntry::Vectorize) {
5551         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5552                                          CostKind, VL0);
5553       } else {
5554         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5555         Align CommonAlignment = Alignment;
5556         for (Value *V : VL)
5557           CommonAlignment =
5558               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5559         VecLdCost = TTI->getGatherScatterOpCost(
5560             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5561             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5562       }
5563       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5564       return CommonCost + VecLdCost - ScalarLdCost;
5565     }
5566     case Instruction::Store: {
5567       // We know that we can merge the stores. Calculate the cost.
5568       bool IsReorder = !E->ReorderIndices.empty();
5569       auto *SI =
5570           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5571       Align Alignment = SI->getAlign();
5572       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5573           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5574       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5575       InstructionCost VecStCost = TTI->getMemoryOpCost(
5576           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5577       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5578       return CommonCost + VecStCost - ScalarStCost;
5579     }
5580     case Instruction::Call: {
5581       CallInst *CI = cast<CallInst>(VL0);
5582       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5583 
5584       // Calculate the cost of the scalar and vector calls.
5585       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5586       InstructionCost ScalarEltCost =
5587           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5588       if (NeedToShuffleReuses) {
5589         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5590       }
5591       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5592 
5593       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5594       InstructionCost VecCallCost =
5595           std::min(VecCallCosts.first, VecCallCosts.second);
5596 
5597       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5598                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5599                         << " for " << *CI << "\n");
5600 
5601       return CommonCost + VecCallCost - ScalarCallCost;
5602     }
5603     case Instruction::ShuffleVector: {
5604       assert(E->isAltShuffle() &&
5605              ((Instruction::isBinaryOp(E->getOpcode()) &&
5606                Instruction::isBinaryOp(E->getAltOpcode())) ||
5607               (Instruction::isCast(E->getOpcode()) &&
5608                Instruction::isCast(E->getAltOpcode())) ||
5609               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5610              "Invalid Shuffle Vector Operand");
5611       InstructionCost ScalarCost = 0;
5612       if (NeedToShuffleReuses) {
5613         for (unsigned Idx : E->ReuseShuffleIndices) {
5614           Instruction *I = cast<Instruction>(VL[Idx]);
5615           CommonCost -= TTI->getInstructionCost(I, CostKind);
5616         }
5617         for (Value *V : VL) {
5618           Instruction *I = cast<Instruction>(V);
5619           CommonCost += TTI->getInstructionCost(I, CostKind);
5620         }
5621       }
5622       for (Value *V : VL) {
5623         Instruction *I = cast<Instruction>(V);
5624         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5625         ScalarCost += TTI->getInstructionCost(I, CostKind);
5626       }
5627       // VecCost is equal to sum of the cost of creating 2 vectors
5628       // and the cost of creating shuffle.
5629       InstructionCost VecCost = 0;
5630       // Try to find the previous shuffle node with the same operands and same
5631       // main/alternate ops.
5632       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5633         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5634           if (TE.get() == E)
5635             break;
5636           if (TE->isAltShuffle() &&
5637               ((TE->getOpcode() == E->getOpcode() &&
5638                 TE->getAltOpcode() == E->getAltOpcode()) ||
5639                (TE->getOpcode() == E->getAltOpcode() &&
5640                 TE->getAltOpcode() == E->getOpcode())) &&
5641               TE->hasEqualOperands(*E))
5642             return true;
5643         }
5644         return false;
5645       };
5646       if (TryFindNodeWithEqualOperands()) {
5647         LLVM_DEBUG({
5648           dbgs() << "SLP: diamond match for alternate node found.\n";
5649           E->dump();
5650         });
5651         // No need to add new vector costs here since we're going to reuse
5652         // same main/alternate vector ops, just do different shuffling.
5653       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5654         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5655         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5656                                                CostKind);
5657       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5658         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5659                                           Builder.getInt1Ty(),
5660                                           CI0->getPredicate(), CostKind, VL0);
5661         VecCost += TTI->getCmpSelInstrCost(
5662             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5663             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5664             E->getAltOp());
5665       } else {
5666         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5667         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5668         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5669         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5670         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5671                                         TTI::CastContextHint::None, CostKind);
5672         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5673                                          TTI::CastContextHint::None, CostKind);
5674       }
5675 
5676       SmallVector<int> Mask;
5677       buildShuffleEntryMask(
5678           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5679           [E](Instruction *I) {
5680             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5681             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5682           },
5683           Mask);
5684       CommonCost =
5685           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5686       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5687       return CommonCost + VecCost - ScalarCost;
5688     }
5689     default:
5690       llvm_unreachable("Unknown instruction");
5691   }
5692 }
5693 
5694 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5695   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5696                     << VectorizableTree.size() << " is fully vectorizable .\n");
5697 
5698   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5699     SmallVector<int> Mask;
5700     return TE->State == TreeEntry::NeedToGather &&
5701            !any_of(TE->Scalars,
5702                    [this](Value *V) { return EphValues.contains(V); }) &&
5703            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5704             TE->Scalars.size() < Limit ||
5705             ((TE->getOpcode() == Instruction::ExtractElement ||
5706               all_of(TE->Scalars,
5707                      [](Value *V) {
5708                        return isa<ExtractElementInst, UndefValue>(V);
5709                      })) &&
5710              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5711             (TE->State == TreeEntry::NeedToGather &&
5712              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5713   };
5714 
5715   // We only handle trees of heights 1 and 2.
5716   if (VectorizableTree.size() == 1 &&
5717       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5718        (ForReduction &&
5719         AreVectorizableGathers(VectorizableTree[0].get(),
5720                                VectorizableTree[0]->Scalars.size()) &&
5721         VectorizableTree[0]->getVectorFactor() > 2)))
5722     return true;
5723 
5724   if (VectorizableTree.size() != 2)
5725     return false;
5726 
5727   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5728   // with the second gather nodes if they have less scalar operands rather than
5729   // the initial tree element (may be profitable to shuffle the second gather)
5730   // or they are extractelements, which form shuffle.
5731   SmallVector<int> Mask;
5732   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5733       AreVectorizableGathers(VectorizableTree[1].get(),
5734                              VectorizableTree[0]->Scalars.size()))
5735     return true;
5736 
5737   // Gathering cost would be too much for tiny trees.
5738   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5739       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5740        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5741     return false;
5742 
5743   return true;
5744 }
5745 
5746 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5747                                        TargetTransformInfo *TTI,
5748                                        bool MustMatchOrInst) {
5749   // Look past the root to find a source value. Arbitrarily follow the
5750   // path through operand 0 of any 'or'. Also, peek through optional
5751   // shift-left-by-multiple-of-8-bits.
5752   Value *ZextLoad = Root;
5753   const APInt *ShAmtC;
5754   bool FoundOr = false;
5755   while (!isa<ConstantExpr>(ZextLoad) &&
5756          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5757           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5758            ShAmtC->urem(8) == 0))) {
5759     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5760     ZextLoad = BinOp->getOperand(0);
5761     if (BinOp->getOpcode() == Instruction::Or)
5762       FoundOr = true;
5763   }
5764   // Check if the input is an extended load of the required or/shift expression.
5765   Value *Load;
5766   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5767       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5768     return false;
5769 
5770   // Require that the total load bit width is a legal integer type.
5771   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5772   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5773   Type *SrcTy = Load->getType();
5774   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5775   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5776     return false;
5777 
5778   // Everything matched - assume that we can fold the whole sequence using
5779   // load combining.
5780   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5781              << *(cast<Instruction>(Root)) << "\n");
5782 
5783   return true;
5784 }
5785 
5786 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5787   if (RdxKind != RecurKind::Or)
5788     return false;
5789 
5790   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5791   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5792   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5793                                     /* MatchOr */ false);
5794 }
5795 
5796 bool BoUpSLP::isLoadCombineCandidate() const {
5797   // Peek through a final sequence of stores and check if all operations are
5798   // likely to be load-combined.
5799   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5800   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5801     Value *X;
5802     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5803         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5804       return false;
5805   }
5806   return true;
5807 }
5808 
5809 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5810   // No need to vectorize inserts of gathered values.
5811   if (VectorizableTree.size() == 2 &&
5812       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5813       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5814     return true;
5815 
5816   // We can vectorize the tree if its size is greater than or equal to the
5817   // minimum size specified by the MinTreeSize command line option.
5818   if (VectorizableTree.size() >= MinTreeSize)
5819     return false;
5820 
5821   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5822   // can vectorize it if we can prove it fully vectorizable.
5823   if (isFullyVectorizableTinyTree(ForReduction))
5824     return false;
5825 
5826   assert(VectorizableTree.empty()
5827              ? ExternalUses.empty()
5828              : true && "We shouldn't have any external users");
5829 
5830   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5831   // vectorizable.
5832   return true;
5833 }
5834 
5835 InstructionCost BoUpSLP::getSpillCost() const {
5836   // Walk from the bottom of the tree to the top, tracking which values are
5837   // live. When we see a call instruction that is not part of our tree,
5838   // query TTI to see if there is a cost to keeping values live over it
5839   // (for example, if spills and fills are required).
5840   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5841   InstructionCost Cost = 0;
5842 
5843   SmallPtrSet<Instruction*, 4> LiveValues;
5844   Instruction *PrevInst = nullptr;
5845 
5846   // The entries in VectorizableTree are not necessarily ordered by their
5847   // position in basic blocks. Collect them and order them by dominance so later
5848   // instructions are guaranteed to be visited first. For instructions in
5849   // different basic blocks, we only scan to the beginning of the block, so
5850   // their order does not matter, as long as all instructions in a basic block
5851   // are grouped together. Using dominance ensures a deterministic order.
5852   SmallVector<Instruction *, 16> OrderedScalars;
5853   for (const auto &TEPtr : VectorizableTree) {
5854     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5855     if (!Inst)
5856       continue;
5857     OrderedScalars.push_back(Inst);
5858   }
5859   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5860     auto *NodeA = DT->getNode(A->getParent());
5861     auto *NodeB = DT->getNode(B->getParent());
5862     assert(NodeA && "Should only process reachable instructions");
5863     assert(NodeB && "Should only process reachable instructions");
5864     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5865            "Different nodes should have different DFS numbers");
5866     if (NodeA != NodeB)
5867       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5868     return B->comesBefore(A);
5869   });
5870 
5871   for (Instruction *Inst : OrderedScalars) {
5872     if (!PrevInst) {
5873       PrevInst = Inst;
5874       continue;
5875     }
5876 
5877     // Update LiveValues.
5878     LiveValues.erase(PrevInst);
5879     for (auto &J : PrevInst->operands()) {
5880       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5881         LiveValues.insert(cast<Instruction>(&*J));
5882     }
5883 
5884     LLVM_DEBUG({
5885       dbgs() << "SLP: #LV: " << LiveValues.size();
5886       for (auto *X : LiveValues)
5887         dbgs() << " " << X->getName();
5888       dbgs() << ", Looking at ";
5889       Inst->dump();
5890     });
5891 
5892     // Now find the sequence of instructions between PrevInst and Inst.
5893     unsigned NumCalls = 0;
5894     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5895                                  PrevInstIt =
5896                                      PrevInst->getIterator().getReverse();
5897     while (InstIt != PrevInstIt) {
5898       if (PrevInstIt == PrevInst->getParent()->rend()) {
5899         PrevInstIt = Inst->getParent()->rbegin();
5900         continue;
5901       }
5902 
5903       // Debug information does not impact spill cost.
5904       if ((isa<CallInst>(&*PrevInstIt) &&
5905            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5906           &*PrevInstIt != PrevInst)
5907         NumCalls++;
5908 
5909       ++PrevInstIt;
5910     }
5911 
5912     if (NumCalls) {
5913       SmallVector<Type*, 4> V;
5914       for (auto *II : LiveValues) {
5915         auto *ScalarTy = II->getType();
5916         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5917           ScalarTy = VectorTy->getElementType();
5918         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5919       }
5920       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5921     }
5922 
5923     PrevInst = Inst;
5924   }
5925 
5926   return Cost;
5927 }
5928 
5929 /// Check if two insertelement instructions are from the same buildvector.
5930 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5931                                             InsertElementInst *V) {
5932   // Instructions must be from the same basic blocks.
5933   if (VU->getParent() != V->getParent())
5934     return false;
5935   // Checks if 2 insertelements are from the same buildvector.
5936   if (VU->getType() != V->getType())
5937     return false;
5938   // Multiple used inserts are separate nodes.
5939   if (!VU->hasOneUse() && !V->hasOneUse())
5940     return false;
5941   auto *IE1 = VU;
5942   auto *IE2 = V;
5943   // Go through the vector operand of insertelement instructions trying to find
5944   // either VU as the original vector for IE2 or V as the original vector for
5945   // IE1.
5946   do {
5947     if (IE2 == VU || IE1 == V)
5948       return true;
5949     if (IE1) {
5950       if (IE1 != VU && !IE1->hasOneUse())
5951         IE1 = nullptr;
5952       else
5953         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5954     }
5955     if (IE2) {
5956       if (IE2 != V && !IE2->hasOneUse())
5957         IE2 = nullptr;
5958       else
5959         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5960     }
5961   } while (IE1 || IE2);
5962   return false;
5963 }
5964 
5965 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5966   InstructionCost Cost = 0;
5967   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5968                     << VectorizableTree.size() << ".\n");
5969 
5970   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5971 
5972   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5973     TreeEntry &TE = *VectorizableTree[I].get();
5974 
5975     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5976     Cost += C;
5977     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5978                       << " for bundle that starts with " << *TE.Scalars[0]
5979                       << ".\n"
5980                       << "SLP: Current total cost = " << Cost << "\n");
5981   }
5982 
5983   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5984   InstructionCost ExtractCost = 0;
5985   SmallVector<unsigned> VF;
5986   SmallVector<SmallVector<int>> ShuffleMask;
5987   SmallVector<Value *> FirstUsers;
5988   SmallVector<APInt> DemandedElts;
5989   for (ExternalUser &EU : ExternalUses) {
5990     // We only add extract cost once for the same scalar.
5991     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5992         !ExtractCostCalculated.insert(EU.Scalar).second)
5993       continue;
5994 
5995     // Uses by ephemeral values are free (because the ephemeral value will be
5996     // removed prior to code generation, and so the extraction will be
5997     // removed as well).
5998     if (EphValues.count(EU.User))
5999       continue;
6000 
6001     // No extract cost for vector "scalar"
6002     if (isa<FixedVectorType>(EU.Scalar->getType()))
6003       continue;
6004 
6005     // Already counted the cost for external uses when tried to adjust the cost
6006     // for extractelements, no need to add it again.
6007     if (isa<ExtractElementInst>(EU.Scalar))
6008       continue;
6009 
6010     // If found user is an insertelement, do not calculate extract cost but try
6011     // to detect it as a final shuffled/identity match.
6012     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6013       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6014         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6015         if (InsertIdx) {
6016           auto *It = find_if(FirstUsers, [VU](Value *V) {
6017             return areTwoInsertFromSameBuildVector(VU,
6018                                                    cast<InsertElementInst>(V));
6019           });
6020           int VecId = -1;
6021           if (It == FirstUsers.end()) {
6022             VF.push_back(FTy->getNumElements());
6023             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6024             // Find the insertvector, vectorized in tree, if any.
6025             Value *Base = VU;
6026             while (isa<InsertElementInst>(Base)) {
6027               // Build the mask for the vectorized insertelement instructions.
6028               if (const TreeEntry *E = getTreeEntry(Base)) {
6029                 VU = cast<InsertElementInst>(Base);
6030                 do {
6031                   int Idx = E->findLaneForValue(Base);
6032                   ShuffleMask.back()[Idx] = Idx;
6033                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6034                 } while (E == getTreeEntry(Base));
6035                 break;
6036               }
6037               Base = cast<InsertElementInst>(Base)->getOperand(0);
6038             }
6039             FirstUsers.push_back(VU);
6040             DemandedElts.push_back(APInt::getZero(VF.back()));
6041             VecId = FirstUsers.size() - 1;
6042           } else {
6043             VecId = std::distance(FirstUsers.begin(), It);
6044           }
6045           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6046           DemandedElts[VecId].setBit(*InsertIdx);
6047           continue;
6048         }
6049       }
6050     }
6051 
6052     // If we plan to rewrite the tree in a smaller type, we will need to sign
6053     // extend the extracted value back to the original type. Here, we account
6054     // for the extract and the added cost of the sign extend if needed.
6055     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6056     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6057     if (MinBWs.count(ScalarRoot)) {
6058       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6059       auto Extend =
6060           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6061       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6062       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6063                                                    VecTy, EU.Lane);
6064     } else {
6065       ExtractCost +=
6066           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6067     }
6068   }
6069 
6070   InstructionCost SpillCost = getSpillCost();
6071   Cost += SpillCost + ExtractCost;
6072   if (FirstUsers.size() == 1) {
6073     int Limit = ShuffleMask.front().size() * 2;
6074     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6075         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6076       InstructionCost C = TTI->getShuffleCost(
6077           TTI::SK_PermuteSingleSrc,
6078           cast<FixedVectorType>(FirstUsers.front()->getType()),
6079           ShuffleMask.front());
6080       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6081                         << " for final shuffle of insertelement external users "
6082                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6083                         << "SLP: Current total cost = " << Cost << "\n");
6084       Cost += C;
6085     }
6086     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6087         cast<FixedVectorType>(FirstUsers.front()->getType()),
6088         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6089     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6090                       << " for insertelements gather.\n"
6091                       << "SLP: Current total cost = " << Cost << "\n");
6092     Cost -= InsertCost;
6093   } else if (FirstUsers.size() >= 2) {
6094     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6095     // Combined masks of the first 2 vectors.
6096     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6097     copy(ShuffleMask.front(), CombinedMask.begin());
6098     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6099     auto *VecTy = FixedVectorType::get(
6100         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6101         MaxVF);
6102     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6103       if (ShuffleMask[1][I] != UndefMaskElem) {
6104         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6105         CombinedDemandedElts.setBit(I);
6106       }
6107     }
6108     InstructionCost C =
6109         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6110     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6111                       << " for final shuffle of vector node and external "
6112                          "insertelement users "
6113                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6114                       << "SLP: Current total cost = " << Cost << "\n");
6115     Cost += C;
6116     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6117         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6118     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6119                       << " for insertelements gather.\n"
6120                       << "SLP: Current total cost = " << Cost << "\n");
6121     Cost -= InsertCost;
6122     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6123       // Other elements - permutation of 2 vectors (the initial one and the
6124       // next Ith incoming vector).
6125       unsigned VF = ShuffleMask[I].size();
6126       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6127         int Mask = ShuffleMask[I][Idx];
6128         if (Mask != UndefMaskElem)
6129           CombinedMask[Idx] = MaxVF + Mask;
6130         else if (CombinedMask[Idx] != UndefMaskElem)
6131           CombinedMask[Idx] = Idx;
6132       }
6133       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6134         if (CombinedMask[Idx] != UndefMaskElem)
6135           CombinedMask[Idx] = Idx;
6136       InstructionCost C =
6137           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6138       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6139                         << " for final shuffle of vector node and external "
6140                            "insertelement users "
6141                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6142                         << "SLP: Current total cost = " << Cost << "\n");
6143       Cost += C;
6144       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6145           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6146           /*Insert*/ true, /*Extract*/ false);
6147       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6148                         << " for insertelements gather.\n"
6149                         << "SLP: Current total cost = " << Cost << "\n");
6150       Cost -= InsertCost;
6151     }
6152   }
6153 
6154 #ifndef NDEBUG
6155   SmallString<256> Str;
6156   {
6157     raw_svector_ostream OS(Str);
6158     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6159        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6160        << "SLP: Total Cost = " << Cost << ".\n";
6161   }
6162   LLVM_DEBUG(dbgs() << Str);
6163   if (ViewSLPTree)
6164     ViewGraph(this, "SLP" + F->getName(), false, Str);
6165 #endif
6166 
6167   return Cost;
6168 }
6169 
6170 Optional<TargetTransformInfo::ShuffleKind>
6171 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6172                                SmallVectorImpl<const TreeEntry *> &Entries) {
6173   // TODO: currently checking only for Scalars in the tree entry, need to count
6174   // reused elements too for better cost estimation.
6175   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6176   Entries.clear();
6177   // Build a lists of values to tree entries.
6178   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6179   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6180     if (EntryPtr.get() == TE)
6181       break;
6182     if (EntryPtr->State != TreeEntry::NeedToGather)
6183       continue;
6184     for (Value *V : EntryPtr->Scalars)
6185       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6186   }
6187   // Find all tree entries used by the gathered values. If no common entries
6188   // found - not a shuffle.
6189   // Here we build a set of tree nodes for each gathered value and trying to
6190   // find the intersection between these sets. If we have at least one common
6191   // tree node for each gathered value - we have just a permutation of the
6192   // single vector. If we have 2 different sets, we're in situation where we
6193   // have a permutation of 2 input vectors.
6194   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6195   DenseMap<Value *, int> UsedValuesEntry;
6196   for (Value *V : TE->Scalars) {
6197     if (isa<UndefValue>(V))
6198       continue;
6199     // Build a list of tree entries where V is used.
6200     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6201     auto It = ValueToTEs.find(V);
6202     if (It != ValueToTEs.end())
6203       VToTEs = It->second;
6204     if (const TreeEntry *VTE = getTreeEntry(V))
6205       VToTEs.insert(VTE);
6206     if (VToTEs.empty())
6207       return None;
6208     if (UsedTEs.empty()) {
6209       // The first iteration, just insert the list of nodes to vector.
6210       UsedTEs.push_back(VToTEs);
6211     } else {
6212       // Need to check if there are any previously used tree nodes which use V.
6213       // If there are no such nodes, consider that we have another one input
6214       // vector.
6215       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6216       unsigned Idx = 0;
6217       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6218         // Do we have a non-empty intersection of previously listed tree entries
6219         // and tree entries using current V?
6220         set_intersect(VToTEs, Set);
6221         if (!VToTEs.empty()) {
6222           // Yes, write the new subset and continue analysis for the next
6223           // scalar.
6224           Set.swap(VToTEs);
6225           break;
6226         }
6227         VToTEs = SavedVToTEs;
6228         ++Idx;
6229       }
6230       // No non-empty intersection found - need to add a second set of possible
6231       // source vectors.
6232       if (Idx == UsedTEs.size()) {
6233         // If the number of input vectors is greater than 2 - not a permutation,
6234         // fallback to the regular gather.
6235         if (UsedTEs.size() == 2)
6236           return None;
6237         UsedTEs.push_back(SavedVToTEs);
6238         Idx = UsedTEs.size() - 1;
6239       }
6240       UsedValuesEntry.try_emplace(V, Idx);
6241     }
6242   }
6243 
6244   unsigned VF = 0;
6245   if (UsedTEs.size() == 1) {
6246     // Try to find the perfect match in another gather node at first.
6247     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6248       return EntryPtr->isSame(TE->Scalars);
6249     });
6250     if (It != UsedTEs.front().end()) {
6251       Entries.push_back(*It);
6252       std::iota(Mask.begin(), Mask.end(), 0);
6253       return TargetTransformInfo::SK_PermuteSingleSrc;
6254     }
6255     // No perfect match, just shuffle, so choose the first tree node.
6256     Entries.push_back(*UsedTEs.front().begin());
6257   } else {
6258     // Try to find nodes with the same vector factor.
6259     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6260     DenseMap<int, const TreeEntry *> VFToTE;
6261     for (const TreeEntry *TE : UsedTEs.front())
6262       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6263     for (const TreeEntry *TE : UsedTEs.back()) {
6264       auto It = VFToTE.find(TE->getVectorFactor());
6265       if (It != VFToTE.end()) {
6266         VF = It->first;
6267         Entries.push_back(It->second);
6268         Entries.push_back(TE);
6269         break;
6270       }
6271     }
6272     // No 2 source vectors with the same vector factor - give up and do regular
6273     // gather.
6274     if (Entries.empty())
6275       return None;
6276   }
6277 
6278   // Build a shuffle mask for better cost estimation and vector emission.
6279   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6280     Value *V = TE->Scalars[I];
6281     if (isa<UndefValue>(V))
6282       continue;
6283     unsigned Idx = UsedValuesEntry.lookup(V);
6284     const TreeEntry *VTE = Entries[Idx];
6285     int FoundLane = VTE->findLaneForValue(V);
6286     Mask[I] = Idx * VF + FoundLane;
6287     // Extra check required by isSingleSourceMaskImpl function (called by
6288     // ShuffleVectorInst::isSingleSourceMask).
6289     if (Mask[I] >= 2 * E)
6290       return None;
6291   }
6292   switch (Entries.size()) {
6293   case 1:
6294     return TargetTransformInfo::SK_PermuteSingleSrc;
6295   case 2:
6296     return TargetTransformInfo::SK_PermuteTwoSrc;
6297   default:
6298     break;
6299   }
6300   return None;
6301 }
6302 
6303 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6304                                        const APInt &ShuffledIndices,
6305                                        bool NeedToShuffle) const {
6306   InstructionCost Cost =
6307       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6308                                     /*Extract*/ false);
6309   if (NeedToShuffle)
6310     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6311   return Cost;
6312 }
6313 
6314 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6315   // Find the type of the operands in VL.
6316   Type *ScalarTy = VL[0]->getType();
6317   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6318     ScalarTy = SI->getValueOperand()->getType();
6319   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6320   bool DuplicateNonConst = false;
6321   // Find the cost of inserting/extracting values from the vector.
6322   // Check if the same elements are inserted several times and count them as
6323   // shuffle candidates.
6324   APInt ShuffledElements = APInt::getZero(VL.size());
6325   DenseSet<Value *> UniqueElements;
6326   // Iterate in reverse order to consider insert elements with the high cost.
6327   for (unsigned I = VL.size(); I > 0; --I) {
6328     unsigned Idx = I - 1;
6329     // No need to shuffle duplicates for constants.
6330     if (isConstant(VL[Idx])) {
6331       ShuffledElements.setBit(Idx);
6332       continue;
6333     }
6334     if (!UniqueElements.insert(VL[Idx]).second) {
6335       DuplicateNonConst = true;
6336       ShuffledElements.setBit(Idx);
6337     }
6338   }
6339   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6340 }
6341 
6342 // Perform operand reordering on the instructions in VL and return the reordered
6343 // operands in Left and Right.
6344 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6345                                              SmallVectorImpl<Value *> &Left,
6346                                              SmallVectorImpl<Value *> &Right,
6347                                              const DataLayout &DL,
6348                                              ScalarEvolution &SE,
6349                                              const BoUpSLP &R) {
6350   if (VL.empty())
6351     return;
6352   VLOperands Ops(VL, DL, SE, R);
6353   // Reorder the operands in place.
6354   Ops.reorder();
6355   Left = Ops.getVL(0);
6356   Right = Ops.getVL(1);
6357 }
6358 
6359 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6360   // Get the basic block this bundle is in. All instructions in the bundle
6361   // should be in this block.
6362   auto *Front = E->getMainOp();
6363   auto *BB = Front->getParent();
6364   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6365     auto *I = cast<Instruction>(V);
6366     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6367   }));
6368 
6369   // The last instruction in the bundle in program order.
6370   Instruction *LastInst = nullptr;
6371 
6372   // Find the last instruction. The common case should be that BB has been
6373   // scheduled, and the last instruction is VL.back(). So we start with
6374   // VL.back() and iterate over schedule data until we reach the end of the
6375   // bundle. The end of the bundle is marked by null ScheduleData.
6376   if (BlocksSchedules.count(BB)) {
6377     auto *Bundle =
6378         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6379     if (Bundle && Bundle->isPartOfBundle())
6380       for (; Bundle; Bundle = Bundle->NextInBundle)
6381         if (Bundle->OpValue == Bundle->Inst)
6382           LastInst = Bundle->Inst;
6383   }
6384 
6385   // LastInst can still be null at this point if there's either not an entry
6386   // for BB in BlocksSchedules or there's no ScheduleData available for
6387   // VL.back(). This can be the case if buildTree_rec aborts for various
6388   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6389   // size is reached, etc.). ScheduleData is initialized in the scheduling
6390   // "dry-run".
6391   //
6392   // If this happens, we can still find the last instruction by brute force. We
6393   // iterate forwards from Front (inclusive) until we either see all
6394   // instructions in the bundle or reach the end of the block. If Front is the
6395   // last instruction in program order, LastInst will be set to Front, and we
6396   // will visit all the remaining instructions in the block.
6397   //
6398   // One of the reasons we exit early from buildTree_rec is to place an upper
6399   // bound on compile-time. Thus, taking an additional compile-time hit here is
6400   // not ideal. However, this should be exceedingly rare since it requires that
6401   // we both exit early from buildTree_rec and that the bundle be out-of-order
6402   // (causing us to iterate all the way to the end of the block).
6403   if (!LastInst) {
6404     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6405     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6406       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6407         LastInst = &I;
6408       if (Bundle.empty())
6409         break;
6410     }
6411   }
6412   assert(LastInst && "Failed to find last instruction in bundle");
6413 
6414   // Set the insertion point after the last instruction in the bundle. Set the
6415   // debug location to Front.
6416   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6417   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6418 }
6419 
6420 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6421   // List of instructions/lanes from current block and/or the blocks which are
6422   // part of the current loop. These instructions will be inserted at the end to
6423   // make it possible to optimize loops and hoist invariant instructions out of
6424   // the loops body with better chances for success.
6425   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6426   SmallSet<int, 4> PostponedIndices;
6427   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6428   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6429     SmallPtrSet<BasicBlock *, 4> Visited;
6430     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6431       InsertBB = InsertBB->getSinglePredecessor();
6432     return InsertBB && InsertBB == InstBB;
6433   };
6434   for (int I = 0, E = VL.size(); I < E; ++I) {
6435     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6436       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6437            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6438           PostponedIndices.insert(I).second)
6439         PostponedInsts.emplace_back(Inst, I);
6440   }
6441 
6442   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6443     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6444     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6445     if (!InsElt)
6446       return Vec;
6447     GatherShuffleSeq.insert(InsElt);
6448     CSEBlocks.insert(InsElt->getParent());
6449     // Add to our 'need-to-extract' list.
6450     if (TreeEntry *Entry = getTreeEntry(V)) {
6451       // Find which lane we need to extract.
6452       unsigned FoundLane = Entry->findLaneForValue(V);
6453       ExternalUses.emplace_back(V, InsElt, FoundLane);
6454     }
6455     return Vec;
6456   };
6457   Value *Val0 =
6458       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6459   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6460   Value *Vec = PoisonValue::get(VecTy);
6461   SmallVector<int> NonConsts;
6462   // Insert constant values at first.
6463   for (int I = 0, E = VL.size(); I < E; ++I) {
6464     if (PostponedIndices.contains(I))
6465       continue;
6466     if (!isConstant(VL[I])) {
6467       NonConsts.push_back(I);
6468       continue;
6469     }
6470     Vec = CreateInsertElement(Vec, VL[I], I);
6471   }
6472   // Insert non-constant values.
6473   for (int I : NonConsts)
6474     Vec = CreateInsertElement(Vec, VL[I], I);
6475   // Append instructions, which are/may be part of the loop, in the end to make
6476   // it possible to hoist non-loop-based instructions.
6477   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6478     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6479 
6480   return Vec;
6481 }
6482 
6483 namespace {
6484 /// Merges shuffle masks and emits final shuffle instruction, if required.
6485 class ShuffleInstructionBuilder {
6486   IRBuilderBase &Builder;
6487   const unsigned VF = 0;
6488   bool IsFinalized = false;
6489   SmallVector<int, 4> Mask;
6490   /// Holds all of the instructions that we gathered.
6491   SetVector<Instruction *> &GatherShuffleSeq;
6492   /// A list of blocks that we are going to CSE.
6493   SetVector<BasicBlock *> &CSEBlocks;
6494 
6495 public:
6496   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6497                             SetVector<Instruction *> &GatherShuffleSeq,
6498                             SetVector<BasicBlock *> &CSEBlocks)
6499       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6500         CSEBlocks(CSEBlocks) {}
6501 
6502   /// Adds a mask, inverting it before applying.
6503   void addInversedMask(ArrayRef<unsigned> SubMask) {
6504     if (SubMask.empty())
6505       return;
6506     SmallVector<int, 4> NewMask;
6507     inversePermutation(SubMask, NewMask);
6508     addMask(NewMask);
6509   }
6510 
6511   /// Functions adds masks, merging them into  single one.
6512   void addMask(ArrayRef<unsigned> SubMask) {
6513     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6514     addMask(NewMask);
6515   }
6516 
6517   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6518 
6519   Value *finalize(Value *V) {
6520     IsFinalized = true;
6521     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6522     if (VF == ValueVF && Mask.empty())
6523       return V;
6524     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6525     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6526     addMask(NormalizedMask);
6527 
6528     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6529       return V;
6530     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6531     if (auto *I = dyn_cast<Instruction>(Vec)) {
6532       GatherShuffleSeq.insert(I);
6533       CSEBlocks.insert(I->getParent());
6534     }
6535     return Vec;
6536   }
6537 
6538   ~ShuffleInstructionBuilder() {
6539     assert((IsFinalized || Mask.empty()) &&
6540            "Shuffle construction must be finalized.");
6541   }
6542 };
6543 } // namespace
6544 
6545 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6546   unsigned VF = VL.size();
6547   InstructionsState S = getSameOpcode(VL);
6548   if (S.getOpcode()) {
6549     if (TreeEntry *E = getTreeEntry(S.OpValue))
6550       if (E->isSame(VL)) {
6551         Value *V = vectorizeTree(E);
6552         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6553           if (!E->ReuseShuffleIndices.empty()) {
6554             // Reshuffle to get only unique values.
6555             // If some of the scalars are duplicated in the vectorization tree
6556             // entry, we do not vectorize them but instead generate a mask for
6557             // the reuses. But if there are several users of the same entry,
6558             // they may have different vectorization factors. This is especially
6559             // important for PHI nodes. In this case, we need to adapt the
6560             // resulting instruction for the user vectorization factor and have
6561             // to reshuffle it again to take only unique elements of the vector.
6562             // Without this code the function incorrectly returns reduced vector
6563             // instruction with the same elements, not with the unique ones.
6564 
6565             // block:
6566             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6567             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6568             // ... (use %2)
6569             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6570             // br %block
6571             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6572             SmallSet<int, 4> UsedIdxs;
6573             int Pos = 0;
6574             int Sz = VL.size();
6575             for (int Idx : E->ReuseShuffleIndices) {
6576               if (Idx != Sz && Idx != UndefMaskElem &&
6577                   UsedIdxs.insert(Idx).second)
6578                 UniqueIdxs[Idx] = Pos;
6579               ++Pos;
6580             }
6581             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6582                                             "less than original vector size.");
6583             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6584             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6585           } else {
6586             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6587                    "Expected vectorization factor less "
6588                    "than original vector size.");
6589             SmallVector<int> UniformMask(VF, 0);
6590             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6591             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6592           }
6593           if (auto *I = dyn_cast<Instruction>(V)) {
6594             GatherShuffleSeq.insert(I);
6595             CSEBlocks.insert(I->getParent());
6596           }
6597         }
6598         return V;
6599       }
6600   }
6601 
6602   // Check that every instruction appears once in this bundle.
6603   SmallVector<int> ReuseShuffleIndicies;
6604   SmallVector<Value *> UniqueValues;
6605   if (VL.size() > 2) {
6606     DenseMap<Value *, unsigned> UniquePositions;
6607     unsigned NumValues =
6608         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6609                                     return !isa<UndefValue>(V);
6610                                   }).base());
6611     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6612     int UniqueVals = 0;
6613     for (Value *V : VL.drop_back(VL.size() - VF)) {
6614       if (isa<UndefValue>(V)) {
6615         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6616         continue;
6617       }
6618       if (isConstant(V)) {
6619         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6620         UniqueValues.emplace_back(V);
6621         continue;
6622       }
6623       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6624       ReuseShuffleIndicies.emplace_back(Res.first->second);
6625       if (Res.second) {
6626         UniqueValues.emplace_back(V);
6627         ++UniqueVals;
6628       }
6629     }
6630     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6631       // Emit pure splat vector.
6632       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6633                                   UndefMaskElem);
6634     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6635       ReuseShuffleIndicies.clear();
6636       UniqueValues.clear();
6637       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6638     }
6639     UniqueValues.append(VF - UniqueValues.size(),
6640                         PoisonValue::get(VL[0]->getType()));
6641     VL = UniqueValues;
6642   }
6643 
6644   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6645                                            CSEBlocks);
6646   Value *Vec = gather(VL);
6647   if (!ReuseShuffleIndicies.empty()) {
6648     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6649     Vec = ShuffleBuilder.finalize(Vec);
6650   }
6651   return Vec;
6652 }
6653 
6654 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6655   IRBuilder<>::InsertPointGuard Guard(Builder);
6656 
6657   if (E->VectorizedValue) {
6658     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6659     return E->VectorizedValue;
6660   }
6661 
6662   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6663   unsigned VF = E->getVectorFactor();
6664   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6665                                            CSEBlocks);
6666   if (E->State == TreeEntry::NeedToGather) {
6667     if (E->getMainOp())
6668       setInsertPointAfterBundle(E);
6669     Value *Vec;
6670     SmallVector<int> Mask;
6671     SmallVector<const TreeEntry *> Entries;
6672     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6673         isGatherShuffledEntry(E, Mask, Entries);
6674     if (Shuffle.hasValue()) {
6675       assert((Entries.size() == 1 || Entries.size() == 2) &&
6676              "Expected shuffle of 1 or 2 entries.");
6677       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6678                                         Entries.back()->VectorizedValue, Mask);
6679       if (auto *I = dyn_cast<Instruction>(Vec)) {
6680         GatherShuffleSeq.insert(I);
6681         CSEBlocks.insert(I->getParent());
6682       }
6683     } else {
6684       Vec = gather(E->Scalars);
6685     }
6686     if (NeedToShuffleReuses) {
6687       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6688       Vec = ShuffleBuilder.finalize(Vec);
6689     }
6690     E->VectorizedValue = Vec;
6691     return Vec;
6692   }
6693 
6694   assert((E->State == TreeEntry::Vectorize ||
6695           E->State == TreeEntry::ScatterVectorize) &&
6696          "Unhandled state");
6697   unsigned ShuffleOrOp =
6698       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6699   Instruction *VL0 = E->getMainOp();
6700   Type *ScalarTy = VL0->getType();
6701   if (auto *Store = dyn_cast<StoreInst>(VL0))
6702     ScalarTy = Store->getValueOperand()->getType();
6703   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6704     ScalarTy = IE->getOperand(1)->getType();
6705   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6706   switch (ShuffleOrOp) {
6707     case Instruction::PHI: {
6708       assert(
6709           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6710           "PHI reordering is free.");
6711       auto *PH = cast<PHINode>(VL0);
6712       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6713       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6714       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6715       Value *V = NewPhi;
6716 
6717       // Adjust insertion point once all PHI's have been generated.
6718       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6719       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6720 
6721       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6722       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6723       V = ShuffleBuilder.finalize(V);
6724 
6725       E->VectorizedValue = V;
6726 
6727       // PHINodes may have multiple entries from the same block. We want to
6728       // visit every block once.
6729       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6730 
6731       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6732         ValueList Operands;
6733         BasicBlock *IBB = PH->getIncomingBlock(i);
6734 
6735         if (!VisitedBBs.insert(IBB).second) {
6736           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6737           continue;
6738         }
6739 
6740         Builder.SetInsertPoint(IBB->getTerminator());
6741         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6742         Value *Vec = vectorizeTree(E->getOperand(i));
6743         NewPhi->addIncoming(Vec, IBB);
6744       }
6745 
6746       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6747              "Invalid number of incoming values");
6748       return V;
6749     }
6750 
6751     case Instruction::ExtractElement: {
6752       Value *V = E->getSingleOperand(0);
6753       Builder.SetInsertPoint(VL0);
6754       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6755       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6756       V = ShuffleBuilder.finalize(V);
6757       E->VectorizedValue = V;
6758       return V;
6759     }
6760     case Instruction::ExtractValue: {
6761       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6762       Builder.SetInsertPoint(LI);
6763       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6764       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6765       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6766       Value *NewV = propagateMetadata(V, E->Scalars);
6767       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6768       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6769       NewV = ShuffleBuilder.finalize(NewV);
6770       E->VectorizedValue = NewV;
6771       return NewV;
6772     }
6773     case Instruction::InsertElement: {
6774       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6775       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6776       Value *V = vectorizeTree(E->getOperand(1));
6777 
6778       // Create InsertVector shuffle if necessary
6779       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6780         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6781       }));
6782       const unsigned NumElts =
6783           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6784       const unsigned NumScalars = E->Scalars.size();
6785 
6786       unsigned Offset = *getInsertIndex(VL0);
6787       assert(Offset < NumElts && "Failed to find vector index offset");
6788 
6789       // Create shuffle to resize vector
6790       SmallVector<int> Mask;
6791       if (!E->ReorderIndices.empty()) {
6792         inversePermutation(E->ReorderIndices, Mask);
6793         Mask.append(NumElts - NumScalars, UndefMaskElem);
6794       } else {
6795         Mask.assign(NumElts, UndefMaskElem);
6796         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6797       }
6798       // Create InsertVector shuffle if necessary
6799       bool IsIdentity = true;
6800       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6801       Mask.swap(PrevMask);
6802       for (unsigned I = 0; I < NumScalars; ++I) {
6803         Value *Scalar = E->Scalars[PrevMask[I]];
6804         unsigned InsertIdx = *getInsertIndex(Scalar);
6805         IsIdentity &= InsertIdx - Offset == I;
6806         Mask[InsertIdx - Offset] = I;
6807       }
6808       if (!IsIdentity || NumElts != NumScalars) {
6809         V = Builder.CreateShuffleVector(V, Mask);
6810         if (auto *I = dyn_cast<Instruction>(V)) {
6811           GatherShuffleSeq.insert(I);
6812           CSEBlocks.insert(I->getParent());
6813         }
6814       }
6815 
6816       if ((!IsIdentity || Offset != 0 ||
6817            !isUndefVector(FirstInsert->getOperand(0))) &&
6818           NumElts != NumScalars) {
6819         SmallVector<int> InsertMask(NumElts);
6820         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6821         for (unsigned I = 0; I < NumElts; I++) {
6822           if (Mask[I] != UndefMaskElem)
6823             InsertMask[Offset + I] = NumElts + I;
6824         }
6825 
6826         V = Builder.CreateShuffleVector(
6827             FirstInsert->getOperand(0), V, InsertMask,
6828             cast<Instruction>(E->Scalars.back())->getName());
6829         if (auto *I = dyn_cast<Instruction>(V)) {
6830           GatherShuffleSeq.insert(I);
6831           CSEBlocks.insert(I->getParent());
6832         }
6833       }
6834 
6835       ++NumVectorInstructions;
6836       E->VectorizedValue = V;
6837       return V;
6838     }
6839     case Instruction::ZExt:
6840     case Instruction::SExt:
6841     case Instruction::FPToUI:
6842     case Instruction::FPToSI:
6843     case Instruction::FPExt:
6844     case Instruction::PtrToInt:
6845     case Instruction::IntToPtr:
6846     case Instruction::SIToFP:
6847     case Instruction::UIToFP:
6848     case Instruction::Trunc:
6849     case Instruction::FPTrunc:
6850     case Instruction::BitCast: {
6851       setInsertPointAfterBundle(E);
6852 
6853       Value *InVec = vectorizeTree(E->getOperand(0));
6854 
6855       if (E->VectorizedValue) {
6856         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6857         return E->VectorizedValue;
6858       }
6859 
6860       auto *CI = cast<CastInst>(VL0);
6861       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6862       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6863       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6864       V = ShuffleBuilder.finalize(V);
6865 
6866       E->VectorizedValue = V;
6867       ++NumVectorInstructions;
6868       return V;
6869     }
6870     case Instruction::FCmp:
6871     case Instruction::ICmp: {
6872       setInsertPointAfterBundle(E);
6873 
6874       Value *L = vectorizeTree(E->getOperand(0));
6875       Value *R = vectorizeTree(E->getOperand(1));
6876 
6877       if (E->VectorizedValue) {
6878         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6879         return E->VectorizedValue;
6880       }
6881 
6882       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6883       Value *V = Builder.CreateCmp(P0, L, R);
6884       propagateIRFlags(V, E->Scalars, VL0);
6885       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6886       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6887       V = ShuffleBuilder.finalize(V);
6888 
6889       E->VectorizedValue = V;
6890       ++NumVectorInstructions;
6891       return V;
6892     }
6893     case Instruction::Select: {
6894       setInsertPointAfterBundle(E);
6895 
6896       Value *Cond = vectorizeTree(E->getOperand(0));
6897       Value *True = vectorizeTree(E->getOperand(1));
6898       Value *False = vectorizeTree(E->getOperand(2));
6899 
6900       if (E->VectorizedValue) {
6901         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6902         return E->VectorizedValue;
6903       }
6904 
6905       Value *V = Builder.CreateSelect(Cond, True, False);
6906       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6907       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6908       V = ShuffleBuilder.finalize(V);
6909 
6910       E->VectorizedValue = V;
6911       ++NumVectorInstructions;
6912       return V;
6913     }
6914     case Instruction::FNeg: {
6915       setInsertPointAfterBundle(E);
6916 
6917       Value *Op = vectorizeTree(E->getOperand(0));
6918 
6919       if (E->VectorizedValue) {
6920         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6921         return E->VectorizedValue;
6922       }
6923 
6924       Value *V = Builder.CreateUnOp(
6925           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6926       propagateIRFlags(V, E->Scalars, VL0);
6927       if (auto *I = dyn_cast<Instruction>(V))
6928         V = propagateMetadata(I, E->Scalars);
6929 
6930       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6931       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6932       V = ShuffleBuilder.finalize(V);
6933 
6934       E->VectorizedValue = V;
6935       ++NumVectorInstructions;
6936 
6937       return V;
6938     }
6939     case Instruction::Add:
6940     case Instruction::FAdd:
6941     case Instruction::Sub:
6942     case Instruction::FSub:
6943     case Instruction::Mul:
6944     case Instruction::FMul:
6945     case Instruction::UDiv:
6946     case Instruction::SDiv:
6947     case Instruction::FDiv:
6948     case Instruction::URem:
6949     case Instruction::SRem:
6950     case Instruction::FRem:
6951     case Instruction::Shl:
6952     case Instruction::LShr:
6953     case Instruction::AShr:
6954     case Instruction::And:
6955     case Instruction::Or:
6956     case Instruction::Xor: {
6957       setInsertPointAfterBundle(E);
6958 
6959       Value *LHS = vectorizeTree(E->getOperand(0));
6960       Value *RHS = vectorizeTree(E->getOperand(1));
6961 
6962       if (E->VectorizedValue) {
6963         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6964         return E->VectorizedValue;
6965       }
6966 
6967       Value *V = Builder.CreateBinOp(
6968           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6969           RHS);
6970       propagateIRFlags(V, E->Scalars, VL0);
6971       if (auto *I = dyn_cast<Instruction>(V))
6972         V = propagateMetadata(I, E->Scalars);
6973 
6974       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6975       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6976       V = ShuffleBuilder.finalize(V);
6977 
6978       E->VectorizedValue = V;
6979       ++NumVectorInstructions;
6980 
6981       return V;
6982     }
6983     case Instruction::Load: {
6984       // Loads are inserted at the head of the tree because we don't want to
6985       // sink them all the way down past store instructions.
6986       setInsertPointAfterBundle(E);
6987 
6988       LoadInst *LI = cast<LoadInst>(VL0);
6989       Instruction *NewLI;
6990       unsigned AS = LI->getPointerAddressSpace();
6991       Value *PO = LI->getPointerOperand();
6992       if (E->State == TreeEntry::Vectorize) {
6993 
6994         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6995 
6996         // The pointer operand uses an in-tree scalar so we add the new BitCast
6997         // to ExternalUses list to make sure that an extract will be generated
6998         // in the future.
6999         if (TreeEntry *Entry = getTreeEntry(PO)) {
7000           // Find which lane we need to extract.
7001           unsigned FoundLane = Entry->findLaneForValue(PO);
7002           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
7003         }
7004 
7005         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7006       } else {
7007         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7008         Value *VecPtr = vectorizeTree(E->getOperand(0));
7009         // Use the minimum alignment of the gathered loads.
7010         Align CommonAlignment = LI->getAlign();
7011         for (Value *V : E->Scalars)
7012           CommonAlignment =
7013               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7014         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7015       }
7016       Value *V = propagateMetadata(NewLI, E->Scalars);
7017 
7018       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7019       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7020       V = ShuffleBuilder.finalize(V);
7021       E->VectorizedValue = V;
7022       ++NumVectorInstructions;
7023       return V;
7024     }
7025     case Instruction::Store: {
7026       auto *SI = cast<StoreInst>(VL0);
7027       unsigned AS = SI->getPointerAddressSpace();
7028 
7029       setInsertPointAfterBundle(E);
7030 
7031       Value *VecValue = vectorizeTree(E->getOperand(0));
7032       ShuffleBuilder.addMask(E->ReorderIndices);
7033       VecValue = ShuffleBuilder.finalize(VecValue);
7034 
7035       Value *ScalarPtr = SI->getPointerOperand();
7036       Value *VecPtr = Builder.CreateBitCast(
7037           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7038       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
7039                                                  SI->getAlign());
7040 
7041       // The pointer operand uses an in-tree scalar, so add the new BitCast to
7042       // ExternalUses to make sure that an extract will be generated in the
7043       // future.
7044       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7045         // Find which lane we need to extract.
7046         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7047         ExternalUses.push_back(
7048             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
7049       }
7050 
7051       Value *V = propagateMetadata(ST, E->Scalars);
7052 
7053       E->VectorizedValue = V;
7054       ++NumVectorInstructions;
7055       return V;
7056     }
7057     case Instruction::GetElementPtr: {
7058       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7059       setInsertPointAfterBundle(E);
7060 
7061       Value *Op0 = vectorizeTree(E->getOperand(0));
7062 
7063       SmallVector<Value *> OpVecs;
7064       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7065         Value *OpVec = vectorizeTree(E->getOperand(J));
7066         OpVecs.push_back(OpVec);
7067       }
7068 
7069       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7070       if (Instruction *I = dyn_cast<Instruction>(V))
7071         V = propagateMetadata(I, E->Scalars);
7072 
7073       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7074       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7075       V = ShuffleBuilder.finalize(V);
7076 
7077       E->VectorizedValue = V;
7078       ++NumVectorInstructions;
7079 
7080       return V;
7081     }
7082     case Instruction::Call: {
7083       CallInst *CI = cast<CallInst>(VL0);
7084       setInsertPointAfterBundle(E);
7085 
7086       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7087       if (Function *FI = CI->getCalledFunction())
7088         IID = FI->getIntrinsicID();
7089 
7090       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7091 
7092       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7093       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7094                           VecCallCosts.first <= VecCallCosts.second;
7095 
7096       Value *ScalarArg = nullptr;
7097       std::vector<Value *> OpVecs;
7098       SmallVector<Type *, 2> TysForDecl =
7099           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7100       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7101         ValueList OpVL;
7102         // Some intrinsics have scalar arguments. This argument should not be
7103         // vectorized.
7104         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7105           CallInst *CEI = cast<CallInst>(VL0);
7106           ScalarArg = CEI->getArgOperand(j);
7107           OpVecs.push_back(CEI->getArgOperand(j));
7108           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7109             TysForDecl.push_back(ScalarArg->getType());
7110           continue;
7111         }
7112 
7113         Value *OpVec = vectorizeTree(E->getOperand(j));
7114         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7115         OpVecs.push_back(OpVec);
7116       }
7117 
7118       Function *CF;
7119       if (!UseIntrinsic) {
7120         VFShape Shape =
7121             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7122                                   VecTy->getNumElements())),
7123                          false /*HasGlobalPred*/);
7124         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7125       } else {
7126         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7127       }
7128 
7129       SmallVector<OperandBundleDef, 1> OpBundles;
7130       CI->getOperandBundlesAsDefs(OpBundles);
7131       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7132 
7133       // The scalar argument uses an in-tree scalar so we add the new vectorized
7134       // call to ExternalUses list to make sure that an extract will be
7135       // generated in the future.
7136       if (ScalarArg) {
7137         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7138           // Find which lane we need to extract.
7139           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7140           ExternalUses.push_back(
7141               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7142         }
7143       }
7144 
7145       propagateIRFlags(V, E->Scalars, VL0);
7146       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7147       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7148       V = ShuffleBuilder.finalize(V);
7149 
7150       E->VectorizedValue = V;
7151       ++NumVectorInstructions;
7152       return V;
7153     }
7154     case Instruction::ShuffleVector: {
7155       assert(E->isAltShuffle() &&
7156              ((Instruction::isBinaryOp(E->getOpcode()) &&
7157                Instruction::isBinaryOp(E->getAltOpcode())) ||
7158               (Instruction::isCast(E->getOpcode()) &&
7159                Instruction::isCast(E->getAltOpcode())) ||
7160               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7161              "Invalid Shuffle Vector Operand");
7162 
7163       Value *LHS = nullptr, *RHS = nullptr;
7164       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7165         setInsertPointAfterBundle(E);
7166         LHS = vectorizeTree(E->getOperand(0));
7167         RHS = vectorizeTree(E->getOperand(1));
7168       } else {
7169         setInsertPointAfterBundle(E);
7170         LHS = vectorizeTree(E->getOperand(0));
7171       }
7172 
7173       if (E->VectorizedValue) {
7174         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7175         return E->VectorizedValue;
7176       }
7177 
7178       Value *V0, *V1;
7179       if (Instruction::isBinaryOp(E->getOpcode())) {
7180         V0 = Builder.CreateBinOp(
7181             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7182         V1 = Builder.CreateBinOp(
7183             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7184       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7185         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7186         auto *AltCI = cast<CmpInst>(E->getAltOp());
7187         CmpInst::Predicate AltPred = AltCI->getPredicate();
7188         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7189       } else {
7190         V0 = Builder.CreateCast(
7191             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7192         V1 = Builder.CreateCast(
7193             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7194       }
7195       // Add V0 and V1 to later analysis to try to find and remove matching
7196       // instruction, if any.
7197       for (Value *V : {V0, V1}) {
7198         if (auto *I = dyn_cast<Instruction>(V)) {
7199           GatherShuffleSeq.insert(I);
7200           CSEBlocks.insert(I->getParent());
7201         }
7202       }
7203 
7204       // Create shuffle to take alternate operations from the vector.
7205       // Also, gather up main and alt scalar ops to propagate IR flags to
7206       // each vector operation.
7207       ValueList OpScalars, AltScalars;
7208       SmallVector<int> Mask;
7209       buildShuffleEntryMask(
7210           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7211           [E](Instruction *I) {
7212             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7213             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7214           },
7215           Mask, &OpScalars, &AltScalars);
7216 
7217       propagateIRFlags(V0, OpScalars);
7218       propagateIRFlags(V1, AltScalars);
7219 
7220       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7221       if (auto *I = dyn_cast<Instruction>(V)) {
7222         V = propagateMetadata(I, E->Scalars);
7223         GatherShuffleSeq.insert(I);
7224         CSEBlocks.insert(I->getParent());
7225       }
7226       V = ShuffleBuilder.finalize(V);
7227 
7228       E->VectorizedValue = V;
7229       ++NumVectorInstructions;
7230 
7231       return V;
7232     }
7233     default:
7234     llvm_unreachable("unknown inst");
7235   }
7236   return nullptr;
7237 }
7238 
7239 Value *BoUpSLP::vectorizeTree() {
7240   ExtraValueToDebugLocsMap ExternallyUsedValues;
7241   return vectorizeTree(ExternallyUsedValues);
7242 }
7243 
7244 Value *
7245 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7246   // All blocks must be scheduled before any instructions are inserted.
7247   for (auto &BSIter : BlocksSchedules) {
7248     scheduleBlock(BSIter.second.get());
7249   }
7250 
7251   Builder.SetInsertPoint(&F->getEntryBlock().front());
7252   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7253 
7254   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7255   // vectorized root. InstCombine will then rewrite the entire expression. We
7256   // sign extend the extracted values below.
7257   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7258   if (MinBWs.count(ScalarRoot)) {
7259     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7260       // If current instr is a phi and not the last phi, insert it after the
7261       // last phi node.
7262       if (isa<PHINode>(I))
7263         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7264       else
7265         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7266     }
7267     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7268     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7269     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7270     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7271     VectorizableTree[0]->VectorizedValue = Trunc;
7272   }
7273 
7274   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7275                     << " values .\n");
7276 
7277   // Extract all of the elements with the external uses.
7278   for (const auto &ExternalUse : ExternalUses) {
7279     Value *Scalar = ExternalUse.Scalar;
7280     llvm::User *User = ExternalUse.User;
7281 
7282     // Skip users that we already RAUW. This happens when one instruction
7283     // has multiple uses of the same value.
7284     if (User && !is_contained(Scalar->users(), User))
7285       continue;
7286     TreeEntry *E = getTreeEntry(Scalar);
7287     assert(E && "Invalid scalar");
7288     assert(E->State != TreeEntry::NeedToGather &&
7289            "Extracting from a gather list");
7290 
7291     Value *Vec = E->VectorizedValue;
7292     assert(Vec && "Can't find vectorizable value");
7293 
7294     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7295     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7296       if (Scalar->getType() != Vec->getType()) {
7297         Value *Ex;
7298         // "Reuse" the existing extract to improve final codegen.
7299         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7300           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7301                                             ES->getOperand(1));
7302         } else {
7303           Ex = Builder.CreateExtractElement(Vec, Lane);
7304         }
7305         // If necessary, sign-extend or zero-extend ScalarRoot
7306         // to the larger type.
7307         if (!MinBWs.count(ScalarRoot))
7308           return Ex;
7309         if (MinBWs[ScalarRoot].second)
7310           return Builder.CreateSExt(Ex, Scalar->getType());
7311         return Builder.CreateZExt(Ex, Scalar->getType());
7312       }
7313       assert(isa<FixedVectorType>(Scalar->getType()) &&
7314              isa<InsertElementInst>(Scalar) &&
7315              "In-tree scalar of vector type is not insertelement?");
7316       return Vec;
7317     };
7318     // If User == nullptr, the Scalar is used as extra arg. Generate
7319     // ExtractElement instruction and update the record for this scalar in
7320     // ExternallyUsedValues.
7321     if (!User) {
7322       assert(ExternallyUsedValues.count(Scalar) &&
7323              "Scalar with nullptr as an external user must be registered in "
7324              "ExternallyUsedValues map");
7325       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7326         Builder.SetInsertPoint(VecI->getParent(),
7327                                std::next(VecI->getIterator()));
7328       } else {
7329         Builder.SetInsertPoint(&F->getEntryBlock().front());
7330       }
7331       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7332       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7333       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7334       auto It = ExternallyUsedValues.find(Scalar);
7335       assert(It != ExternallyUsedValues.end() &&
7336              "Externally used scalar is not found in ExternallyUsedValues");
7337       NewInstLocs.append(It->second);
7338       ExternallyUsedValues.erase(Scalar);
7339       // Required to update internally referenced instructions.
7340       Scalar->replaceAllUsesWith(NewInst);
7341       continue;
7342     }
7343 
7344     // Generate extracts for out-of-tree users.
7345     // Find the insertion point for the extractelement lane.
7346     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7347       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7348         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7349           if (PH->getIncomingValue(i) == Scalar) {
7350             Instruction *IncomingTerminator =
7351                 PH->getIncomingBlock(i)->getTerminator();
7352             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7353               Builder.SetInsertPoint(VecI->getParent(),
7354                                      std::next(VecI->getIterator()));
7355             } else {
7356               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7357             }
7358             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7359             CSEBlocks.insert(PH->getIncomingBlock(i));
7360             PH->setOperand(i, NewInst);
7361           }
7362         }
7363       } else {
7364         Builder.SetInsertPoint(cast<Instruction>(User));
7365         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7366         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7367         User->replaceUsesOfWith(Scalar, NewInst);
7368       }
7369     } else {
7370       Builder.SetInsertPoint(&F->getEntryBlock().front());
7371       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7372       CSEBlocks.insert(&F->getEntryBlock());
7373       User->replaceUsesOfWith(Scalar, NewInst);
7374     }
7375 
7376     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7377   }
7378 
7379   // For each vectorized value:
7380   for (auto &TEPtr : VectorizableTree) {
7381     TreeEntry *Entry = TEPtr.get();
7382 
7383     // No need to handle users of gathered values.
7384     if (Entry->State == TreeEntry::NeedToGather)
7385       continue;
7386 
7387     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7388 
7389     // For each lane:
7390     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7391       Value *Scalar = Entry->Scalars[Lane];
7392 
7393 #ifndef NDEBUG
7394       Type *Ty = Scalar->getType();
7395       if (!Ty->isVoidTy()) {
7396         for (User *U : Scalar->users()) {
7397           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7398 
7399           // It is legal to delete users in the ignorelist.
7400           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7401                   (isa_and_nonnull<Instruction>(U) &&
7402                    isDeleted(cast<Instruction>(U)))) &&
7403                  "Deleting out-of-tree value");
7404         }
7405       }
7406 #endif
7407       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7408       eraseInstruction(cast<Instruction>(Scalar));
7409     }
7410   }
7411 
7412   Builder.ClearInsertionPoint();
7413   InstrElementSize.clear();
7414 
7415   return VectorizableTree[0]->VectorizedValue;
7416 }
7417 
7418 void BoUpSLP::optimizeGatherSequence() {
7419   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7420                     << " gather sequences instructions.\n");
7421   // LICM InsertElementInst sequences.
7422   for (Instruction *I : GatherShuffleSeq) {
7423     if (isDeleted(I))
7424       continue;
7425 
7426     // Check if this block is inside a loop.
7427     Loop *L = LI->getLoopFor(I->getParent());
7428     if (!L)
7429       continue;
7430 
7431     // Check if it has a preheader.
7432     BasicBlock *PreHeader = L->getLoopPreheader();
7433     if (!PreHeader)
7434       continue;
7435 
7436     // If the vector or the element that we insert into it are
7437     // instructions that are defined in this basic block then we can't
7438     // hoist this instruction.
7439     if (any_of(I->operands(), [L](Value *V) {
7440           auto *OpI = dyn_cast<Instruction>(V);
7441           return OpI && L->contains(OpI);
7442         }))
7443       continue;
7444 
7445     // We can hoist this instruction. Move it to the pre-header.
7446     I->moveBefore(PreHeader->getTerminator());
7447   }
7448 
7449   // Make a list of all reachable blocks in our CSE queue.
7450   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7451   CSEWorkList.reserve(CSEBlocks.size());
7452   for (BasicBlock *BB : CSEBlocks)
7453     if (DomTreeNode *N = DT->getNode(BB)) {
7454       assert(DT->isReachableFromEntry(N));
7455       CSEWorkList.push_back(N);
7456     }
7457 
7458   // Sort blocks by domination. This ensures we visit a block after all blocks
7459   // dominating it are visited.
7460   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7461     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7462            "Different nodes should have different DFS numbers");
7463     return A->getDFSNumIn() < B->getDFSNumIn();
7464   });
7465 
7466   // Less defined shuffles can be replaced by the more defined copies.
7467   // Between two shuffles one is less defined if it has the same vector operands
7468   // and its mask indeces are the same as in the first one or undefs. E.g.
7469   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7470   // poison, <0, 0, 0, 0>.
7471   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7472                                            SmallVectorImpl<int> &NewMask) {
7473     if (I1->getType() != I2->getType())
7474       return false;
7475     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7476     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7477     if (!SI1 || !SI2)
7478       return I1->isIdenticalTo(I2);
7479     if (SI1->isIdenticalTo(SI2))
7480       return true;
7481     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7482       if (SI1->getOperand(I) != SI2->getOperand(I))
7483         return false;
7484     // Check if the second instruction is more defined than the first one.
7485     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7486     ArrayRef<int> SM1 = SI1->getShuffleMask();
7487     // Count trailing undefs in the mask to check the final number of used
7488     // registers.
7489     unsigned LastUndefsCnt = 0;
7490     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7491       if (SM1[I] == UndefMaskElem)
7492         ++LastUndefsCnt;
7493       else
7494         LastUndefsCnt = 0;
7495       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7496           NewMask[I] != SM1[I])
7497         return false;
7498       if (NewMask[I] == UndefMaskElem)
7499         NewMask[I] = SM1[I];
7500     }
7501     // Check if the last undefs actually change the final number of used vector
7502     // registers.
7503     return SM1.size() - LastUndefsCnt > 1 &&
7504            TTI->getNumberOfParts(SI1->getType()) ==
7505                TTI->getNumberOfParts(
7506                    FixedVectorType::get(SI1->getType()->getElementType(),
7507                                         SM1.size() - LastUndefsCnt));
7508   };
7509   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7510   // instructions. TODO: We can further optimize this scan if we split the
7511   // instructions into different buckets based on the insert lane.
7512   SmallVector<Instruction *, 16> Visited;
7513   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7514     assert(*I &&
7515            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7516            "Worklist not sorted properly!");
7517     BasicBlock *BB = (*I)->getBlock();
7518     // For all instructions in blocks containing gather sequences:
7519     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7520       if (isDeleted(&In))
7521         continue;
7522       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7523           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7524         continue;
7525 
7526       // Check if we can replace this instruction with any of the
7527       // visited instructions.
7528       bool Replaced = false;
7529       for (Instruction *&V : Visited) {
7530         SmallVector<int> NewMask;
7531         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7532             DT->dominates(V->getParent(), In.getParent())) {
7533           In.replaceAllUsesWith(V);
7534           eraseInstruction(&In);
7535           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7536             if (!NewMask.empty())
7537               SI->setShuffleMask(NewMask);
7538           Replaced = true;
7539           break;
7540         }
7541         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7542             GatherShuffleSeq.contains(V) &&
7543             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7544             DT->dominates(In.getParent(), V->getParent())) {
7545           In.moveAfter(V);
7546           V->replaceAllUsesWith(&In);
7547           eraseInstruction(V);
7548           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7549             if (!NewMask.empty())
7550               SI->setShuffleMask(NewMask);
7551           V = &In;
7552           Replaced = true;
7553           break;
7554         }
7555       }
7556       if (!Replaced) {
7557         assert(!is_contained(Visited, &In));
7558         Visited.push_back(&In);
7559       }
7560     }
7561   }
7562   CSEBlocks.clear();
7563   GatherShuffleSeq.clear();
7564 }
7565 
7566 BoUpSLP::ScheduleData *
7567 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7568   ScheduleData *Bundle = nullptr;
7569   ScheduleData *PrevInBundle = nullptr;
7570   for (Value *V : VL) {
7571     ScheduleData *BundleMember = getScheduleData(V);
7572     assert(BundleMember &&
7573            "no ScheduleData for bundle member "
7574            "(maybe not in same basic block)");
7575     assert(BundleMember->isSchedulingEntity() &&
7576            "bundle member already part of other bundle");
7577     if (PrevInBundle) {
7578       PrevInBundle->NextInBundle = BundleMember;
7579     } else {
7580       Bundle = BundleMember;
7581     }
7582 
7583     // Group the instructions to a bundle.
7584     BundleMember->FirstInBundle = Bundle;
7585     PrevInBundle = BundleMember;
7586   }
7587   assert(Bundle && "Failed to find schedule bundle");
7588   return Bundle;
7589 }
7590 
7591 // Groups the instructions to a bundle (which is then a single scheduling entity)
7592 // and schedules instructions until the bundle gets ready.
7593 Optional<BoUpSLP::ScheduleData *>
7594 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7595                                             const InstructionsState &S) {
7596   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7597   // instructions.
7598   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7599     return nullptr;
7600 
7601   // Initialize the instruction bundle.
7602   Instruction *OldScheduleEnd = ScheduleEnd;
7603   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7604 
7605   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7606                                                          ScheduleData *Bundle) {
7607     // The scheduling region got new instructions at the lower end (or it is a
7608     // new region for the first bundle). This makes it necessary to
7609     // recalculate all dependencies.
7610     // It is seldom that this needs to be done a second time after adding the
7611     // initial bundle to the region.
7612     if (ScheduleEnd != OldScheduleEnd) {
7613       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7614         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7615       ReSchedule = true;
7616     }
7617     if (Bundle) {
7618       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7619                         << " in block " << BB->getName() << "\n");
7620       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7621     }
7622 
7623     if (ReSchedule) {
7624       resetSchedule();
7625       initialFillReadyList(ReadyInsts);
7626     }
7627 
7628     // Now try to schedule the new bundle or (if no bundle) just calculate
7629     // dependencies. As soon as the bundle is "ready" it means that there are no
7630     // cyclic dependencies and we can schedule it. Note that's important that we
7631     // don't "schedule" the bundle yet (see cancelScheduling).
7632     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7633            !ReadyInsts.empty()) {
7634       ScheduleData *Picked = ReadyInsts.pop_back_val();
7635       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7636              "must be ready to schedule");
7637       schedule(Picked, ReadyInsts);
7638     }
7639   };
7640 
7641   // Make sure that the scheduling region contains all
7642   // instructions of the bundle.
7643   for (Value *V : VL) {
7644     if (!extendSchedulingRegion(V, S)) {
7645       // If the scheduling region got new instructions at the lower end (or it
7646       // is a new region for the first bundle). This makes it necessary to
7647       // recalculate all dependencies.
7648       // Otherwise the compiler may crash trying to incorrectly calculate
7649       // dependencies and emit instruction in the wrong order at the actual
7650       // scheduling.
7651       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7652       return None;
7653     }
7654   }
7655 
7656   bool ReSchedule = false;
7657   for (Value *V : VL) {
7658     ScheduleData *BundleMember = getScheduleData(V);
7659     assert(BundleMember &&
7660            "no ScheduleData for bundle member (maybe not in same basic block)");
7661 
7662     // Make sure we don't leave the pieces of the bundle in the ready list when
7663     // whole bundle might not be ready.
7664     ReadyInsts.remove(BundleMember);
7665 
7666     if (!BundleMember->IsScheduled)
7667       continue;
7668     // A bundle member was scheduled as single instruction before and now
7669     // needs to be scheduled as part of the bundle. We just get rid of the
7670     // existing schedule.
7671     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7672                       << " was already scheduled\n");
7673     ReSchedule = true;
7674   }
7675 
7676   auto *Bundle = buildBundle(VL);
7677   TryScheduleBundleImpl(ReSchedule, Bundle);
7678   if (!Bundle->isReady()) {
7679     cancelScheduling(VL, S.OpValue);
7680     return None;
7681   }
7682   return Bundle;
7683 }
7684 
7685 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7686                                                 Value *OpValue) {
7687   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7688     return;
7689 
7690   ScheduleData *Bundle = getScheduleData(OpValue);
7691   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7692   assert(!Bundle->IsScheduled &&
7693          "Can't cancel bundle which is already scheduled");
7694   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7695          "tried to unbundle something which is not a bundle");
7696 
7697   // Remove the bundle from the ready list.
7698   if (Bundle->isReady())
7699     ReadyInsts.remove(Bundle);
7700 
7701   // Un-bundle: make single instructions out of the bundle.
7702   ScheduleData *BundleMember = Bundle;
7703   while (BundleMember) {
7704     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7705     BundleMember->FirstInBundle = BundleMember;
7706     ScheduleData *Next = BundleMember->NextInBundle;
7707     BundleMember->NextInBundle = nullptr;
7708     if (BundleMember->unscheduledDepsInBundle() == 0) {
7709       ReadyInsts.insert(BundleMember);
7710     }
7711     BundleMember = Next;
7712   }
7713 }
7714 
7715 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7716   // Allocate a new ScheduleData for the instruction.
7717   if (ChunkPos >= ChunkSize) {
7718     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7719     ChunkPos = 0;
7720   }
7721   return &(ScheduleDataChunks.back()[ChunkPos++]);
7722 }
7723 
7724 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7725                                                       const InstructionsState &S) {
7726   if (getScheduleData(V, isOneOf(S, V)))
7727     return true;
7728   Instruction *I = dyn_cast<Instruction>(V);
7729   assert(I && "bundle member must be an instruction");
7730   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7731          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7732          "be scheduled");
7733   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7734     ScheduleData *ISD = getScheduleData(I);
7735     if (!ISD)
7736       return false;
7737     assert(isInSchedulingRegion(ISD) &&
7738            "ScheduleData not in scheduling region");
7739     ScheduleData *SD = allocateScheduleDataChunks();
7740     SD->Inst = I;
7741     SD->init(SchedulingRegionID, S.OpValue);
7742     ExtraScheduleDataMap[I][S.OpValue] = SD;
7743     return true;
7744   };
7745   if (CheckSheduleForI(I))
7746     return true;
7747   if (!ScheduleStart) {
7748     // It's the first instruction in the new region.
7749     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7750     ScheduleStart = I;
7751     ScheduleEnd = I->getNextNode();
7752     if (isOneOf(S, I) != I)
7753       CheckSheduleForI(I);
7754     assert(ScheduleEnd && "tried to vectorize a terminator?");
7755     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7756     return true;
7757   }
7758   // Search up and down at the same time, because we don't know if the new
7759   // instruction is above or below the existing scheduling region.
7760   BasicBlock::reverse_iterator UpIter =
7761       ++ScheduleStart->getIterator().getReverse();
7762   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7763   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7764   BasicBlock::iterator LowerEnd = BB->end();
7765   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7766          &*DownIter != I) {
7767     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7768       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7769       return false;
7770     }
7771 
7772     ++UpIter;
7773     ++DownIter;
7774   }
7775   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7776     assert(I->getParent() == ScheduleStart->getParent() &&
7777            "Instruction is in wrong basic block.");
7778     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7779     ScheduleStart = I;
7780     if (isOneOf(S, I) != I)
7781       CheckSheduleForI(I);
7782     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7783                       << "\n");
7784     return true;
7785   }
7786   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7787          "Expected to reach top of the basic block or instruction down the "
7788          "lower end.");
7789   assert(I->getParent() == ScheduleEnd->getParent() &&
7790          "Instruction is in wrong basic block.");
7791   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7792                    nullptr);
7793   ScheduleEnd = I->getNextNode();
7794   if (isOneOf(S, I) != I)
7795     CheckSheduleForI(I);
7796   assert(ScheduleEnd && "tried to vectorize a terminator?");
7797   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7798   return true;
7799 }
7800 
7801 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7802                                                 Instruction *ToI,
7803                                                 ScheduleData *PrevLoadStore,
7804                                                 ScheduleData *NextLoadStore) {
7805   ScheduleData *CurrentLoadStore = PrevLoadStore;
7806   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7807     ScheduleData *SD = ScheduleDataMap[I];
7808     if (!SD) {
7809       SD = allocateScheduleDataChunks();
7810       ScheduleDataMap[I] = SD;
7811       SD->Inst = I;
7812     }
7813     assert(!isInSchedulingRegion(SD) &&
7814            "new ScheduleData already in scheduling region");
7815     SD->init(SchedulingRegionID, I);
7816 
7817     if (I->mayReadOrWriteMemory() &&
7818         (!isa<IntrinsicInst>(I) ||
7819          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7820           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7821               Intrinsic::pseudoprobe))) {
7822       // Update the linked list of memory accessing instructions.
7823       if (CurrentLoadStore) {
7824         CurrentLoadStore->NextLoadStore = SD;
7825       } else {
7826         FirstLoadStoreInRegion = SD;
7827       }
7828       CurrentLoadStore = SD;
7829     }
7830   }
7831   if (NextLoadStore) {
7832     if (CurrentLoadStore)
7833       CurrentLoadStore->NextLoadStore = NextLoadStore;
7834   } else {
7835     LastLoadStoreInRegion = CurrentLoadStore;
7836   }
7837 }
7838 
7839 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7840                                                      bool InsertInReadyList,
7841                                                      BoUpSLP *SLP) {
7842   assert(SD->isSchedulingEntity());
7843 
7844   SmallVector<ScheduleData *, 10> WorkList;
7845   WorkList.push_back(SD);
7846 
7847   while (!WorkList.empty()) {
7848     ScheduleData *SD = WorkList.pop_back_val();
7849     for (ScheduleData *BundleMember = SD; BundleMember;
7850          BundleMember = BundleMember->NextInBundle) {
7851       assert(isInSchedulingRegion(BundleMember));
7852       if (BundleMember->hasValidDependencies())
7853         continue;
7854 
7855       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7856                  << "\n");
7857       BundleMember->Dependencies = 0;
7858       BundleMember->resetUnscheduledDeps();
7859 
7860       // Handle def-use chain dependencies.
7861       if (BundleMember->OpValue != BundleMember->Inst) {
7862         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
7863           BundleMember->Dependencies++;
7864           ScheduleData *DestBundle = UseSD->FirstInBundle;
7865           if (!DestBundle->IsScheduled)
7866             BundleMember->incrementUnscheduledDeps(1);
7867           if (!DestBundle->hasValidDependencies())
7868             WorkList.push_back(DestBundle);
7869         }
7870       } else {
7871         for (User *U : BundleMember->Inst->users()) {
7872           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
7873             BundleMember->Dependencies++;
7874             ScheduleData *DestBundle = UseSD->FirstInBundle;
7875             if (!DestBundle->IsScheduled)
7876               BundleMember->incrementUnscheduledDeps(1);
7877             if (!DestBundle->hasValidDependencies())
7878               WorkList.push_back(DestBundle);
7879           }
7880         }
7881       }
7882 
7883       // Handle the memory dependencies (if any).
7884       ScheduleData *DepDest = BundleMember->NextLoadStore;
7885       if (!DepDest)
7886         continue;
7887       Instruction *SrcInst = BundleMember->Inst;
7888       assert(SrcInst->mayReadOrWriteMemory() &&
7889              "NextLoadStore list for non memory effecting bundle?");
7890       MemoryLocation SrcLoc = getLocation(SrcInst);
7891       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7892       unsigned numAliased = 0;
7893       unsigned DistToSrc = 1;
7894 
7895       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7896         assert(isInSchedulingRegion(DepDest));
7897 
7898         // We have two limits to reduce the complexity:
7899         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7900         //    SLP->isAliased (which is the expensive part in this loop).
7901         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7902         //    the whole loop (even if the loop is fast, it's quadratic).
7903         //    It's important for the loop break condition (see below) to
7904         //    check this limit even between two read-only instructions.
7905         if (DistToSrc >= MaxMemDepDistance ||
7906             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7907              (numAliased >= AliasedCheckLimit ||
7908               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7909 
7910           // We increment the counter only if the locations are aliased
7911           // (instead of counting all alias checks). This gives a better
7912           // balance between reduced runtime and accurate dependencies.
7913           numAliased++;
7914 
7915           DepDest->MemoryDependencies.push_back(BundleMember);
7916           BundleMember->Dependencies++;
7917           ScheduleData *DestBundle = DepDest->FirstInBundle;
7918           if (!DestBundle->IsScheduled) {
7919             BundleMember->incrementUnscheduledDeps(1);
7920           }
7921           if (!DestBundle->hasValidDependencies()) {
7922             WorkList.push_back(DestBundle);
7923           }
7924         }
7925 
7926         // Example, explaining the loop break condition: Let's assume our
7927         // starting instruction is i0 and MaxMemDepDistance = 3.
7928         //
7929         //                      +--------v--v--v
7930         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7931         //             +--------^--^--^
7932         //
7933         // MaxMemDepDistance let us stop alias-checking at i3 and we add
7934         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7935         // Previously we already added dependencies from i3 to i6,i7,i8
7936         // (because of MaxMemDepDistance). As we added a dependency from
7937         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7938         // and we can abort this loop at i6.
7939         if (DistToSrc >= 2 * MaxMemDepDistance)
7940           break;
7941         DistToSrc++;
7942       }
7943     }
7944     if (InsertInReadyList && SD->isReady()) {
7945       ReadyInsts.insert(SD);
7946       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7947                         << "\n");
7948     }
7949   }
7950 }
7951 
7952 void BoUpSLP::BlockScheduling::resetSchedule() {
7953   assert(ScheduleStart &&
7954          "tried to reset schedule on block which has not been scheduled");
7955   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7956     doForAllOpcodes(I, [&](ScheduleData *SD) {
7957       assert(isInSchedulingRegion(SD) &&
7958              "ScheduleData not in scheduling region");
7959       SD->IsScheduled = false;
7960       SD->resetUnscheduledDeps();
7961     });
7962   }
7963   ReadyInsts.clear();
7964 }
7965 
7966 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7967   if (!BS->ScheduleStart)
7968     return;
7969 
7970   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7971 
7972   // A key point - if we got here, pre-scheduling was able to find a valid
7973   // scheduling of the sub-graph of the scheduling window which consists
7974   // of all vector bundles and their transitive users.  As such, we do not
7975   // need to reschedule anything *outside of* that subgraph.
7976 
7977   BS->resetSchedule();
7978 
7979   // For the real scheduling we use a more sophisticated ready-list: it is
7980   // sorted by the original instruction location. This lets the final schedule
7981   // be as  close as possible to the original instruction order.
7982   DenseMap<ScheduleData *, unsigned> OriginalOrder;
7983   auto ScheduleDataCompare = [&](ScheduleData *SD1, ScheduleData *SD2) {
7984     return OriginalOrder[SD2] < OriginalOrder[SD1];
7985   };
7986   std::set<ScheduleData *, decltype(ScheduleDataCompare)>
7987     ReadyInsts(ScheduleDataCompare);
7988 
7989   // Ensure that all dependency data is updated (for nodes in the sub-graph)
7990   // and fill the ready-list with initial instructions.
7991   int Idx = 0;
7992   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7993        I = I->getNextNode()) {
7994     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
7995       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7996               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7997              "scheduler and vectorizer bundle mismatch");
7998       OriginalOrder[SD->FirstInBundle] = Idx++;
7999 
8000       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8001         BS->calculateDependencies(SD, false, this);
8002     });
8003   }
8004   BS->initialFillReadyList(ReadyInsts);
8005 
8006   Instruction *LastScheduledInst = BS->ScheduleEnd;
8007 
8008   // Do the "real" scheduling.
8009   while (!ReadyInsts.empty()) {
8010     ScheduleData *picked = *ReadyInsts.begin();
8011     ReadyInsts.erase(ReadyInsts.begin());
8012 
8013     // Move the scheduled instruction(s) to their dedicated places, if not
8014     // there yet.
8015     for (ScheduleData *BundleMember = picked; BundleMember;
8016          BundleMember = BundleMember->NextInBundle) {
8017       Instruction *pickedInst = BundleMember->Inst;
8018       if (pickedInst->getNextNode() != LastScheduledInst)
8019         pickedInst->moveBefore(LastScheduledInst);
8020       LastScheduledInst = pickedInst;
8021     }
8022 
8023     BS->schedule(picked, ReadyInsts);
8024   }
8025 
8026   // Check that we didn't break any of our invariants.
8027 #ifdef EXPENSIVE_CHECKS
8028   BS->verify();
8029 #endif
8030 
8031 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8032   // Check that all schedulable entities got scheduled
8033   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8034     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8035       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8036         assert(SD->IsScheduled && "must be scheduled at this point");
8037       }
8038     });
8039   }
8040 #endif
8041 
8042   // Avoid duplicate scheduling of the block.
8043   BS->ScheduleStart = nullptr;
8044 }
8045 
8046 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8047   // If V is a store, just return the width of the stored value (or value
8048   // truncated just before storing) without traversing the expression tree.
8049   // This is the common case.
8050   if (auto *Store = dyn_cast<StoreInst>(V)) {
8051     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8052       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8053     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8054   }
8055 
8056   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8057     return getVectorElementSize(IEI->getOperand(1));
8058 
8059   auto E = InstrElementSize.find(V);
8060   if (E != InstrElementSize.end())
8061     return E->second;
8062 
8063   // If V is not a store, we can traverse the expression tree to find loads
8064   // that feed it. The type of the loaded value may indicate a more suitable
8065   // width than V's type. We want to base the vector element size on the width
8066   // of memory operations where possible.
8067   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8068   SmallPtrSet<Instruction *, 16> Visited;
8069   if (auto *I = dyn_cast<Instruction>(V)) {
8070     Worklist.emplace_back(I, I->getParent());
8071     Visited.insert(I);
8072   }
8073 
8074   // Traverse the expression tree in bottom-up order looking for loads. If we
8075   // encounter an instruction we don't yet handle, we give up.
8076   auto Width = 0u;
8077   while (!Worklist.empty()) {
8078     Instruction *I;
8079     BasicBlock *Parent;
8080     std::tie(I, Parent) = Worklist.pop_back_val();
8081 
8082     // We should only be looking at scalar instructions here. If the current
8083     // instruction has a vector type, skip.
8084     auto *Ty = I->getType();
8085     if (isa<VectorType>(Ty))
8086       continue;
8087 
8088     // If the current instruction is a load, update MaxWidth to reflect the
8089     // width of the loaded value.
8090     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8091         isa<ExtractValueInst>(I))
8092       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8093 
8094     // Otherwise, we need to visit the operands of the instruction. We only
8095     // handle the interesting cases from buildTree here. If an operand is an
8096     // instruction we haven't yet visited and from the same basic block as the
8097     // user or the use is a PHI node, we add it to the worklist.
8098     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8099              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8100              isa<UnaryOperator>(I)) {
8101       for (Use &U : I->operands())
8102         if (auto *J = dyn_cast<Instruction>(U.get()))
8103           if (Visited.insert(J).second &&
8104               (isa<PHINode>(I) || J->getParent() == Parent))
8105             Worklist.emplace_back(J, J->getParent());
8106     } else {
8107       break;
8108     }
8109   }
8110 
8111   // If we didn't encounter a memory access in the expression tree, or if we
8112   // gave up for some reason, just return the width of V. Otherwise, return the
8113   // maximum width we found.
8114   if (!Width) {
8115     if (auto *CI = dyn_cast<CmpInst>(V))
8116       V = CI->getOperand(0);
8117     Width = DL->getTypeSizeInBits(V->getType());
8118   }
8119 
8120   for (Instruction *I : Visited)
8121     InstrElementSize[I] = Width;
8122 
8123   return Width;
8124 }
8125 
8126 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8127 // smaller type with a truncation. We collect the values that will be demoted
8128 // in ToDemote and additional roots that require investigating in Roots.
8129 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8130                                   SmallVectorImpl<Value *> &ToDemote,
8131                                   SmallVectorImpl<Value *> &Roots) {
8132   // We can always demote constants.
8133   if (isa<Constant>(V)) {
8134     ToDemote.push_back(V);
8135     return true;
8136   }
8137 
8138   // If the value is not an instruction in the expression with only one use, it
8139   // cannot be demoted.
8140   auto *I = dyn_cast<Instruction>(V);
8141   if (!I || !I->hasOneUse() || !Expr.count(I))
8142     return false;
8143 
8144   switch (I->getOpcode()) {
8145 
8146   // We can always demote truncations and extensions. Since truncations can
8147   // seed additional demotion, we save the truncated value.
8148   case Instruction::Trunc:
8149     Roots.push_back(I->getOperand(0));
8150     break;
8151   case Instruction::ZExt:
8152   case Instruction::SExt:
8153     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8154         isa<InsertElementInst>(I->getOperand(0)))
8155       return false;
8156     break;
8157 
8158   // We can demote certain binary operations if we can demote both of their
8159   // operands.
8160   case Instruction::Add:
8161   case Instruction::Sub:
8162   case Instruction::Mul:
8163   case Instruction::And:
8164   case Instruction::Or:
8165   case Instruction::Xor:
8166     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8167         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8168       return false;
8169     break;
8170 
8171   // We can demote selects if we can demote their true and false values.
8172   case Instruction::Select: {
8173     SelectInst *SI = cast<SelectInst>(I);
8174     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8175         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8176       return false;
8177     break;
8178   }
8179 
8180   // We can demote phis if we can demote all their incoming operands. Note that
8181   // we don't need to worry about cycles since we ensure single use above.
8182   case Instruction::PHI: {
8183     PHINode *PN = cast<PHINode>(I);
8184     for (Value *IncValue : PN->incoming_values())
8185       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8186         return false;
8187     break;
8188   }
8189 
8190   // Otherwise, conservatively give up.
8191   default:
8192     return false;
8193   }
8194 
8195   // Record the value that we can demote.
8196   ToDemote.push_back(V);
8197   return true;
8198 }
8199 
8200 void BoUpSLP::computeMinimumValueSizes() {
8201   // If there are no external uses, the expression tree must be rooted by a
8202   // store. We can't demote in-memory values, so there is nothing to do here.
8203   if (ExternalUses.empty())
8204     return;
8205 
8206   // We only attempt to truncate integer expressions.
8207   auto &TreeRoot = VectorizableTree[0]->Scalars;
8208   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8209   if (!TreeRootIT)
8210     return;
8211 
8212   // If the expression is not rooted by a store, these roots should have
8213   // external uses. We will rely on InstCombine to rewrite the expression in
8214   // the narrower type. However, InstCombine only rewrites single-use values.
8215   // This means that if a tree entry other than a root is used externally, it
8216   // must have multiple uses and InstCombine will not rewrite it. The code
8217   // below ensures that only the roots are used externally.
8218   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8219   for (auto &EU : ExternalUses)
8220     if (!Expr.erase(EU.Scalar))
8221       return;
8222   if (!Expr.empty())
8223     return;
8224 
8225   // Collect the scalar values of the vectorizable expression. We will use this
8226   // context to determine which values can be demoted. If we see a truncation,
8227   // we mark it as seeding another demotion.
8228   for (auto &EntryPtr : VectorizableTree)
8229     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8230 
8231   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8232   // have a single external user that is not in the vectorizable tree.
8233   for (auto *Root : TreeRoot)
8234     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8235       return;
8236 
8237   // Conservatively determine if we can actually truncate the roots of the
8238   // expression. Collect the values that can be demoted in ToDemote and
8239   // additional roots that require investigating in Roots.
8240   SmallVector<Value *, 32> ToDemote;
8241   SmallVector<Value *, 4> Roots;
8242   for (auto *Root : TreeRoot)
8243     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8244       return;
8245 
8246   // The maximum bit width required to represent all the values that can be
8247   // demoted without loss of precision. It would be safe to truncate the roots
8248   // of the expression to this width.
8249   auto MaxBitWidth = 8u;
8250 
8251   // We first check if all the bits of the roots are demanded. If they're not,
8252   // we can truncate the roots to this narrower type.
8253   for (auto *Root : TreeRoot) {
8254     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8255     MaxBitWidth = std::max<unsigned>(
8256         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8257   }
8258 
8259   // True if the roots can be zero-extended back to their original type, rather
8260   // than sign-extended. We know that if the leading bits are not demanded, we
8261   // can safely zero-extend. So we initialize IsKnownPositive to True.
8262   bool IsKnownPositive = true;
8263 
8264   // If all the bits of the roots are demanded, we can try a little harder to
8265   // compute a narrower type. This can happen, for example, if the roots are
8266   // getelementptr indices. InstCombine promotes these indices to the pointer
8267   // width. Thus, all their bits are technically demanded even though the
8268   // address computation might be vectorized in a smaller type.
8269   //
8270   // We start by looking at each entry that can be demoted. We compute the
8271   // maximum bit width required to store the scalar by using ValueTracking to
8272   // compute the number of high-order bits we can truncate.
8273   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8274       llvm::all_of(TreeRoot, [](Value *R) {
8275         assert(R->hasOneUse() && "Root should have only one use!");
8276         return isa<GetElementPtrInst>(R->user_back());
8277       })) {
8278     MaxBitWidth = 8u;
8279 
8280     // Determine if the sign bit of all the roots is known to be zero. If not,
8281     // IsKnownPositive is set to False.
8282     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8283       KnownBits Known = computeKnownBits(R, *DL);
8284       return Known.isNonNegative();
8285     });
8286 
8287     // Determine the maximum number of bits required to store the scalar
8288     // values.
8289     for (auto *Scalar : ToDemote) {
8290       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8291       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8292       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8293     }
8294 
8295     // If we can't prove that the sign bit is zero, we must add one to the
8296     // maximum bit width to account for the unknown sign bit. This preserves
8297     // the existing sign bit so we can safely sign-extend the root back to the
8298     // original type. Otherwise, if we know the sign bit is zero, we will
8299     // zero-extend the root instead.
8300     //
8301     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8302     //        one to the maximum bit width will yield a larger-than-necessary
8303     //        type. In general, we need to add an extra bit only if we can't
8304     //        prove that the upper bit of the original type is equal to the
8305     //        upper bit of the proposed smaller type. If these two bits are the
8306     //        same (either zero or one) we know that sign-extending from the
8307     //        smaller type will result in the same value. Here, since we can't
8308     //        yet prove this, we are just making the proposed smaller type
8309     //        larger to ensure correctness.
8310     if (!IsKnownPositive)
8311       ++MaxBitWidth;
8312   }
8313 
8314   // Round MaxBitWidth up to the next power-of-two.
8315   if (!isPowerOf2_64(MaxBitWidth))
8316     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8317 
8318   // If the maximum bit width we compute is less than the with of the roots'
8319   // type, we can proceed with the narrowing. Otherwise, do nothing.
8320   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8321     return;
8322 
8323   // If we can truncate the root, we must collect additional values that might
8324   // be demoted as a result. That is, those seeded by truncations we will
8325   // modify.
8326   while (!Roots.empty())
8327     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8328 
8329   // Finally, map the values we can demote to the maximum bit with we computed.
8330   for (auto *Scalar : ToDemote)
8331     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8332 }
8333 
8334 namespace {
8335 
8336 /// The SLPVectorizer Pass.
8337 struct SLPVectorizer : public FunctionPass {
8338   SLPVectorizerPass Impl;
8339 
8340   /// Pass identification, replacement for typeid
8341   static char ID;
8342 
8343   explicit SLPVectorizer() : FunctionPass(ID) {
8344     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8345   }
8346 
8347   bool doInitialization(Module &M) override { return false; }
8348 
8349   bool runOnFunction(Function &F) override {
8350     if (skipFunction(F))
8351       return false;
8352 
8353     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8354     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8355     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8356     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8357     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8358     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8359     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8360     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8361     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8362     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8363 
8364     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8365   }
8366 
8367   void getAnalysisUsage(AnalysisUsage &AU) const override {
8368     FunctionPass::getAnalysisUsage(AU);
8369     AU.addRequired<AssumptionCacheTracker>();
8370     AU.addRequired<ScalarEvolutionWrapperPass>();
8371     AU.addRequired<AAResultsWrapperPass>();
8372     AU.addRequired<TargetTransformInfoWrapperPass>();
8373     AU.addRequired<LoopInfoWrapperPass>();
8374     AU.addRequired<DominatorTreeWrapperPass>();
8375     AU.addRequired<DemandedBitsWrapperPass>();
8376     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8377     AU.addRequired<InjectTLIMappingsLegacy>();
8378     AU.addPreserved<LoopInfoWrapperPass>();
8379     AU.addPreserved<DominatorTreeWrapperPass>();
8380     AU.addPreserved<AAResultsWrapperPass>();
8381     AU.addPreserved<GlobalsAAWrapperPass>();
8382     AU.setPreservesCFG();
8383   }
8384 };
8385 
8386 } // end anonymous namespace
8387 
8388 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8389   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8390   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8391   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8392   auto *AA = &AM.getResult<AAManager>(F);
8393   auto *LI = &AM.getResult<LoopAnalysis>(F);
8394   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8395   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8396   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8397   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8398 
8399   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8400   if (!Changed)
8401     return PreservedAnalyses::all();
8402 
8403   PreservedAnalyses PA;
8404   PA.preserveSet<CFGAnalyses>();
8405   return PA;
8406 }
8407 
8408 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8409                                 TargetTransformInfo *TTI_,
8410                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8411                                 LoopInfo *LI_, DominatorTree *DT_,
8412                                 AssumptionCache *AC_, DemandedBits *DB_,
8413                                 OptimizationRemarkEmitter *ORE_) {
8414   if (!RunSLPVectorization)
8415     return false;
8416   SE = SE_;
8417   TTI = TTI_;
8418   TLI = TLI_;
8419   AA = AA_;
8420   LI = LI_;
8421   DT = DT_;
8422   AC = AC_;
8423   DB = DB_;
8424   DL = &F.getParent()->getDataLayout();
8425 
8426   Stores.clear();
8427   GEPs.clear();
8428   bool Changed = false;
8429 
8430   // If the target claims to have no vector registers don't attempt
8431   // vectorization.
8432   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8433     LLVM_DEBUG(
8434         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8435     return false;
8436   }
8437 
8438   // Don't vectorize when the attribute NoImplicitFloat is used.
8439   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8440     return false;
8441 
8442   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8443 
8444   // Use the bottom up slp vectorizer to construct chains that start with
8445   // store instructions.
8446   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8447 
8448   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8449   // delete instructions.
8450 
8451   // Update DFS numbers now so that we can use them for ordering.
8452   DT->updateDFSNumbers();
8453 
8454   // Scan the blocks in the function in post order.
8455   for (auto BB : post_order(&F.getEntryBlock())) {
8456     collectSeedInstructions(BB);
8457 
8458     // Vectorize trees that end at stores.
8459     if (!Stores.empty()) {
8460       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8461                         << " underlying objects.\n");
8462       Changed |= vectorizeStoreChains(R);
8463     }
8464 
8465     // Vectorize trees that end at reductions.
8466     Changed |= vectorizeChainsInBlock(BB, R);
8467 
8468     // Vectorize the index computations of getelementptr instructions. This
8469     // is primarily intended to catch gather-like idioms ending at
8470     // non-consecutive loads.
8471     if (!GEPs.empty()) {
8472       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8473                         << " underlying objects.\n");
8474       Changed |= vectorizeGEPIndices(BB, R);
8475     }
8476   }
8477 
8478   if (Changed) {
8479     R.optimizeGatherSequence();
8480     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8481   }
8482   return Changed;
8483 }
8484 
8485 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8486                                             unsigned Idx) {
8487   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8488                     << "\n");
8489   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8490   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8491   unsigned VF = Chain.size();
8492 
8493   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8494     return false;
8495 
8496   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8497                     << "\n");
8498 
8499   R.buildTree(Chain);
8500   if (R.isTreeTinyAndNotFullyVectorizable())
8501     return false;
8502   if (R.isLoadCombineCandidate())
8503     return false;
8504   R.reorderTopToBottom();
8505   R.reorderBottomToTop();
8506   R.buildExternalUses();
8507 
8508   R.computeMinimumValueSizes();
8509 
8510   InstructionCost Cost = R.getTreeCost();
8511 
8512   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8513   if (Cost < -SLPCostThreshold) {
8514     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8515 
8516     using namespace ore;
8517 
8518     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8519                                         cast<StoreInst>(Chain[0]))
8520                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8521                      << " and with tree size "
8522                      << NV("TreeSize", R.getTreeSize()));
8523 
8524     R.vectorizeTree();
8525     return true;
8526   }
8527 
8528   return false;
8529 }
8530 
8531 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8532                                         BoUpSLP &R) {
8533   // We may run into multiple chains that merge into a single chain. We mark the
8534   // stores that we vectorized so that we don't visit the same store twice.
8535   BoUpSLP::ValueSet VectorizedStores;
8536   bool Changed = false;
8537 
8538   int E = Stores.size();
8539   SmallBitVector Tails(E, false);
8540   int MaxIter = MaxStoreLookup.getValue();
8541   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8542       E, std::make_pair(E, INT_MAX));
8543   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8544   int IterCnt;
8545   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8546                                   &CheckedPairs,
8547                                   &ConsecutiveChain](int K, int Idx) {
8548     if (IterCnt >= MaxIter)
8549       return true;
8550     if (CheckedPairs[Idx].test(K))
8551       return ConsecutiveChain[K].second == 1 &&
8552              ConsecutiveChain[K].first == Idx;
8553     ++IterCnt;
8554     CheckedPairs[Idx].set(K);
8555     CheckedPairs[K].set(Idx);
8556     Optional<int> Diff = getPointersDiff(
8557         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8558         Stores[Idx]->getValueOperand()->getType(),
8559         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8560     if (!Diff || *Diff == 0)
8561       return false;
8562     int Val = *Diff;
8563     if (Val < 0) {
8564       if (ConsecutiveChain[Idx].second > -Val) {
8565         Tails.set(K);
8566         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8567       }
8568       return false;
8569     }
8570     if (ConsecutiveChain[K].second <= Val)
8571       return false;
8572 
8573     Tails.set(Idx);
8574     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8575     return Val == 1;
8576   };
8577   // Do a quadratic search on all of the given stores in reverse order and find
8578   // all of the pairs of stores that follow each other.
8579   for (int Idx = E - 1; Idx >= 0; --Idx) {
8580     // If a store has multiple consecutive store candidates, search according
8581     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8582     // This is because usually pairing with immediate succeeding or preceding
8583     // candidate create the best chance to find slp vectorization opportunity.
8584     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8585     IterCnt = 0;
8586     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8587       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8588           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8589         break;
8590   }
8591 
8592   // Tracks if we tried to vectorize stores starting from the given tail
8593   // already.
8594   SmallBitVector TriedTails(E, false);
8595   // For stores that start but don't end a link in the chain:
8596   for (int Cnt = E; Cnt > 0; --Cnt) {
8597     int I = Cnt - 1;
8598     if (ConsecutiveChain[I].first == E || Tails.test(I))
8599       continue;
8600     // We found a store instr that starts a chain. Now follow the chain and try
8601     // to vectorize it.
8602     BoUpSLP::ValueList Operands;
8603     // Collect the chain into a list.
8604     while (I != E && !VectorizedStores.count(Stores[I])) {
8605       Operands.push_back(Stores[I]);
8606       Tails.set(I);
8607       if (ConsecutiveChain[I].second != 1) {
8608         // Mark the new end in the chain and go back, if required. It might be
8609         // required if the original stores come in reversed order, for example.
8610         if (ConsecutiveChain[I].first != E &&
8611             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8612             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8613           TriedTails.set(I);
8614           Tails.reset(ConsecutiveChain[I].first);
8615           if (Cnt < ConsecutiveChain[I].first + 2)
8616             Cnt = ConsecutiveChain[I].first + 2;
8617         }
8618         break;
8619       }
8620       // Move to the next value in the chain.
8621       I = ConsecutiveChain[I].first;
8622     }
8623     assert(!Operands.empty() && "Expected non-empty list of stores.");
8624 
8625     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8626     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8627     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8628 
8629     unsigned MinVF = R.getMinVF(EltSize);
8630     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8631                               MaxElts);
8632 
8633     // FIXME: Is division-by-2 the correct step? Should we assert that the
8634     // register size is a power-of-2?
8635     unsigned StartIdx = 0;
8636     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8637       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8638         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8639         if (!VectorizedStores.count(Slice.front()) &&
8640             !VectorizedStores.count(Slice.back()) &&
8641             vectorizeStoreChain(Slice, R, Cnt)) {
8642           // Mark the vectorized stores so that we don't vectorize them again.
8643           VectorizedStores.insert(Slice.begin(), Slice.end());
8644           Changed = true;
8645           // If we vectorized initial block, no need to try to vectorize it
8646           // again.
8647           if (Cnt == StartIdx)
8648             StartIdx += Size;
8649           Cnt += Size;
8650           continue;
8651         }
8652         ++Cnt;
8653       }
8654       // Check if the whole array was vectorized already - exit.
8655       if (StartIdx >= Operands.size())
8656         break;
8657     }
8658   }
8659 
8660   return Changed;
8661 }
8662 
8663 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8664   // Initialize the collections. We will make a single pass over the block.
8665   Stores.clear();
8666   GEPs.clear();
8667 
8668   // Visit the store and getelementptr instructions in BB and organize them in
8669   // Stores and GEPs according to the underlying objects of their pointer
8670   // operands.
8671   for (Instruction &I : *BB) {
8672     // Ignore store instructions that are volatile or have a pointer operand
8673     // that doesn't point to a scalar type.
8674     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8675       if (!SI->isSimple())
8676         continue;
8677       if (!isValidElementType(SI->getValueOperand()->getType()))
8678         continue;
8679       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8680     }
8681 
8682     // Ignore getelementptr instructions that have more than one index, a
8683     // constant index, or a pointer operand that doesn't point to a scalar
8684     // type.
8685     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8686       auto Idx = GEP->idx_begin()->get();
8687       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8688         continue;
8689       if (!isValidElementType(Idx->getType()))
8690         continue;
8691       if (GEP->getType()->isVectorTy())
8692         continue;
8693       GEPs[GEP->getPointerOperand()].push_back(GEP);
8694     }
8695   }
8696 }
8697 
8698 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8699   if (!A || !B)
8700     return false;
8701   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8702     return false;
8703   Value *VL[] = {A, B};
8704   return tryToVectorizeList(VL, R);
8705 }
8706 
8707 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8708                                            bool LimitForRegisterSize) {
8709   if (VL.size() < 2)
8710     return false;
8711 
8712   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8713                     << VL.size() << ".\n");
8714 
8715   // Check that all of the parts are instructions of the same type,
8716   // we permit an alternate opcode via InstructionsState.
8717   InstructionsState S = getSameOpcode(VL);
8718   if (!S.getOpcode())
8719     return false;
8720 
8721   Instruction *I0 = cast<Instruction>(S.OpValue);
8722   // Make sure invalid types (including vector type) are rejected before
8723   // determining vectorization factor for scalar instructions.
8724   for (Value *V : VL) {
8725     Type *Ty = V->getType();
8726     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8727       // NOTE: the following will give user internal llvm type name, which may
8728       // not be useful.
8729       R.getORE()->emit([&]() {
8730         std::string type_str;
8731         llvm::raw_string_ostream rso(type_str);
8732         Ty->print(rso);
8733         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8734                << "Cannot SLP vectorize list: type "
8735                << rso.str() + " is unsupported by vectorizer";
8736       });
8737       return false;
8738     }
8739   }
8740 
8741   unsigned Sz = R.getVectorElementSize(I0);
8742   unsigned MinVF = R.getMinVF(Sz);
8743   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8744   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8745   if (MaxVF < 2) {
8746     R.getORE()->emit([&]() {
8747       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8748              << "Cannot SLP vectorize list: vectorization factor "
8749              << "less than 2 is not supported";
8750     });
8751     return false;
8752   }
8753 
8754   bool Changed = false;
8755   bool CandidateFound = false;
8756   InstructionCost MinCost = SLPCostThreshold.getValue();
8757   Type *ScalarTy = VL[0]->getType();
8758   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8759     ScalarTy = IE->getOperand(1)->getType();
8760 
8761   unsigned NextInst = 0, MaxInst = VL.size();
8762   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8763     // No actual vectorization should happen, if number of parts is the same as
8764     // provided vectorization factor (i.e. the scalar type is used for vector
8765     // code during codegen).
8766     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8767     if (TTI->getNumberOfParts(VecTy) == VF)
8768       continue;
8769     for (unsigned I = NextInst; I < MaxInst; ++I) {
8770       unsigned OpsWidth = 0;
8771 
8772       if (I + VF > MaxInst)
8773         OpsWidth = MaxInst - I;
8774       else
8775         OpsWidth = VF;
8776 
8777       if (!isPowerOf2_32(OpsWidth))
8778         continue;
8779 
8780       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8781           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8782         break;
8783 
8784       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8785       // Check that a previous iteration of this loop did not delete the Value.
8786       if (llvm::any_of(Ops, [&R](Value *V) {
8787             auto *I = dyn_cast<Instruction>(V);
8788             return I && R.isDeleted(I);
8789           }))
8790         continue;
8791 
8792       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8793                         << "\n");
8794 
8795       R.buildTree(Ops);
8796       if (R.isTreeTinyAndNotFullyVectorizable())
8797         continue;
8798       R.reorderTopToBottom();
8799       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
8800       R.buildExternalUses();
8801 
8802       R.computeMinimumValueSizes();
8803       InstructionCost Cost = R.getTreeCost();
8804       CandidateFound = true;
8805       MinCost = std::min(MinCost, Cost);
8806 
8807       if (Cost < -SLPCostThreshold) {
8808         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8809         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8810                                                     cast<Instruction>(Ops[0]))
8811                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8812                                  << " and with tree size "
8813                                  << ore::NV("TreeSize", R.getTreeSize()));
8814 
8815         R.vectorizeTree();
8816         // Move to the next bundle.
8817         I += VF - 1;
8818         NextInst = I + 1;
8819         Changed = true;
8820       }
8821     }
8822   }
8823 
8824   if (!Changed && CandidateFound) {
8825     R.getORE()->emit([&]() {
8826       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8827              << "List vectorization was possible but not beneficial with cost "
8828              << ore::NV("Cost", MinCost) << " >= "
8829              << ore::NV("Treshold", -SLPCostThreshold);
8830     });
8831   } else if (!Changed) {
8832     R.getORE()->emit([&]() {
8833       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8834              << "Cannot SLP vectorize list: vectorization was impossible"
8835              << " with available vectorization factors";
8836     });
8837   }
8838   return Changed;
8839 }
8840 
8841 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8842   if (!I)
8843     return false;
8844 
8845   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8846     return false;
8847 
8848   Value *P = I->getParent();
8849 
8850   // Vectorize in current basic block only.
8851   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8852   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8853   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8854     return false;
8855 
8856   // Try to vectorize V.
8857   if (tryToVectorizePair(Op0, Op1, R))
8858     return true;
8859 
8860   auto *A = dyn_cast<BinaryOperator>(Op0);
8861   auto *B = dyn_cast<BinaryOperator>(Op1);
8862   // Try to skip B.
8863   if (B && B->hasOneUse()) {
8864     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8865     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8866     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8867       return true;
8868     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8869       return true;
8870   }
8871 
8872   // Try to skip A.
8873   if (A && A->hasOneUse()) {
8874     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8875     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8876     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8877       return true;
8878     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8879       return true;
8880   }
8881   return false;
8882 }
8883 
8884 namespace {
8885 
8886 /// Model horizontal reductions.
8887 ///
8888 /// A horizontal reduction is a tree of reduction instructions that has values
8889 /// that can be put into a vector as its leaves. For example:
8890 ///
8891 /// mul mul mul mul
8892 ///  \  /    \  /
8893 ///   +       +
8894 ///    \     /
8895 ///       +
8896 /// This tree has "mul" as its leaf values and "+" as its reduction
8897 /// instructions. A reduction can feed into a store or a binary operation
8898 /// feeding a phi.
8899 ///    ...
8900 ///    \  /
8901 ///     +
8902 ///     |
8903 ///  phi +=
8904 ///
8905 ///  Or:
8906 ///    ...
8907 ///    \  /
8908 ///     +
8909 ///     |
8910 ///   *p =
8911 ///
8912 class HorizontalReduction {
8913   using ReductionOpsType = SmallVector<Value *, 16>;
8914   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8915   ReductionOpsListType ReductionOps;
8916   SmallVector<Value *, 32> ReducedVals;
8917   // Use map vector to make stable output.
8918   MapVector<Instruction *, Value *> ExtraArgs;
8919   WeakTrackingVH ReductionRoot;
8920   /// The type of reduction operation.
8921   RecurKind RdxKind;
8922 
8923   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8924 
8925   static bool isCmpSelMinMax(Instruction *I) {
8926     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8927            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8928   }
8929 
8930   // And/or are potentially poison-safe logical patterns like:
8931   // select x, y, false
8932   // select x, true, y
8933   static bool isBoolLogicOp(Instruction *I) {
8934     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8935            match(I, m_LogicalOr(m_Value(), m_Value()));
8936   }
8937 
8938   /// Checks if instruction is associative and can be vectorized.
8939   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8940     if (Kind == RecurKind::None)
8941       return false;
8942 
8943     // Integer ops that map to select instructions or intrinsics are fine.
8944     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8945         isBoolLogicOp(I))
8946       return true;
8947 
8948     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8949       // FP min/max are associative except for NaN and -0.0. We do not
8950       // have to rule out -0.0 here because the intrinsic semantics do not
8951       // specify a fixed result for it.
8952       return I->getFastMathFlags().noNaNs();
8953     }
8954 
8955     return I->isAssociative();
8956   }
8957 
8958   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8959     // Poison-safe 'or' takes the form: select X, true, Y
8960     // To make that work with the normal operand processing, we skip the
8961     // true value operand.
8962     // TODO: Change the code and data structures to handle this without a hack.
8963     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8964       return I->getOperand(2);
8965     return I->getOperand(Index);
8966   }
8967 
8968   /// Checks if the ParentStackElem.first should be marked as a reduction
8969   /// operation with an extra argument or as extra argument itself.
8970   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8971                     Value *ExtraArg) {
8972     if (ExtraArgs.count(ParentStackElem.first)) {
8973       ExtraArgs[ParentStackElem.first] = nullptr;
8974       // We ran into something like:
8975       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8976       // The whole ParentStackElem.first should be considered as an extra value
8977       // in this case.
8978       // Do not perform analysis of remaining operands of ParentStackElem.first
8979       // instruction, this whole instruction is an extra argument.
8980       ParentStackElem.second = INVALID_OPERAND_INDEX;
8981     } else {
8982       // We ran into something like:
8983       // ParentStackElem.first += ... + ExtraArg + ...
8984       ExtraArgs[ParentStackElem.first] = ExtraArg;
8985     }
8986   }
8987 
8988   /// Creates reduction operation with the current opcode.
8989   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8990                          Value *RHS, const Twine &Name, bool UseSelect) {
8991     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8992     switch (Kind) {
8993     case RecurKind::Or:
8994       if (UseSelect &&
8995           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8996         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8997       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8998                                  Name);
8999     case RecurKind::And:
9000       if (UseSelect &&
9001           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9002         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9003       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9004                                  Name);
9005     case RecurKind::Add:
9006     case RecurKind::Mul:
9007     case RecurKind::Xor:
9008     case RecurKind::FAdd:
9009     case RecurKind::FMul:
9010       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9011                                  Name);
9012     case RecurKind::FMax:
9013       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9014     case RecurKind::FMin:
9015       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9016     case RecurKind::SMax:
9017       if (UseSelect) {
9018         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9019         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9020       }
9021       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9022     case RecurKind::SMin:
9023       if (UseSelect) {
9024         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9025         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9026       }
9027       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9028     case RecurKind::UMax:
9029       if (UseSelect) {
9030         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9031         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9032       }
9033       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9034     case RecurKind::UMin:
9035       if (UseSelect) {
9036         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9037         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9038       }
9039       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9040     default:
9041       llvm_unreachable("Unknown reduction operation.");
9042     }
9043   }
9044 
9045   /// Creates reduction operation with the current opcode with the IR flags
9046   /// from \p ReductionOps.
9047   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9048                          Value *RHS, const Twine &Name,
9049                          const ReductionOpsListType &ReductionOps) {
9050     bool UseSelect = ReductionOps.size() == 2 ||
9051                      // Logical or/and.
9052                      (ReductionOps.size() == 1 &&
9053                       isa<SelectInst>(ReductionOps.front().front()));
9054     assert((!UseSelect || ReductionOps.size() != 2 ||
9055             isa<SelectInst>(ReductionOps[1][0])) &&
9056            "Expected cmp + select pairs for reduction");
9057     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9058     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9059       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9060         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9061         propagateIRFlags(Op, ReductionOps[1]);
9062         return Op;
9063       }
9064     }
9065     propagateIRFlags(Op, ReductionOps[0]);
9066     return Op;
9067   }
9068 
9069   /// Creates reduction operation with the current opcode with the IR flags
9070   /// from \p I.
9071   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9072                          Value *RHS, const Twine &Name, Instruction *I) {
9073     auto *SelI = dyn_cast<SelectInst>(I);
9074     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9075     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9076       if (auto *Sel = dyn_cast<SelectInst>(Op))
9077         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9078     }
9079     propagateIRFlags(Op, I);
9080     return Op;
9081   }
9082 
9083   static RecurKind getRdxKind(Instruction *I) {
9084     assert(I && "Expected instruction for reduction matching");
9085     if (match(I, m_Add(m_Value(), m_Value())))
9086       return RecurKind::Add;
9087     if (match(I, m_Mul(m_Value(), m_Value())))
9088       return RecurKind::Mul;
9089     if (match(I, m_And(m_Value(), m_Value())) ||
9090         match(I, m_LogicalAnd(m_Value(), m_Value())))
9091       return RecurKind::And;
9092     if (match(I, m_Or(m_Value(), m_Value())) ||
9093         match(I, m_LogicalOr(m_Value(), m_Value())))
9094       return RecurKind::Or;
9095     if (match(I, m_Xor(m_Value(), m_Value())))
9096       return RecurKind::Xor;
9097     if (match(I, m_FAdd(m_Value(), m_Value())))
9098       return RecurKind::FAdd;
9099     if (match(I, m_FMul(m_Value(), m_Value())))
9100       return RecurKind::FMul;
9101 
9102     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9103       return RecurKind::FMax;
9104     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9105       return RecurKind::FMin;
9106 
9107     // This matches either cmp+select or intrinsics. SLP is expected to handle
9108     // either form.
9109     // TODO: If we are canonicalizing to intrinsics, we can remove several
9110     //       special-case paths that deal with selects.
9111     if (match(I, m_SMax(m_Value(), m_Value())))
9112       return RecurKind::SMax;
9113     if (match(I, m_SMin(m_Value(), m_Value())))
9114       return RecurKind::SMin;
9115     if (match(I, m_UMax(m_Value(), m_Value())))
9116       return RecurKind::UMax;
9117     if (match(I, m_UMin(m_Value(), m_Value())))
9118       return RecurKind::UMin;
9119 
9120     if (auto *Select = dyn_cast<SelectInst>(I)) {
9121       // Try harder: look for min/max pattern based on instructions producing
9122       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9123       // During the intermediate stages of SLP, it's very common to have
9124       // pattern like this (since optimizeGatherSequence is run only once
9125       // at the end):
9126       // %1 = extractelement <2 x i32> %a, i32 0
9127       // %2 = extractelement <2 x i32> %a, i32 1
9128       // %cond = icmp sgt i32 %1, %2
9129       // %3 = extractelement <2 x i32> %a, i32 0
9130       // %4 = extractelement <2 x i32> %a, i32 1
9131       // %select = select i1 %cond, i32 %3, i32 %4
9132       CmpInst::Predicate Pred;
9133       Instruction *L1;
9134       Instruction *L2;
9135 
9136       Value *LHS = Select->getTrueValue();
9137       Value *RHS = Select->getFalseValue();
9138       Value *Cond = Select->getCondition();
9139 
9140       // TODO: Support inverse predicates.
9141       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9142         if (!isa<ExtractElementInst>(RHS) ||
9143             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9144           return RecurKind::None;
9145       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9146         if (!isa<ExtractElementInst>(LHS) ||
9147             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9148           return RecurKind::None;
9149       } else {
9150         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9151           return RecurKind::None;
9152         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9153             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9154             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9155           return RecurKind::None;
9156       }
9157 
9158       switch (Pred) {
9159       default:
9160         return RecurKind::None;
9161       case CmpInst::ICMP_SGT:
9162       case CmpInst::ICMP_SGE:
9163         return RecurKind::SMax;
9164       case CmpInst::ICMP_SLT:
9165       case CmpInst::ICMP_SLE:
9166         return RecurKind::SMin;
9167       case CmpInst::ICMP_UGT:
9168       case CmpInst::ICMP_UGE:
9169         return RecurKind::UMax;
9170       case CmpInst::ICMP_ULT:
9171       case CmpInst::ICMP_ULE:
9172         return RecurKind::UMin;
9173       }
9174     }
9175     return RecurKind::None;
9176   }
9177 
9178   /// Get the index of the first operand.
9179   static unsigned getFirstOperandIndex(Instruction *I) {
9180     return isCmpSelMinMax(I) ? 1 : 0;
9181   }
9182 
9183   /// Total number of operands in the reduction operation.
9184   static unsigned getNumberOfOperands(Instruction *I) {
9185     return isCmpSelMinMax(I) ? 3 : 2;
9186   }
9187 
9188   /// Checks if the instruction is in basic block \p BB.
9189   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9190   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9191     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9192       auto *Sel = cast<SelectInst>(I);
9193       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9194       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9195     }
9196     return I->getParent() == BB;
9197   }
9198 
9199   /// Expected number of uses for reduction operations/reduced values.
9200   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9201     if (IsCmpSelMinMax) {
9202       // SelectInst must be used twice while the condition op must have single
9203       // use only.
9204       if (auto *Sel = dyn_cast<SelectInst>(I))
9205         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9206       return I->hasNUses(2);
9207     }
9208 
9209     // Arithmetic reduction operation must be used once only.
9210     return I->hasOneUse();
9211   }
9212 
9213   /// Initializes the list of reduction operations.
9214   void initReductionOps(Instruction *I) {
9215     if (isCmpSelMinMax(I))
9216       ReductionOps.assign(2, ReductionOpsType());
9217     else
9218       ReductionOps.assign(1, ReductionOpsType());
9219   }
9220 
9221   /// Add all reduction operations for the reduction instruction \p I.
9222   void addReductionOps(Instruction *I) {
9223     if (isCmpSelMinMax(I)) {
9224       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9225       ReductionOps[1].emplace_back(I);
9226     } else {
9227       ReductionOps[0].emplace_back(I);
9228     }
9229   }
9230 
9231   static Value *getLHS(RecurKind Kind, Instruction *I) {
9232     if (Kind == RecurKind::None)
9233       return nullptr;
9234     return I->getOperand(getFirstOperandIndex(I));
9235   }
9236   static Value *getRHS(RecurKind Kind, Instruction *I) {
9237     if (Kind == RecurKind::None)
9238       return nullptr;
9239     return I->getOperand(getFirstOperandIndex(I) + 1);
9240   }
9241 
9242 public:
9243   HorizontalReduction() = default;
9244 
9245   /// Try to find a reduction tree.
9246   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9247     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9248            "Phi needs to use the binary operator");
9249     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9250             isa<IntrinsicInst>(Inst)) &&
9251            "Expected binop, select, or intrinsic for reduction matching");
9252     RdxKind = getRdxKind(Inst);
9253 
9254     // We could have a initial reductions that is not an add.
9255     //  r *= v1 + v2 + v3 + v4
9256     // In such a case start looking for a tree rooted in the first '+'.
9257     if (Phi) {
9258       if (getLHS(RdxKind, Inst) == Phi) {
9259         Phi = nullptr;
9260         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9261         if (!Inst)
9262           return false;
9263         RdxKind = getRdxKind(Inst);
9264       } else if (getRHS(RdxKind, Inst) == Phi) {
9265         Phi = nullptr;
9266         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9267         if (!Inst)
9268           return false;
9269         RdxKind = getRdxKind(Inst);
9270       }
9271     }
9272 
9273     if (!isVectorizable(RdxKind, Inst))
9274       return false;
9275 
9276     // Analyze "regular" integer/FP types for reductions - no target-specific
9277     // types or pointers.
9278     Type *Ty = Inst->getType();
9279     if (!isValidElementType(Ty) || Ty->isPointerTy())
9280       return false;
9281 
9282     // Though the ultimate reduction may have multiple uses, its condition must
9283     // have only single use.
9284     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9285       if (!Sel->getCondition()->hasOneUse())
9286         return false;
9287 
9288     ReductionRoot = Inst;
9289 
9290     // The opcode for leaf values that we perform a reduction on.
9291     // For example: load(x) + load(y) + load(z) + fptoui(w)
9292     // The leaf opcode for 'w' does not match, so we don't include it as a
9293     // potential candidate for the reduction.
9294     unsigned LeafOpcode = 0;
9295 
9296     // Post-order traverse the reduction tree starting at Inst. We only handle
9297     // true trees containing binary operators or selects.
9298     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9299     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9300     initReductionOps(Inst);
9301     while (!Stack.empty()) {
9302       Instruction *TreeN = Stack.back().first;
9303       unsigned EdgeToVisit = Stack.back().second++;
9304       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9305       bool IsReducedValue = TreeRdxKind != RdxKind;
9306 
9307       // Postorder visit.
9308       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9309         if (IsReducedValue)
9310           ReducedVals.push_back(TreeN);
9311         else {
9312           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9313           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9314             // Check if TreeN is an extra argument of its parent operation.
9315             if (Stack.size() <= 1) {
9316               // TreeN can't be an extra argument as it is a root reduction
9317               // operation.
9318               return false;
9319             }
9320             // Yes, TreeN is an extra argument, do not add it to a list of
9321             // reduction operations.
9322             // Stack[Stack.size() - 2] always points to the parent operation.
9323             markExtraArg(Stack[Stack.size() - 2], TreeN);
9324             ExtraArgs.erase(TreeN);
9325           } else
9326             addReductionOps(TreeN);
9327         }
9328         // Retract.
9329         Stack.pop_back();
9330         continue;
9331       }
9332 
9333       // Visit operands.
9334       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9335       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9336       if (!EdgeInst) {
9337         // Edge value is not a reduction instruction or a leaf instruction.
9338         // (It may be a constant, function argument, or something else.)
9339         markExtraArg(Stack.back(), EdgeVal);
9340         continue;
9341       }
9342       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9343       // Continue analysis if the next operand is a reduction operation or
9344       // (possibly) a leaf value. If the leaf value opcode is not set,
9345       // the first met operation != reduction operation is considered as the
9346       // leaf opcode.
9347       // Only handle trees in the current basic block.
9348       // Each tree node needs to have minimal number of users except for the
9349       // ultimate reduction.
9350       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9351       if (EdgeInst != Phi && EdgeInst != Inst &&
9352           hasSameParent(EdgeInst, Inst->getParent()) &&
9353           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9354           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9355         if (IsRdxInst) {
9356           // We need to be able to reassociate the reduction operations.
9357           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9358             // I is an extra argument for TreeN (its parent operation).
9359             markExtraArg(Stack.back(), EdgeInst);
9360             continue;
9361           }
9362         } else if (!LeafOpcode) {
9363           LeafOpcode = EdgeInst->getOpcode();
9364         }
9365         Stack.push_back(
9366             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9367         continue;
9368       }
9369       // I is an extra argument for TreeN (its parent operation).
9370       markExtraArg(Stack.back(), EdgeInst);
9371     }
9372     return true;
9373   }
9374 
9375   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9376   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9377     // If there are a sufficient number of reduction values, reduce
9378     // to a nearby power-of-2. We can safely generate oversized
9379     // vectors and rely on the backend to split them to legal sizes.
9380     unsigned NumReducedVals = ReducedVals.size();
9381     if (NumReducedVals < 4)
9382       return nullptr;
9383 
9384     // Intersect the fast-math-flags from all reduction operations.
9385     FastMathFlags RdxFMF;
9386     RdxFMF.set();
9387     for (ReductionOpsType &RdxOp : ReductionOps) {
9388       for (Value *RdxVal : RdxOp) {
9389         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9390           RdxFMF &= FPMO->getFastMathFlags();
9391       }
9392     }
9393 
9394     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9395     Builder.setFastMathFlags(RdxFMF);
9396 
9397     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9398     // The same extra argument may be used several times, so log each attempt
9399     // to use it.
9400     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9401       assert(Pair.first && "DebugLoc must be set.");
9402       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9403     }
9404 
9405     // The compare instruction of a min/max is the insertion point for new
9406     // instructions and may be replaced with a new compare instruction.
9407     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9408       assert(isa<SelectInst>(RdxRootInst) &&
9409              "Expected min/max reduction to have select root instruction");
9410       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9411       assert(isa<Instruction>(ScalarCond) &&
9412              "Expected min/max reduction to have compare condition");
9413       return cast<Instruction>(ScalarCond);
9414     };
9415 
9416     // The reduction root is used as the insertion point for new instructions,
9417     // so set it as externally used to prevent it from being deleted.
9418     ExternallyUsedValues[ReductionRoot];
9419     SmallVector<Value *, 16> IgnoreList;
9420     for (ReductionOpsType &RdxOp : ReductionOps)
9421       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9422 
9423     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9424     if (NumReducedVals > ReduxWidth) {
9425       // In the loop below, we are building a tree based on a window of
9426       // 'ReduxWidth' values.
9427       // If the operands of those values have common traits (compare predicate,
9428       // constant operand, etc), then we want to group those together to
9429       // minimize the cost of the reduction.
9430 
9431       // TODO: This should be extended to count common operands for
9432       //       compares and binops.
9433 
9434       // Step 1: Count the number of times each compare predicate occurs.
9435       SmallDenseMap<unsigned, unsigned> PredCountMap;
9436       for (Value *RdxVal : ReducedVals) {
9437         CmpInst::Predicate Pred;
9438         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9439           ++PredCountMap[Pred];
9440       }
9441       // Step 2: Sort the values so the most common predicates come first.
9442       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9443         CmpInst::Predicate PredA, PredB;
9444         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9445             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9446           return PredCountMap[PredA] > PredCountMap[PredB];
9447         }
9448         return false;
9449       });
9450     }
9451 
9452     Value *VectorizedTree = nullptr;
9453     unsigned i = 0;
9454     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9455       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9456       V.buildTree(VL, IgnoreList);
9457       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9458         break;
9459       if (V.isLoadCombineReductionCandidate(RdxKind))
9460         break;
9461       V.reorderTopToBottom();
9462       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9463       V.buildExternalUses(ExternallyUsedValues);
9464 
9465       // For a poison-safe boolean logic reduction, do not replace select
9466       // instructions with logic ops. All reduced values will be frozen (see
9467       // below) to prevent leaking poison.
9468       if (isa<SelectInst>(ReductionRoot) &&
9469           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9470           NumReducedVals != ReduxWidth)
9471         break;
9472 
9473       V.computeMinimumValueSizes();
9474 
9475       // Estimate cost.
9476       InstructionCost TreeCost =
9477           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9478       InstructionCost ReductionCost =
9479           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9480       InstructionCost Cost = TreeCost + ReductionCost;
9481       if (!Cost.isValid()) {
9482         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9483         return nullptr;
9484       }
9485       if (Cost >= -SLPCostThreshold) {
9486         V.getORE()->emit([&]() {
9487           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9488                                           cast<Instruction>(VL[0]))
9489                  << "Vectorizing horizontal reduction is possible"
9490                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9491                  << " and threshold "
9492                  << ore::NV("Threshold", -SLPCostThreshold);
9493         });
9494         break;
9495       }
9496 
9497       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9498                         << Cost << ". (HorRdx)\n");
9499       V.getORE()->emit([&]() {
9500         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9501                                   cast<Instruction>(VL[0]))
9502                << "Vectorized horizontal reduction with cost "
9503                << ore::NV("Cost", Cost) << " and with tree size "
9504                << ore::NV("TreeSize", V.getTreeSize());
9505       });
9506 
9507       // Vectorize a tree.
9508       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9509       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9510 
9511       // Emit a reduction. If the root is a select (min/max idiom), the insert
9512       // point is the compare condition of that select.
9513       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9514       if (isCmpSelMinMax(RdxRootInst))
9515         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9516       else
9517         Builder.SetInsertPoint(RdxRootInst);
9518 
9519       // To prevent poison from leaking across what used to be sequential, safe,
9520       // scalar boolean logic operations, the reduction operand must be frozen.
9521       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9522         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9523 
9524       Value *ReducedSubTree =
9525           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9526 
9527       if (!VectorizedTree) {
9528         // Initialize the final value in the reduction.
9529         VectorizedTree = ReducedSubTree;
9530       } else {
9531         // Update the final value in the reduction.
9532         Builder.SetCurrentDebugLocation(Loc);
9533         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9534                                   ReducedSubTree, "op.rdx", ReductionOps);
9535       }
9536       i += ReduxWidth;
9537       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9538     }
9539 
9540     if (VectorizedTree) {
9541       // Finish the reduction.
9542       for (; i < NumReducedVals; ++i) {
9543         auto *I = cast<Instruction>(ReducedVals[i]);
9544         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9545         VectorizedTree =
9546             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9547       }
9548       for (auto &Pair : ExternallyUsedValues) {
9549         // Add each externally used value to the final reduction.
9550         for (auto *I : Pair.second) {
9551           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9552           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9553                                     Pair.first, "op.extra", I);
9554         }
9555       }
9556 
9557       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9558 
9559       // Mark all scalar reduction ops for deletion, they are replaced by the
9560       // vector reductions.
9561       V.eraseInstructions(IgnoreList);
9562     }
9563     return VectorizedTree;
9564   }
9565 
9566   unsigned numReductionValues() const { return ReducedVals.size(); }
9567 
9568 private:
9569   /// Calculate the cost of a reduction.
9570   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9571                                    Value *FirstReducedVal, unsigned ReduxWidth,
9572                                    FastMathFlags FMF) {
9573     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9574     Type *ScalarTy = FirstReducedVal->getType();
9575     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9576     InstructionCost VectorCost, ScalarCost;
9577     switch (RdxKind) {
9578     case RecurKind::Add:
9579     case RecurKind::Mul:
9580     case RecurKind::Or:
9581     case RecurKind::And:
9582     case RecurKind::Xor:
9583     case RecurKind::FAdd:
9584     case RecurKind::FMul: {
9585       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9586       VectorCost =
9587           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9588       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9589       break;
9590     }
9591     case RecurKind::FMax:
9592     case RecurKind::FMin: {
9593       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9594       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9595       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9596                                                /*IsUnsigned=*/false, CostKind);
9597       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9598       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9599                                            SclCondTy, RdxPred, CostKind) +
9600                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9601                                            SclCondTy, RdxPred, CostKind);
9602       break;
9603     }
9604     case RecurKind::SMax:
9605     case RecurKind::SMin:
9606     case RecurKind::UMax:
9607     case RecurKind::UMin: {
9608       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9609       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9610       bool IsUnsigned =
9611           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9612       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9613                                                CostKind);
9614       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9615       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9616                                            SclCondTy, RdxPred, CostKind) +
9617                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9618                                            SclCondTy, RdxPred, CostKind);
9619       break;
9620     }
9621     default:
9622       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9623     }
9624 
9625     // Scalar cost is repeated for N-1 elements.
9626     ScalarCost *= (ReduxWidth - 1);
9627     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9628                       << " for reduction that starts with " << *FirstReducedVal
9629                       << " (It is a splitting reduction)\n");
9630     return VectorCost - ScalarCost;
9631   }
9632 
9633   /// Emit a horizontal reduction of the vectorized value.
9634   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9635                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9636     assert(VectorizedValue && "Need to have a vectorized tree node");
9637     assert(isPowerOf2_32(ReduxWidth) &&
9638            "We only handle power-of-two reductions for now");
9639     assert(RdxKind != RecurKind::FMulAdd &&
9640            "A call to the llvm.fmuladd intrinsic is not handled yet");
9641 
9642     ++NumVectorInstructions;
9643     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9644   }
9645 };
9646 
9647 } // end anonymous namespace
9648 
9649 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9650   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9651     return cast<FixedVectorType>(IE->getType())->getNumElements();
9652 
9653   unsigned AggregateSize = 1;
9654   auto *IV = cast<InsertValueInst>(InsertInst);
9655   Type *CurrentType = IV->getType();
9656   do {
9657     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9658       for (auto *Elt : ST->elements())
9659         if (Elt != ST->getElementType(0)) // check homogeneity
9660           return None;
9661       AggregateSize *= ST->getNumElements();
9662       CurrentType = ST->getElementType(0);
9663     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9664       AggregateSize *= AT->getNumElements();
9665       CurrentType = AT->getElementType();
9666     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9667       AggregateSize *= VT->getNumElements();
9668       return AggregateSize;
9669     } else if (CurrentType->isSingleValueType()) {
9670       return AggregateSize;
9671     } else {
9672       return None;
9673     }
9674   } while (true);
9675 }
9676 
9677 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9678                                    TargetTransformInfo *TTI,
9679                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9680                                    SmallVectorImpl<Value *> &InsertElts,
9681                                    unsigned OperandOffset) {
9682   do {
9683     Value *InsertedOperand = LastInsertInst->getOperand(1);
9684     Optional<unsigned> OperandIndex =
9685         getInsertIndex(LastInsertInst, OperandOffset);
9686     if (!OperandIndex)
9687       return;
9688     if (isa<InsertElementInst>(InsertedOperand) ||
9689         isa<InsertValueInst>(InsertedOperand)) {
9690       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9691                              BuildVectorOpds, InsertElts, *OperandIndex);
9692 
9693     } else {
9694       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9695       InsertElts[*OperandIndex] = LastInsertInst;
9696     }
9697     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9698   } while (LastInsertInst != nullptr &&
9699            (isa<InsertValueInst>(LastInsertInst) ||
9700             isa<InsertElementInst>(LastInsertInst)) &&
9701            LastInsertInst->hasOneUse());
9702 }
9703 
9704 /// Recognize construction of vectors like
9705 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9706 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9707 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9708 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9709 ///  starting from the last insertelement or insertvalue instruction.
9710 ///
9711 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9712 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9713 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9714 ///
9715 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9716 ///
9717 /// \return true if it matches.
9718 static bool findBuildAggregate(Instruction *LastInsertInst,
9719                                TargetTransformInfo *TTI,
9720                                SmallVectorImpl<Value *> &BuildVectorOpds,
9721                                SmallVectorImpl<Value *> &InsertElts) {
9722 
9723   assert((isa<InsertElementInst>(LastInsertInst) ||
9724           isa<InsertValueInst>(LastInsertInst)) &&
9725          "Expected insertelement or insertvalue instruction!");
9726 
9727   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9728          "Expected empty result vectors!");
9729 
9730   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9731   if (!AggregateSize)
9732     return false;
9733   BuildVectorOpds.resize(*AggregateSize);
9734   InsertElts.resize(*AggregateSize);
9735 
9736   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
9737   llvm::erase_value(BuildVectorOpds, nullptr);
9738   llvm::erase_value(InsertElts, nullptr);
9739   if (BuildVectorOpds.size() >= 2)
9740     return true;
9741 
9742   return false;
9743 }
9744 
9745 /// Try and get a reduction value from a phi node.
9746 ///
9747 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9748 /// if they come from either \p ParentBB or a containing loop latch.
9749 ///
9750 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9751 /// if not possible.
9752 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9753                                 BasicBlock *ParentBB, LoopInfo *LI) {
9754   // There are situations where the reduction value is not dominated by the
9755   // reduction phi. Vectorizing such cases has been reported to cause
9756   // miscompiles. See PR25787.
9757   auto DominatedReduxValue = [&](Value *R) {
9758     return isa<Instruction>(R) &&
9759            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9760   };
9761 
9762   Value *Rdx = nullptr;
9763 
9764   // Return the incoming value if it comes from the same BB as the phi node.
9765   if (P->getIncomingBlock(0) == ParentBB) {
9766     Rdx = P->getIncomingValue(0);
9767   } else if (P->getIncomingBlock(1) == ParentBB) {
9768     Rdx = P->getIncomingValue(1);
9769   }
9770 
9771   if (Rdx && DominatedReduxValue(Rdx))
9772     return Rdx;
9773 
9774   // Otherwise, check whether we have a loop latch to look at.
9775   Loop *BBL = LI->getLoopFor(ParentBB);
9776   if (!BBL)
9777     return nullptr;
9778   BasicBlock *BBLatch = BBL->getLoopLatch();
9779   if (!BBLatch)
9780     return nullptr;
9781 
9782   // There is a loop latch, return the incoming value if it comes from
9783   // that. This reduction pattern occasionally turns up.
9784   if (P->getIncomingBlock(0) == BBLatch) {
9785     Rdx = P->getIncomingValue(0);
9786   } else if (P->getIncomingBlock(1) == BBLatch) {
9787     Rdx = P->getIncomingValue(1);
9788   }
9789 
9790   if (Rdx && DominatedReduxValue(Rdx))
9791     return Rdx;
9792 
9793   return nullptr;
9794 }
9795 
9796 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9797   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9798     return true;
9799   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9800     return true;
9801   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9802     return true;
9803   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9804     return true;
9805   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9806     return true;
9807   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9808     return true;
9809   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9810     return true;
9811   return false;
9812 }
9813 
9814 /// Attempt to reduce a horizontal reduction.
9815 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9816 /// with reduction operators \a Root (or one of its operands) in a basic block
9817 /// \a BB, then check if it can be done. If horizontal reduction is not found
9818 /// and root instruction is a binary operation, vectorization of the operands is
9819 /// attempted.
9820 /// \returns true if a horizontal reduction was matched and reduced or operands
9821 /// of one of the binary instruction were vectorized.
9822 /// \returns false if a horizontal reduction was not matched (or not possible)
9823 /// or no vectorization of any binary operation feeding \a Root instruction was
9824 /// performed.
9825 static bool tryToVectorizeHorReductionOrInstOperands(
9826     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9827     TargetTransformInfo *TTI,
9828     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9829   if (!ShouldVectorizeHor)
9830     return false;
9831 
9832   if (!Root)
9833     return false;
9834 
9835   if (Root->getParent() != BB || isa<PHINode>(Root))
9836     return false;
9837   // Start analysis starting from Root instruction. If horizontal reduction is
9838   // found, try to vectorize it. If it is not a horizontal reduction or
9839   // vectorization is not possible or not effective, and currently analyzed
9840   // instruction is a binary operation, try to vectorize the operands, using
9841   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9842   // the same procedure considering each operand as a possible root of the
9843   // horizontal reduction.
9844   // Interrupt the process if the Root instruction itself was vectorized or all
9845   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9846   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9847   // CmpInsts so we can skip extra attempts in
9848   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9849   std::queue<std::pair<Instruction *, unsigned>> Stack;
9850   Stack.emplace(Root, 0);
9851   SmallPtrSet<Value *, 8> VisitedInstrs;
9852   SmallVector<WeakTrackingVH> PostponedInsts;
9853   bool Res = false;
9854   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9855                                      Value *&B1) -> Value * {
9856     bool IsBinop = matchRdxBop(Inst, B0, B1);
9857     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9858     if (IsBinop || IsSelect) {
9859       HorizontalReduction HorRdx;
9860       if (HorRdx.matchAssociativeReduction(P, Inst))
9861         return HorRdx.tryToReduce(R, TTI);
9862     }
9863     return nullptr;
9864   };
9865   while (!Stack.empty()) {
9866     Instruction *Inst;
9867     unsigned Level;
9868     std::tie(Inst, Level) = Stack.front();
9869     Stack.pop();
9870     // Do not try to analyze instruction that has already been vectorized.
9871     // This may happen when we vectorize instruction operands on a previous
9872     // iteration while stack was populated before that happened.
9873     if (R.isDeleted(Inst))
9874       continue;
9875     Value *B0 = nullptr, *B1 = nullptr;
9876     if (Value *V = TryToReduce(Inst, B0, B1)) {
9877       Res = true;
9878       // Set P to nullptr to avoid re-analysis of phi node in
9879       // matchAssociativeReduction function unless this is the root node.
9880       P = nullptr;
9881       if (auto *I = dyn_cast<Instruction>(V)) {
9882         // Try to find another reduction.
9883         Stack.emplace(I, Level);
9884         continue;
9885       }
9886     } else {
9887       bool IsBinop = B0 && B1;
9888       if (P && IsBinop) {
9889         Inst = dyn_cast<Instruction>(B0);
9890         if (Inst == P)
9891           Inst = dyn_cast<Instruction>(B1);
9892         if (!Inst) {
9893           // Set P to nullptr to avoid re-analysis of phi node in
9894           // matchAssociativeReduction function unless this is the root node.
9895           P = nullptr;
9896           continue;
9897         }
9898       }
9899       // Set P to nullptr to avoid re-analysis of phi node in
9900       // matchAssociativeReduction function unless this is the root node.
9901       P = nullptr;
9902       // Do not try to vectorize CmpInst operands, this is done separately.
9903       // Final attempt for binop args vectorization should happen after the loop
9904       // to try to find reductions.
9905       if (!isa<CmpInst>(Inst))
9906         PostponedInsts.push_back(Inst);
9907     }
9908 
9909     // Try to vectorize operands.
9910     // Continue analysis for the instruction from the same basic block only to
9911     // save compile time.
9912     if (++Level < RecursionMaxDepth)
9913       for (auto *Op : Inst->operand_values())
9914         if (VisitedInstrs.insert(Op).second)
9915           if (auto *I = dyn_cast<Instruction>(Op))
9916             // Do not try to vectorize CmpInst operands,  this is done
9917             // separately.
9918             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9919                 I->getParent() == BB)
9920               Stack.emplace(I, Level);
9921   }
9922   // Try to vectorized binops where reductions were not found.
9923   for (Value *V : PostponedInsts)
9924     if (auto *Inst = dyn_cast<Instruction>(V))
9925       if (!R.isDeleted(Inst))
9926         Res |= Vectorize(Inst, R);
9927   return Res;
9928 }
9929 
9930 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9931                                                  BasicBlock *BB, BoUpSLP &R,
9932                                                  TargetTransformInfo *TTI) {
9933   auto *I = dyn_cast_or_null<Instruction>(V);
9934   if (!I)
9935     return false;
9936 
9937   if (!isa<BinaryOperator>(I))
9938     P = nullptr;
9939   // Try to match and vectorize a horizontal reduction.
9940   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9941     return tryToVectorize(I, R);
9942   };
9943   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9944                                                   ExtraVectorization);
9945 }
9946 
9947 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9948                                                  BasicBlock *BB, BoUpSLP &R) {
9949   const DataLayout &DL = BB->getModule()->getDataLayout();
9950   if (!R.canMapToVector(IVI->getType(), DL))
9951     return false;
9952 
9953   SmallVector<Value *, 16> BuildVectorOpds;
9954   SmallVector<Value *, 16> BuildVectorInsts;
9955   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9956     return false;
9957 
9958   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9959   // Aggregate value is unlikely to be processed in vector register.
9960   return tryToVectorizeList(BuildVectorOpds, R);
9961 }
9962 
9963 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9964                                                    BasicBlock *BB, BoUpSLP &R) {
9965   SmallVector<Value *, 16> BuildVectorInsts;
9966   SmallVector<Value *, 16> BuildVectorOpds;
9967   SmallVector<int> Mask;
9968   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9969       (llvm::all_of(
9970            BuildVectorOpds,
9971            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9972        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9973     return false;
9974 
9975   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9976   return tryToVectorizeList(BuildVectorInsts, R);
9977 }
9978 
9979 template <typename T>
9980 static bool
9981 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9982                        function_ref<unsigned(T *)> Limit,
9983                        function_ref<bool(T *, T *)> Comparator,
9984                        function_ref<bool(T *, T *)> AreCompatible,
9985                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
9986                        bool LimitForRegisterSize) {
9987   bool Changed = false;
9988   // Sort by type, parent, operands.
9989   stable_sort(Incoming, Comparator);
9990 
9991   // Try to vectorize elements base on their type.
9992   SmallVector<T *> Candidates;
9993   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9994     // Look for the next elements with the same type, parent and operand
9995     // kinds.
9996     auto *SameTypeIt = IncIt;
9997     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9998       ++SameTypeIt;
9999 
10000     // Try to vectorize them.
10001     unsigned NumElts = (SameTypeIt - IncIt);
10002     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10003                       << NumElts << ")\n");
10004     // The vectorization is a 3-state attempt:
10005     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10006     // size of maximal register at first.
10007     // 2. Try to vectorize remaining instructions with the same type, if
10008     // possible. This may result in the better vectorization results rather than
10009     // if we try just to vectorize instructions with the same/alternate opcodes.
10010     // 3. Final attempt to try to vectorize all instructions with the
10011     // same/alternate ops only, this may result in some extra final
10012     // vectorization.
10013     if (NumElts > 1 &&
10014         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10015       // Success start over because instructions might have been changed.
10016       Changed = true;
10017     } else if (NumElts < Limit(*IncIt) &&
10018                (Candidates.empty() ||
10019                 Candidates.front()->getType() == (*IncIt)->getType())) {
10020       Candidates.append(IncIt, std::next(IncIt, NumElts));
10021     }
10022     // Final attempt to vectorize instructions with the same types.
10023     if (Candidates.size() > 1 &&
10024         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10025       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10026         // Success start over because instructions might have been changed.
10027         Changed = true;
10028       } else if (LimitForRegisterSize) {
10029         // Try to vectorize using small vectors.
10030         for (auto *It = Candidates.begin(), *End = Candidates.end();
10031              It != End;) {
10032           auto *SameTypeIt = It;
10033           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10034             ++SameTypeIt;
10035           unsigned NumElts = (SameTypeIt - It);
10036           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10037                                             /*LimitForRegisterSize=*/false))
10038             Changed = true;
10039           It = SameTypeIt;
10040         }
10041       }
10042       Candidates.clear();
10043     }
10044 
10045     // Start over at the next instruction of a different type (or the end).
10046     IncIt = SameTypeIt;
10047   }
10048   return Changed;
10049 }
10050 
10051 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10052 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10053 /// operands. If IsCompatibility is false, function implements strict weak
10054 /// ordering relation between two cmp instructions, returning true if the first
10055 /// instruction is "less" than the second, i.e. its predicate is less than the
10056 /// predicate of the second or the operands IDs are less than the operands IDs
10057 /// of the second cmp instruction.
10058 template <bool IsCompatibility>
10059 static bool compareCmp(Value *V, Value *V2,
10060                        function_ref<bool(Instruction *)> IsDeleted) {
10061   auto *CI1 = cast<CmpInst>(V);
10062   auto *CI2 = cast<CmpInst>(V2);
10063   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10064     return false;
10065   if (CI1->getOperand(0)->getType()->getTypeID() <
10066       CI2->getOperand(0)->getType()->getTypeID())
10067     return !IsCompatibility;
10068   if (CI1->getOperand(0)->getType()->getTypeID() >
10069       CI2->getOperand(0)->getType()->getTypeID())
10070     return false;
10071   CmpInst::Predicate Pred1 = CI1->getPredicate();
10072   CmpInst::Predicate Pred2 = CI2->getPredicate();
10073   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10074   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10075   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10076   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10077   if (BasePred1 < BasePred2)
10078     return !IsCompatibility;
10079   if (BasePred1 > BasePred2)
10080     return false;
10081   // Compare operands.
10082   bool LEPreds = Pred1 <= Pred2;
10083   bool GEPreds = Pred1 >= Pred2;
10084   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10085     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10086     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10087     if (Op1->getValueID() < Op2->getValueID())
10088       return !IsCompatibility;
10089     if (Op1->getValueID() > Op2->getValueID())
10090       return false;
10091     if (auto *I1 = dyn_cast<Instruction>(Op1))
10092       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10093         if (I1->getParent() != I2->getParent())
10094           return false;
10095         InstructionsState S = getSameOpcode({I1, I2});
10096         if (S.getOpcode())
10097           continue;
10098         return false;
10099       }
10100   }
10101   return IsCompatibility;
10102 }
10103 
10104 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10105     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10106     bool AtTerminator) {
10107   bool OpsChanged = false;
10108   SmallVector<Instruction *, 4> PostponedCmps;
10109   for (auto *I : reverse(Instructions)) {
10110     if (R.isDeleted(I))
10111       continue;
10112     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10113       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10114     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10115       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10116     else if (isa<CmpInst>(I))
10117       PostponedCmps.push_back(I);
10118   }
10119   if (AtTerminator) {
10120     // Try to find reductions first.
10121     for (Instruction *I : PostponedCmps) {
10122       if (R.isDeleted(I))
10123         continue;
10124       for (Value *Op : I->operands())
10125         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10126     }
10127     // Try to vectorize operands as vector bundles.
10128     for (Instruction *I : PostponedCmps) {
10129       if (R.isDeleted(I))
10130         continue;
10131       OpsChanged |= tryToVectorize(I, R);
10132     }
10133     // Try to vectorize list of compares.
10134     // Sort by type, compare predicate, etc.
10135     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10136       return compareCmp<false>(V, V2,
10137                                [&R](Instruction *I) { return R.isDeleted(I); });
10138     };
10139 
10140     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10141       if (V1 == V2)
10142         return true;
10143       return compareCmp<true>(V1, V2,
10144                               [&R](Instruction *I) { return R.isDeleted(I); });
10145     };
10146     auto Limit = [&R](Value *V) {
10147       unsigned EltSize = R.getVectorElementSize(V);
10148       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10149     };
10150 
10151     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10152     OpsChanged |= tryToVectorizeSequence<Value>(
10153         Vals, Limit, CompareSorter, AreCompatibleCompares,
10154         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10155           // Exclude possible reductions from other blocks.
10156           bool ArePossiblyReducedInOtherBlock =
10157               any_of(Candidates, [](Value *V) {
10158                 return any_of(V->users(), [V](User *U) {
10159                   return isa<SelectInst>(U) &&
10160                          cast<SelectInst>(U)->getParent() !=
10161                              cast<Instruction>(V)->getParent();
10162                 });
10163               });
10164           if (ArePossiblyReducedInOtherBlock)
10165             return false;
10166           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10167         },
10168         /*LimitForRegisterSize=*/true);
10169     Instructions.clear();
10170   } else {
10171     // Insert in reverse order since the PostponedCmps vector was filled in
10172     // reverse order.
10173     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10174   }
10175   return OpsChanged;
10176 }
10177 
10178 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10179   bool Changed = false;
10180   SmallVector<Value *, 4> Incoming;
10181   SmallPtrSet<Value *, 16> VisitedInstrs;
10182   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10183   // node. Allows better to identify the chains that can be vectorized in the
10184   // better way.
10185   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10186   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10187     assert(isValidElementType(V1->getType()) &&
10188            isValidElementType(V2->getType()) &&
10189            "Expected vectorizable types only.");
10190     // It is fine to compare type IDs here, since we expect only vectorizable
10191     // types, like ints, floats and pointers, we don't care about other type.
10192     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10193       return true;
10194     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10195       return false;
10196     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10197     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10198     if (Opcodes1.size() < Opcodes2.size())
10199       return true;
10200     if (Opcodes1.size() > Opcodes2.size())
10201       return false;
10202     Optional<bool> ConstOrder;
10203     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10204       // Undefs are compatible with any other value.
10205       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10206         if (!ConstOrder)
10207           ConstOrder =
10208               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10209         continue;
10210       }
10211       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10212         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10213           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10214           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10215           if (!NodeI1)
10216             return NodeI2 != nullptr;
10217           if (!NodeI2)
10218             return false;
10219           assert((NodeI1 == NodeI2) ==
10220                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10221                  "Different nodes should have different DFS numbers");
10222           if (NodeI1 != NodeI2)
10223             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10224           InstructionsState S = getSameOpcode({I1, I2});
10225           if (S.getOpcode())
10226             continue;
10227           return I1->getOpcode() < I2->getOpcode();
10228         }
10229       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10230         if (!ConstOrder)
10231           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10232         continue;
10233       }
10234       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10235         return true;
10236       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10237         return false;
10238     }
10239     return ConstOrder && *ConstOrder;
10240   };
10241   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10242     if (V1 == V2)
10243       return true;
10244     if (V1->getType() != V2->getType())
10245       return false;
10246     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10247     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10248     if (Opcodes1.size() != Opcodes2.size())
10249       return false;
10250     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10251       // Undefs are compatible with any other value.
10252       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10253         continue;
10254       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10255         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10256           if (I1->getParent() != I2->getParent())
10257             return false;
10258           InstructionsState S = getSameOpcode({I1, I2});
10259           if (S.getOpcode())
10260             continue;
10261           return false;
10262         }
10263       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10264         continue;
10265       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10266         return false;
10267     }
10268     return true;
10269   };
10270   auto Limit = [&R](Value *V) {
10271     unsigned EltSize = R.getVectorElementSize(V);
10272     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10273   };
10274 
10275   bool HaveVectorizedPhiNodes = false;
10276   do {
10277     // Collect the incoming values from the PHIs.
10278     Incoming.clear();
10279     for (Instruction &I : *BB) {
10280       PHINode *P = dyn_cast<PHINode>(&I);
10281       if (!P)
10282         break;
10283 
10284       // No need to analyze deleted, vectorized and non-vectorizable
10285       // instructions.
10286       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10287           isValidElementType(P->getType()))
10288         Incoming.push_back(P);
10289     }
10290 
10291     // Find the corresponding non-phi nodes for better matching when trying to
10292     // build the tree.
10293     for (Value *V : Incoming) {
10294       SmallVectorImpl<Value *> &Opcodes =
10295           PHIToOpcodes.try_emplace(V).first->getSecond();
10296       if (!Opcodes.empty())
10297         continue;
10298       SmallVector<Value *, 4> Nodes(1, V);
10299       SmallPtrSet<Value *, 4> Visited;
10300       while (!Nodes.empty()) {
10301         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10302         if (!Visited.insert(PHI).second)
10303           continue;
10304         for (Value *V : PHI->incoming_values()) {
10305           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10306             Nodes.push_back(PHI1);
10307             continue;
10308           }
10309           Opcodes.emplace_back(V);
10310         }
10311       }
10312     }
10313 
10314     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10315         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10316         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10317           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10318         },
10319         /*LimitForRegisterSize=*/true);
10320     Changed |= HaveVectorizedPhiNodes;
10321     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10322   } while (HaveVectorizedPhiNodes);
10323 
10324   VisitedInstrs.clear();
10325 
10326   SmallVector<Instruction *, 8> PostProcessInstructions;
10327   SmallDenseSet<Instruction *, 4> KeyNodes;
10328   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10329     // Skip instructions with scalable type. The num of elements is unknown at
10330     // compile-time for scalable type.
10331     if (isa<ScalableVectorType>(it->getType()))
10332       continue;
10333 
10334     // Skip instructions marked for the deletion.
10335     if (R.isDeleted(&*it))
10336       continue;
10337     // We may go through BB multiple times so skip the one we have checked.
10338     if (!VisitedInstrs.insert(&*it).second) {
10339       if (it->use_empty() && KeyNodes.contains(&*it) &&
10340           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10341                                       it->isTerminator())) {
10342         // We would like to start over since some instructions are deleted
10343         // and the iterator may become invalid value.
10344         Changed = true;
10345         it = BB->begin();
10346         e = BB->end();
10347       }
10348       continue;
10349     }
10350 
10351     if (isa<DbgInfoIntrinsic>(it))
10352       continue;
10353 
10354     // Try to vectorize reductions that use PHINodes.
10355     if (PHINode *P = dyn_cast<PHINode>(it)) {
10356       // Check that the PHI is a reduction PHI.
10357       if (P->getNumIncomingValues() == 2) {
10358         // Try to match and vectorize a horizontal reduction.
10359         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10360                                      TTI)) {
10361           Changed = true;
10362           it = BB->begin();
10363           e = BB->end();
10364           continue;
10365         }
10366       }
10367       // Try to vectorize the incoming values of the PHI, to catch reductions
10368       // that feed into PHIs.
10369       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10370         // Skip if the incoming block is the current BB for now. Also, bypass
10371         // unreachable IR for efficiency and to avoid crashing.
10372         // TODO: Collect the skipped incoming values and try to vectorize them
10373         // after processing BB.
10374         if (BB == P->getIncomingBlock(I) ||
10375             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10376           continue;
10377 
10378         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10379                                             P->getIncomingBlock(I), R, TTI);
10380       }
10381       continue;
10382     }
10383 
10384     // Ran into an instruction without users, like terminator, or function call
10385     // with ignored return value, store. Ignore unused instructions (basing on
10386     // instruction type, except for CallInst and InvokeInst).
10387     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10388                             isa<InvokeInst>(it))) {
10389       KeyNodes.insert(&*it);
10390       bool OpsChanged = false;
10391       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10392         for (auto *V : it->operand_values()) {
10393           // Try to match and vectorize a horizontal reduction.
10394           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10395         }
10396       }
10397       // Start vectorization of post-process list of instructions from the
10398       // top-tree instructions to try to vectorize as many instructions as
10399       // possible.
10400       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10401                                                 it->isTerminator());
10402       if (OpsChanged) {
10403         // We would like to start over since some instructions are deleted
10404         // and the iterator may become invalid value.
10405         Changed = true;
10406         it = BB->begin();
10407         e = BB->end();
10408         continue;
10409       }
10410     }
10411 
10412     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10413         isa<InsertValueInst>(it))
10414       PostProcessInstructions.push_back(&*it);
10415   }
10416 
10417   return Changed;
10418 }
10419 
10420 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10421   auto Changed = false;
10422   for (auto &Entry : GEPs) {
10423     // If the getelementptr list has fewer than two elements, there's nothing
10424     // to do.
10425     if (Entry.second.size() < 2)
10426       continue;
10427 
10428     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10429                       << Entry.second.size() << ".\n");
10430 
10431     // Process the GEP list in chunks suitable for the target's supported
10432     // vector size. If a vector register can't hold 1 element, we are done. We
10433     // are trying to vectorize the index computations, so the maximum number of
10434     // elements is based on the size of the index expression, rather than the
10435     // size of the GEP itself (the target's pointer size).
10436     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10437     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10438     if (MaxVecRegSize < EltSize)
10439       continue;
10440 
10441     unsigned MaxElts = MaxVecRegSize / EltSize;
10442     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10443       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10444       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10445 
10446       // Initialize a set a candidate getelementptrs. Note that we use a
10447       // SetVector here to preserve program order. If the index computations
10448       // are vectorizable and begin with loads, we want to minimize the chance
10449       // of having to reorder them later.
10450       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10451 
10452       // Some of the candidates may have already been vectorized after we
10453       // initially collected them. If so, they are marked as deleted, so remove
10454       // them from the set of candidates.
10455       Candidates.remove_if(
10456           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10457 
10458       // Remove from the set of candidates all pairs of getelementptrs with
10459       // constant differences. Such getelementptrs are likely not good
10460       // candidates for vectorization in a bottom-up phase since one can be
10461       // computed from the other. We also ensure all candidate getelementptr
10462       // indices are unique.
10463       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10464         auto *GEPI = GEPList[I];
10465         if (!Candidates.count(GEPI))
10466           continue;
10467         auto *SCEVI = SE->getSCEV(GEPList[I]);
10468         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10469           auto *GEPJ = GEPList[J];
10470           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10471           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10472             Candidates.remove(GEPI);
10473             Candidates.remove(GEPJ);
10474           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10475             Candidates.remove(GEPJ);
10476           }
10477         }
10478       }
10479 
10480       // We break out of the above computation as soon as we know there are
10481       // fewer than two candidates remaining.
10482       if (Candidates.size() < 2)
10483         continue;
10484 
10485       // Add the single, non-constant index of each candidate to the bundle. We
10486       // ensured the indices met these constraints when we originally collected
10487       // the getelementptrs.
10488       SmallVector<Value *, 16> Bundle(Candidates.size());
10489       auto BundleIndex = 0u;
10490       for (auto *V : Candidates) {
10491         auto *GEP = cast<GetElementPtrInst>(V);
10492         auto *GEPIdx = GEP->idx_begin()->get();
10493         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10494         Bundle[BundleIndex++] = GEPIdx;
10495       }
10496 
10497       // Try and vectorize the indices. We are currently only interested in
10498       // gather-like cases of the form:
10499       //
10500       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10501       //
10502       // where the loads of "a", the loads of "b", and the subtractions can be
10503       // performed in parallel. It's likely that detecting this pattern in a
10504       // bottom-up phase will be simpler and less costly than building a
10505       // full-blown top-down phase beginning at the consecutive loads.
10506       Changed |= tryToVectorizeList(Bundle, R);
10507     }
10508   }
10509   return Changed;
10510 }
10511 
10512 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10513   bool Changed = false;
10514   // Sort by type, base pointers and values operand. Value operands must be
10515   // compatible (have the same opcode, same parent), otherwise it is
10516   // definitely not profitable to try to vectorize them.
10517   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10518     if (V->getPointerOperandType()->getTypeID() <
10519         V2->getPointerOperandType()->getTypeID())
10520       return true;
10521     if (V->getPointerOperandType()->getTypeID() >
10522         V2->getPointerOperandType()->getTypeID())
10523       return false;
10524     // UndefValues are compatible with all other values.
10525     if (isa<UndefValue>(V->getValueOperand()) ||
10526         isa<UndefValue>(V2->getValueOperand()))
10527       return false;
10528     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10529       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10530         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10531             DT->getNode(I1->getParent());
10532         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10533             DT->getNode(I2->getParent());
10534         assert(NodeI1 && "Should only process reachable instructions");
10535         assert(NodeI1 && "Should only process reachable instructions");
10536         assert((NodeI1 == NodeI2) ==
10537                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10538                "Different nodes should have different DFS numbers");
10539         if (NodeI1 != NodeI2)
10540           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10541         InstructionsState S = getSameOpcode({I1, I2});
10542         if (S.getOpcode())
10543           return false;
10544         return I1->getOpcode() < I2->getOpcode();
10545       }
10546     if (isa<Constant>(V->getValueOperand()) &&
10547         isa<Constant>(V2->getValueOperand()))
10548       return false;
10549     return V->getValueOperand()->getValueID() <
10550            V2->getValueOperand()->getValueID();
10551   };
10552 
10553   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10554     if (V1 == V2)
10555       return true;
10556     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10557       return false;
10558     // Undefs are compatible with any other value.
10559     if (isa<UndefValue>(V1->getValueOperand()) ||
10560         isa<UndefValue>(V2->getValueOperand()))
10561       return true;
10562     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10563       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10564         if (I1->getParent() != I2->getParent())
10565           return false;
10566         InstructionsState S = getSameOpcode({I1, I2});
10567         return S.getOpcode() > 0;
10568       }
10569     if (isa<Constant>(V1->getValueOperand()) &&
10570         isa<Constant>(V2->getValueOperand()))
10571       return true;
10572     return V1->getValueOperand()->getValueID() ==
10573            V2->getValueOperand()->getValueID();
10574   };
10575   auto Limit = [&R, this](StoreInst *SI) {
10576     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10577     return R.getMinVF(EltSize);
10578   };
10579 
10580   // Attempt to sort and vectorize each of the store-groups.
10581   for (auto &Pair : Stores) {
10582     if (Pair.second.size() < 2)
10583       continue;
10584 
10585     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10586                       << Pair.second.size() << ".\n");
10587 
10588     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10589       continue;
10590 
10591     Changed |= tryToVectorizeSequence<StoreInst>(
10592         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10593         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10594           return vectorizeStores(Candidates, R);
10595         },
10596         /*LimitForRegisterSize=*/false);
10597   }
10598   return Changed;
10599 }
10600 
10601 char SLPVectorizer::ID = 0;
10602 
10603 static const char lv_name[] = "SLP Vectorizer";
10604 
10605 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10606 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10607 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10608 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10609 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10610 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10611 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10612 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10613 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10614 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10615 
10616 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10617