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