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/Operator.h"
68 #include "llvm/IR/PatternMatch.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/IR/Use.h"
71 #include "llvm/IR/User.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/IR/ValueHandle.h"
74 #ifdef EXPENSIVE_CHECKS
75 #include "llvm/IR/Verifier.h"
76 #endif
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 /// Checks if the provided value does not require scheduling. It does not
776 /// require scheduling if this is not an instruction or it is an instruction
777 /// that does not read/write memory and all operands are either not instructions
778 /// or phi nodes or instructions from different blocks.
779 static bool areAllOperandsNonInsts(Value *V) {
780   auto *I = dyn_cast<Instruction>(V);
781   if (!I)
782     return true;
783   return !mayHaveNonDefUseDependency(*I) &&
784     all_of(I->operands(), [I](Value *V) {
785       auto *IO = dyn_cast<Instruction>(V);
786       if (!IO)
787         return true;
788       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
789     });
790 }
791 
792 /// Checks if the provided value does not require scheduling. It does not
793 /// require scheduling if this is not an instruction or it is an instruction
794 /// that does not read/write memory and all users are phi nodes or instructions
795 /// from the different blocks.
796 static bool isUsedOutsideBlock(Value *V) {
797   auto *I = dyn_cast<Instruction>(V);
798   if (!I)
799     return true;
800   // Limits the number of uses to save compile time.
801   constexpr int UsesLimit = 8;
802   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
803          all_of(I->users(), [I](User *U) {
804            auto *IU = dyn_cast<Instruction>(U);
805            if (!IU)
806              return true;
807            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
808          });
809 }
810 
811 /// Checks if the specified value does not require scheduling. It does not
812 /// require scheduling if all operands and all users do not need to be scheduled
813 /// in the current basic block.
814 static bool doesNotNeedToBeScheduled(Value *V) {
815   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
816 }
817 
818 /// Checks if the specified array of instructions does not require scheduling.
819 /// It is so if all either instructions have operands that do not require
820 /// scheduling or their users do not require scheduling since they are phis or
821 /// in other basic blocks.
822 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
823   return !VL.empty() &&
824          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
825 }
826 
827 namespace slpvectorizer {
828 
829 /// Bottom Up SLP Vectorizer.
830 class BoUpSLP {
831   struct TreeEntry;
832   struct ScheduleData;
833 
834 public:
835   using ValueList = SmallVector<Value *, 8>;
836   using InstrList = SmallVector<Instruction *, 16>;
837   using ValueSet = SmallPtrSet<Value *, 16>;
838   using StoreList = SmallVector<StoreInst *, 8>;
839   using ExtraValueToDebugLocsMap =
840       MapVector<Value *, SmallVector<Instruction *, 2>>;
841   using OrdersType = SmallVector<unsigned, 4>;
842 
843   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
844           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
845           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
846           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
847       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
848         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
849     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
850     // Use the vector register size specified by the target unless overridden
851     // by a command-line option.
852     // TODO: It would be better to limit the vectorization factor based on
853     //       data type rather than just register size. For example, x86 AVX has
854     //       256-bit registers, but it does not support integer operations
855     //       at that width (that requires AVX2).
856     if (MaxVectorRegSizeOption.getNumOccurrences())
857       MaxVecRegSize = MaxVectorRegSizeOption;
858     else
859       MaxVecRegSize =
860           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
861               .getFixedSize();
862 
863     if (MinVectorRegSizeOption.getNumOccurrences())
864       MinVecRegSize = MinVectorRegSizeOption;
865     else
866       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
867   }
868 
869   /// Vectorize the tree that starts with the elements in \p VL.
870   /// Returns the vectorized root.
871   Value *vectorizeTree();
872 
873   /// Vectorize the tree but with the list of externally used values \p
874   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
875   /// generated extractvalue instructions.
876   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
877 
878   /// \returns the cost incurred by unwanted spills and fills, caused by
879   /// holding live values over call sites.
880   InstructionCost getSpillCost() const;
881 
882   /// \returns the vectorization cost of the subtree that starts at \p VL.
883   /// A negative number means that this is profitable.
884   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
885 
886   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
887   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
888   void buildTree(ArrayRef<Value *> Roots,
889                  ArrayRef<Value *> UserIgnoreLst = None);
890 
891   /// Builds external uses of the vectorized scalars, i.e. the list of
892   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
893   /// ExternallyUsedValues contains additional list of external uses to handle
894   /// vectorization of reductions.
895   void
896   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
897 
898   /// Clear the internal data structures that are created by 'buildTree'.
899   void deleteTree() {
900     VectorizableTree.clear();
901     ScalarToTreeEntry.clear();
902     MustGather.clear();
903     ExternalUses.clear();
904     for (auto &Iter : BlocksSchedules) {
905       BlockScheduling *BS = Iter.second.get();
906       BS->clear();
907     }
908     MinBWs.clear();
909     InstrElementSize.clear();
910   }
911 
912   unsigned getTreeSize() const { return VectorizableTree.size(); }
913 
914   /// Perform LICM and CSE on the newly generated gather sequences.
915   void optimizeGatherSequence();
916 
917   /// Checks if the specified gather tree entry \p TE can be represented as a
918   /// shuffled vector entry + (possibly) permutation with other gathers. It
919   /// implements the checks only for possibly ordered scalars (Loads,
920   /// ExtractElement, ExtractValue), which can be part of the graph.
921   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
922 
923   /// Gets reordering data for the given tree entry. If the entry is vectorized
924   /// - just return ReorderIndices, otherwise check if the scalars can be
925   /// reordered and return the most optimal order.
926   /// \param TopToBottom If true, include the order of vectorized stores and
927   /// insertelement nodes, otherwise skip them.
928   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
929 
930   /// Reorders the current graph to the most profitable order starting from the
931   /// root node to the leaf nodes. The best order is chosen only from the nodes
932   /// of the same size (vectorization factor). Smaller nodes are considered
933   /// parts of subgraph with smaller VF and they are reordered independently. We
934   /// can make it because we still need to extend smaller nodes to the wider VF
935   /// and we can merge reordering shuffles with the widening shuffles.
936   void reorderTopToBottom();
937 
938   /// Reorders the current graph to the most profitable order starting from
939   /// leaves to the root. It allows to rotate small subgraphs and reduce the
940   /// number of reshuffles if the leaf nodes use the same order. In this case we
941   /// can merge the orders and just shuffle user node instead of shuffling its
942   /// operands. Plus, even the leaf nodes have different orders, it allows to
943   /// sink reordering in the graph closer to the root node and merge it later
944   /// during analysis.
945   void reorderBottomToTop(bool IgnoreReorder = false);
946 
947   /// \return The vector element size in bits to use when vectorizing the
948   /// expression tree ending at \p V. If V is a store, the size is the width of
949   /// the stored value. Otherwise, the size is the width of the largest loaded
950   /// value reaching V. This method is used by the vectorizer to calculate
951   /// vectorization factors.
952   unsigned getVectorElementSize(Value *V);
953 
954   /// Compute the minimum type sizes required to represent the entries in a
955   /// vectorizable tree.
956   void computeMinimumValueSizes();
957 
958   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
959   unsigned getMaxVecRegSize() const {
960     return MaxVecRegSize;
961   }
962 
963   // \returns minimum vector register size as set by cl::opt.
964   unsigned getMinVecRegSize() const {
965     return MinVecRegSize;
966   }
967 
968   unsigned getMinVF(unsigned Sz) const {
969     return std::max(2U, getMinVecRegSize() / Sz);
970   }
971 
972   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
973     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
974       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
975     return MaxVF ? MaxVF : UINT_MAX;
976   }
977 
978   /// Check if homogeneous aggregate is isomorphic to some VectorType.
979   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
980   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
981   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
982   ///
983   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
984   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
985 
986   /// \returns True if the VectorizableTree is both tiny and not fully
987   /// vectorizable. We do not vectorize such trees.
988   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
989 
990   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
991   /// can be load combined in the backend. Load combining may not be allowed in
992   /// the IR optimizer, so we do not want to alter the pattern. For example,
993   /// partially transforming a scalar bswap() pattern into vector code is
994   /// effectively impossible for the backend to undo.
995   /// TODO: If load combining is allowed in the IR optimizer, this analysis
996   ///       may not be necessary.
997   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
998 
999   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1000   /// can be load combined in the backend. Load combining may not be allowed in
1001   /// the IR optimizer, so we do not want to alter the pattern. For example,
1002   /// partially transforming a scalar bswap() pattern into vector code is
1003   /// effectively impossible for the backend to undo.
1004   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1005   ///       may not be necessary.
1006   bool isLoadCombineCandidate() const;
1007 
1008   OptimizationRemarkEmitter *getORE() { return ORE; }
1009 
1010   /// This structure holds any data we need about the edges being traversed
1011   /// during buildTree_rec(). We keep track of:
1012   /// (i) the user TreeEntry index, and
1013   /// (ii) the index of the edge.
1014   struct EdgeInfo {
1015     EdgeInfo() = default;
1016     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1017         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1018     /// The user TreeEntry.
1019     TreeEntry *UserTE = nullptr;
1020     /// The operand index of the use.
1021     unsigned EdgeIdx = UINT_MAX;
1022 #ifndef NDEBUG
1023     friend inline raw_ostream &operator<<(raw_ostream &OS,
1024                                           const BoUpSLP::EdgeInfo &EI) {
1025       EI.dump(OS);
1026       return OS;
1027     }
1028     /// Debug print.
1029     void dump(raw_ostream &OS) const {
1030       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1031          << " EdgeIdx:" << EdgeIdx << "}";
1032     }
1033     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1034 #endif
1035   };
1036 
1037   /// A helper data structure to hold the operands of a vector of instructions.
1038   /// This supports a fixed vector length for all operand vectors.
1039   class VLOperands {
1040     /// For each operand we need (i) the value, and (ii) the opcode that it
1041     /// would be attached to if the expression was in a left-linearized form.
1042     /// This is required to avoid illegal operand reordering.
1043     /// For example:
1044     /// \verbatim
1045     ///                         0 Op1
1046     ///                         |/
1047     /// Op1 Op2   Linearized    + Op2
1048     ///   \ /     ---------->   |/
1049     ///    -                    -
1050     ///
1051     /// Op1 - Op2            (0 + Op1) - Op2
1052     /// \endverbatim
1053     ///
1054     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1055     ///
1056     /// Another way to think of this is to track all the operations across the
1057     /// path from the operand all the way to the root of the tree and to
1058     /// calculate the operation that corresponds to this path. For example, the
1059     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1060     /// corresponding operation is a '-' (which matches the one in the
1061     /// linearized tree, as shown above).
1062     ///
1063     /// For lack of a better term, we refer to this operation as Accumulated
1064     /// Path Operation (APO).
1065     struct OperandData {
1066       OperandData() = default;
1067       OperandData(Value *V, bool APO, bool IsUsed)
1068           : V(V), APO(APO), IsUsed(IsUsed) {}
1069       /// The operand value.
1070       Value *V = nullptr;
1071       /// TreeEntries only allow a single opcode, or an alternate sequence of
1072       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1073       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1074       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1075       /// (e.g., Add/Mul)
1076       bool APO = false;
1077       /// Helper data for the reordering function.
1078       bool IsUsed = false;
1079     };
1080 
1081     /// During operand reordering, we are trying to select the operand at lane
1082     /// that matches best with the operand at the neighboring lane. Our
1083     /// selection is based on the type of value we are looking for. For example,
1084     /// if the neighboring lane has a load, we need to look for a load that is
1085     /// accessing a consecutive address. These strategies are summarized in the
1086     /// 'ReorderingMode' enumerator.
1087     enum class ReorderingMode {
1088       Load,     ///< Matching loads to consecutive memory addresses
1089       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1090       Constant, ///< Matching constants
1091       Splat,    ///< Matching the same instruction multiple times (broadcast)
1092       Failed,   ///< We failed to create a vectorizable group
1093     };
1094 
1095     using OperandDataVec = SmallVector<OperandData, 2>;
1096 
1097     /// A vector of operand vectors.
1098     SmallVector<OperandDataVec, 4> OpsVec;
1099 
1100     const DataLayout &DL;
1101     ScalarEvolution &SE;
1102     const BoUpSLP &R;
1103 
1104     /// \returns the operand data at \p OpIdx and \p Lane.
1105     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1106       return OpsVec[OpIdx][Lane];
1107     }
1108 
1109     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1110     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1111       return OpsVec[OpIdx][Lane];
1112     }
1113 
1114     /// Clears the used flag for all entries.
1115     void clearUsed() {
1116       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1117            OpIdx != NumOperands; ++OpIdx)
1118         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1119              ++Lane)
1120           OpsVec[OpIdx][Lane].IsUsed = false;
1121     }
1122 
1123     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1124     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1125       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1126     }
1127 
1128     // The hard-coded scores listed here are not very important, though it shall
1129     // be higher for better matches to improve the resulting cost. When
1130     // computing the scores of matching one sub-tree with another, we are
1131     // basically counting the number of values that are matching. So even if all
1132     // scores are set to 1, we would still get a decent matching result.
1133     // However, sometimes we have to break ties. For example we may have to
1134     // choose between matching loads vs matching opcodes. This is what these
1135     // scores are helping us with: they provide the order of preference. Also,
1136     // this is important if the scalar is externally used or used in another
1137     // tree entry node in the different lane.
1138 
1139     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1140     static const int ScoreConsecutiveLoads = 4;
1141     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1142     static const int ScoreReversedLoads = 3;
1143     /// ExtractElementInst from same vector and consecutive indexes.
1144     static const int ScoreConsecutiveExtracts = 4;
1145     /// ExtractElementInst from same vector and reversed indices.
1146     static const int ScoreReversedExtracts = 3;
1147     /// Constants.
1148     static const int ScoreConstants = 2;
1149     /// Instructions with the same opcode.
1150     static const int ScoreSameOpcode = 2;
1151     /// Instructions with alt opcodes (e.g, add + sub).
1152     static const int ScoreAltOpcodes = 1;
1153     /// Identical instructions (a.k.a. splat or broadcast).
1154     static const int ScoreSplat = 1;
1155     /// Matching with an undef is preferable to failing.
1156     static const int ScoreUndef = 1;
1157     /// Score for failing to find a decent match.
1158     static const int ScoreFail = 0;
1159     /// Score if all users are vectorized.
1160     static const int ScoreAllUserVectorized = 1;
1161 
1162     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1163     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1164     /// MainAltOps.
1165     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1166                                ScalarEvolution &SE, int NumLanes,
1167                                ArrayRef<Value *> MainAltOps) {
1168       if (V1 == V2)
1169         return VLOperands::ScoreSplat;
1170 
1171       auto *LI1 = dyn_cast<LoadInst>(V1);
1172       auto *LI2 = dyn_cast<LoadInst>(V2);
1173       if (LI1 && LI2) {
1174         if (LI1->getParent() != LI2->getParent())
1175           return VLOperands::ScoreFail;
1176 
1177         Optional<int> Dist = getPointersDiff(
1178             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1179             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1180         if (!Dist || *Dist == 0)
1181           return VLOperands::ScoreFail;
1182         // The distance is too large - still may be profitable to use masked
1183         // loads/gathers.
1184         if (std::abs(*Dist) > NumLanes / 2)
1185           return VLOperands::ScoreAltOpcodes;
1186         // This still will detect consecutive loads, but we might have "holes"
1187         // in some cases. It is ok for non-power-2 vectorization and may produce
1188         // better results. It should not affect current vectorization.
1189         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1190                            : VLOperands::ScoreReversedLoads;
1191       }
1192 
1193       auto *C1 = dyn_cast<Constant>(V1);
1194       auto *C2 = dyn_cast<Constant>(V2);
1195       if (C1 && C2)
1196         return VLOperands::ScoreConstants;
1197 
1198       // Extracts from consecutive indexes of the same vector better score as
1199       // the extracts could be optimized away.
1200       Value *EV1;
1201       ConstantInt *Ex1Idx;
1202       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1203         // Undefs are always profitable for extractelements.
1204         if (isa<UndefValue>(V2))
1205           return VLOperands::ScoreConsecutiveExtracts;
1206         Value *EV2 = nullptr;
1207         ConstantInt *Ex2Idx = nullptr;
1208         if (match(V2,
1209                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1210                                                          m_Undef())))) {
1211           // Undefs are always profitable for extractelements.
1212           if (!Ex2Idx)
1213             return VLOperands::ScoreConsecutiveExtracts;
1214           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1215             return VLOperands::ScoreConsecutiveExtracts;
1216           if (EV2 == EV1) {
1217             int Idx1 = Ex1Idx->getZExtValue();
1218             int Idx2 = Ex2Idx->getZExtValue();
1219             int Dist = Idx2 - Idx1;
1220             // The distance is too large - still may be profitable to use
1221             // shuffles.
1222             if (std::abs(Dist) == 0)
1223               return VLOperands::ScoreSplat;
1224             if (std::abs(Dist) > NumLanes / 2)
1225               return VLOperands::ScoreSameOpcode;
1226             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1227                               : VLOperands::ScoreReversedExtracts;
1228           }
1229           return VLOperands::ScoreAltOpcodes;
1230         }
1231         return VLOperands::ScoreFail;
1232       }
1233 
1234       auto *I1 = dyn_cast<Instruction>(V1);
1235       auto *I2 = dyn_cast<Instruction>(V2);
1236       if (I1 && I2) {
1237         if (I1->getParent() != I2->getParent())
1238           return VLOperands::ScoreFail;
1239         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1240         Ops.push_back(I1);
1241         Ops.push_back(I2);
1242         InstructionsState S = getSameOpcode(Ops);
1243         // Note: Only consider instructions with <= 2 operands to avoid
1244         // complexity explosion.
1245         if (S.getOpcode() &&
1246             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1247              !S.isAltShuffle()) &&
1248             all_of(Ops, [&S](Value *V) {
1249               return cast<Instruction>(V)->getNumOperands() ==
1250                      S.MainOp->getNumOperands();
1251             }))
1252           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1253                                   : VLOperands::ScoreSameOpcode;
1254       }
1255 
1256       if (isa<UndefValue>(V2))
1257         return VLOperands::ScoreUndef;
1258 
1259       return VLOperands::ScoreFail;
1260     }
1261 
1262     /// \param Lane lane of the operands under analysis.
1263     /// \param OpIdx operand index in \p Lane lane we're looking the best
1264     /// candidate for.
1265     /// \param Idx operand index of the current candidate value.
1266     /// \returns The additional score due to possible broadcasting of the
1267     /// elements in the lane. It is more profitable to have power-of-2 unique
1268     /// elements in the lane, it will be vectorized with higher probability
1269     /// after removing duplicates. Currently the SLP vectorizer supports only
1270     /// vectorization of the power-of-2 number of unique scalars.
1271     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1272       Value *IdxLaneV = getData(Idx, Lane).V;
1273       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1274         return 0;
1275       SmallPtrSet<Value *, 4> Uniques;
1276       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1277         if (Ln == Lane)
1278           continue;
1279         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1280         if (!isa<Instruction>(OpIdxLnV))
1281           return 0;
1282         Uniques.insert(OpIdxLnV);
1283       }
1284       int UniquesCount = Uniques.size();
1285       int UniquesCntWithIdxLaneV =
1286           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1287       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1288       int UniquesCntWithOpIdxLaneV =
1289           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1290       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1291         return 0;
1292       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1293               UniquesCntWithOpIdxLaneV) -
1294              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1295     }
1296 
1297     /// \param Lane lane of the operands under analysis.
1298     /// \param OpIdx operand index in \p Lane lane we're looking the best
1299     /// candidate for.
1300     /// \param Idx operand index of the current candidate value.
1301     /// \returns The additional score for the scalar which users are all
1302     /// vectorized.
1303     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1304       Value *IdxLaneV = getData(Idx, Lane).V;
1305       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1306       // Do not care about number of uses for vector-like instructions
1307       // (extractelement/extractvalue with constant indices), they are extracts
1308       // themselves and already externally used. Vectorization of such
1309       // instructions does not add extra extractelement instruction, just may
1310       // remove it.
1311       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1312           isVectorLikeInstWithConstOps(OpIdxLaneV))
1313         return VLOperands::ScoreAllUserVectorized;
1314       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1315       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1316         return 0;
1317       return R.areAllUsersVectorized(IdxLaneI, None)
1318                  ? VLOperands::ScoreAllUserVectorized
1319                  : 0;
1320     }
1321 
1322     /// Go through the operands of \p LHS and \p RHS recursively until \p
1323     /// MaxLevel, and return the cummulative score. For example:
1324     /// \verbatim
1325     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1326     ///     \ /         \ /         \ /        \ /
1327     ///      +           +           +          +
1328     ///     G1          G2          G3         G4
1329     /// \endverbatim
1330     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1331     /// each level recursively, accumulating the score. It starts from matching
1332     /// the additions at level 0, then moves on to the loads (level 1). The
1333     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1334     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1335     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1336     /// Please note that the order of the operands does not matter, as we
1337     /// evaluate the score of all profitable combinations of operands. In
1338     /// other words the score of G1 and G4 is the same as G1 and G2. This
1339     /// heuristic is based on ideas described in:
1340     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1341     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1342     ///   Luís F. W. Góes
1343     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1344                            ArrayRef<Value *> MainAltOps) {
1345 
1346       // Get the shallow score of V1 and V2.
1347       int ShallowScoreAtThisLevel =
1348           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1349 
1350       // If reached MaxLevel,
1351       //  or if V1 and V2 are not instructions,
1352       //  or if they are SPLAT,
1353       //  or if they are not consecutive,
1354       //  or if profitable to vectorize loads or extractelements, early return
1355       //  the current cost.
1356       auto *I1 = dyn_cast<Instruction>(LHS);
1357       auto *I2 = dyn_cast<Instruction>(RHS);
1358       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1359           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1360           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1361             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1362             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1363            ShallowScoreAtThisLevel))
1364         return ShallowScoreAtThisLevel;
1365       assert(I1 && I2 && "Should have early exited.");
1366 
1367       // Contains the I2 operand indexes that got matched with I1 operands.
1368       SmallSet<unsigned, 4> Op2Used;
1369 
1370       // Recursion towards the operands of I1 and I2. We are trying all possible
1371       // operand pairs, and keeping track of the best score.
1372       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1373            OpIdx1 != NumOperands1; ++OpIdx1) {
1374         // Try to pair op1I with the best operand of I2.
1375         int MaxTmpScore = 0;
1376         unsigned MaxOpIdx2 = 0;
1377         bool FoundBest = false;
1378         // If I2 is commutative try all combinations.
1379         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1380         unsigned ToIdx = isCommutative(I2)
1381                              ? I2->getNumOperands()
1382                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1383         assert(FromIdx <= ToIdx && "Bad index");
1384         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1385           // Skip operands already paired with OpIdx1.
1386           if (Op2Used.count(OpIdx2))
1387             continue;
1388           // Recursively calculate the cost at each level
1389           int TmpScore =
1390               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1391                                  CurrLevel + 1, MaxLevel, None);
1392           // Look for the best score.
1393           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1394             MaxTmpScore = TmpScore;
1395             MaxOpIdx2 = OpIdx2;
1396             FoundBest = true;
1397           }
1398         }
1399         if (FoundBest) {
1400           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1401           Op2Used.insert(MaxOpIdx2);
1402           ShallowScoreAtThisLevel += MaxTmpScore;
1403         }
1404       }
1405       return ShallowScoreAtThisLevel;
1406     }
1407 
1408     /// Score scaling factor for fully compatible instructions but with
1409     /// different number of external uses. Allows better selection of the
1410     /// instructions with less external uses.
1411     static const int ScoreScaleFactor = 10;
1412 
1413     /// \Returns the look-ahead score, which tells us how much the sub-trees
1414     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1415     /// score. This helps break ties in an informed way when we cannot decide on
1416     /// the order of the operands by just considering the immediate
1417     /// predecessors.
1418     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1419                           int Lane, unsigned OpIdx, unsigned Idx,
1420                           bool &IsUsed) {
1421       int Score =
1422           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1423       if (Score) {
1424         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1425         if (Score <= -SplatScore) {
1426           // Set the minimum score for splat-like sequence to avoid setting
1427           // failed state.
1428           Score = 1;
1429         } else {
1430           Score += SplatScore;
1431           // Scale score to see the difference between different operands
1432           // and similar operands but all vectorized/not all vectorized
1433           // uses. It does not affect actual selection of the best
1434           // compatible operand in general, just allows to select the
1435           // operand with all vectorized uses.
1436           Score *= ScoreScaleFactor;
1437           Score += getExternalUseScore(Lane, OpIdx, Idx);
1438           IsUsed = true;
1439         }
1440       }
1441       return Score;
1442     }
1443 
1444     /// Best defined scores per lanes between the passes. Used to choose the
1445     /// best operand (with the highest score) between the passes.
1446     /// The key - {Operand Index, Lane}.
1447     /// The value - the best score between the passes for the lane and the
1448     /// operand.
1449     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1450         BestScoresPerLanes;
1451 
1452     // Search all operands in Ops[*][Lane] for the one that matches best
1453     // Ops[OpIdx][LastLane] and return its opreand index.
1454     // If no good match can be found, return None.
1455     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1456                                       ArrayRef<ReorderingMode> ReorderingModes,
1457                                       ArrayRef<Value *> MainAltOps) {
1458       unsigned NumOperands = getNumOperands();
1459 
1460       // The operand of the previous lane at OpIdx.
1461       Value *OpLastLane = getData(OpIdx, LastLane).V;
1462 
1463       // Our strategy mode for OpIdx.
1464       ReorderingMode RMode = ReorderingModes[OpIdx];
1465       if (RMode == ReorderingMode::Failed)
1466         return None;
1467 
1468       // The linearized opcode of the operand at OpIdx, Lane.
1469       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1470 
1471       // The best operand index and its score.
1472       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1473       // are using the score to differentiate between the two.
1474       struct BestOpData {
1475         Optional<unsigned> Idx = None;
1476         unsigned Score = 0;
1477       } BestOp;
1478       BestOp.Score =
1479           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1480               .first->second;
1481 
1482       // Track if the operand must be marked as used. If the operand is set to
1483       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1484       // want to reestimate the operands again on the following iterations).
1485       bool IsUsed =
1486           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1487       // Iterate through all unused operands and look for the best.
1488       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1489         // Get the operand at Idx and Lane.
1490         OperandData &OpData = getData(Idx, Lane);
1491         Value *Op = OpData.V;
1492         bool OpAPO = OpData.APO;
1493 
1494         // Skip already selected operands.
1495         if (OpData.IsUsed)
1496           continue;
1497 
1498         // Skip if we are trying to move the operand to a position with a
1499         // different opcode in the linearized tree form. This would break the
1500         // semantics.
1501         if (OpAPO != OpIdxAPO)
1502           continue;
1503 
1504         // Look for an operand that matches the current mode.
1505         switch (RMode) {
1506         case ReorderingMode::Load:
1507         case ReorderingMode::Constant:
1508         case ReorderingMode::Opcode: {
1509           bool LeftToRight = Lane > LastLane;
1510           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1511           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1512           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1513                                         OpIdx, Idx, IsUsed);
1514           if (Score > static_cast<int>(BestOp.Score)) {
1515             BestOp.Idx = Idx;
1516             BestOp.Score = Score;
1517             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1518           }
1519           break;
1520         }
1521         case ReorderingMode::Splat:
1522           if (Op == OpLastLane)
1523             BestOp.Idx = Idx;
1524           break;
1525         case ReorderingMode::Failed:
1526           llvm_unreachable("Not expected Failed reordering mode.");
1527         }
1528       }
1529 
1530       if (BestOp.Idx) {
1531         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1532         return BestOp.Idx;
1533       }
1534       // If we could not find a good match return None.
1535       return None;
1536     }
1537 
1538     /// Helper for reorderOperandVecs.
1539     /// \returns the lane that we should start reordering from. This is the one
1540     /// which has the least number of operands that can freely move about or
1541     /// less profitable because it already has the most optimal set of operands.
1542     unsigned getBestLaneToStartReordering() const {
1543       unsigned Min = UINT_MAX;
1544       unsigned SameOpNumber = 0;
1545       // std::pair<unsigned, unsigned> is used to implement a simple voting
1546       // algorithm and choose the lane with the least number of operands that
1547       // can freely move about or less profitable because it already has the
1548       // most optimal set of operands. The first unsigned is a counter for
1549       // voting, the second unsigned is the counter of lanes with instructions
1550       // with same/alternate opcodes and same parent basic block.
1551       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1552       // Try to be closer to the original results, if we have multiple lanes
1553       // with same cost. If 2 lanes have the same cost, use the one with the
1554       // lowest index.
1555       for (int I = getNumLanes(); I > 0; --I) {
1556         unsigned Lane = I - 1;
1557         OperandsOrderData NumFreeOpsHash =
1558             getMaxNumOperandsThatCanBeReordered(Lane);
1559         // Compare the number of operands that can move and choose the one with
1560         // the least number.
1561         if (NumFreeOpsHash.NumOfAPOs < Min) {
1562           Min = NumFreeOpsHash.NumOfAPOs;
1563           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1564           HashMap.clear();
1565           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1566         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1567                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1568           // Select the most optimal lane in terms of number of operands that
1569           // should be moved around.
1570           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1571           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1572         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1573                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1574           auto It = HashMap.find(NumFreeOpsHash.Hash);
1575           if (It == HashMap.end())
1576             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1577           else
1578             ++It->second.first;
1579         }
1580       }
1581       // Select the lane with the minimum counter.
1582       unsigned BestLane = 0;
1583       unsigned CntMin = UINT_MAX;
1584       for (const auto &Data : reverse(HashMap)) {
1585         if (Data.second.first < CntMin) {
1586           CntMin = Data.second.first;
1587           BestLane = Data.second.second;
1588         }
1589       }
1590       return BestLane;
1591     }
1592 
1593     /// Data structure that helps to reorder operands.
1594     struct OperandsOrderData {
1595       /// The best number of operands with the same APOs, which can be
1596       /// reordered.
1597       unsigned NumOfAPOs = UINT_MAX;
1598       /// Number of operands with the same/alternate instruction opcode and
1599       /// parent.
1600       unsigned NumOpsWithSameOpcodeParent = 0;
1601       /// Hash for the actual operands ordering.
1602       /// Used to count operands, actually their position id and opcode
1603       /// value. It is used in the voting mechanism to find the lane with the
1604       /// least number of operands that can freely move about or less profitable
1605       /// because it already has the most optimal set of operands. Can be
1606       /// replaced with SmallVector<unsigned> instead but hash code is faster
1607       /// and requires less memory.
1608       unsigned Hash = 0;
1609     };
1610     /// \returns the maximum number of operands that are allowed to be reordered
1611     /// for \p Lane and the number of compatible instructions(with the same
1612     /// parent/opcode). This is used as a heuristic for selecting the first lane
1613     /// to start operand reordering.
1614     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1615       unsigned CntTrue = 0;
1616       unsigned NumOperands = getNumOperands();
1617       // Operands with the same APO can be reordered. We therefore need to count
1618       // how many of them we have for each APO, like this: Cnt[APO] = x.
1619       // Since we only have two APOs, namely true and false, we can avoid using
1620       // a map. Instead we can simply count the number of operands that
1621       // correspond to one of them (in this case the 'true' APO), and calculate
1622       // the other by subtracting it from the total number of operands.
1623       // Operands with the same instruction opcode and parent are more
1624       // profitable since we don't need to move them in many cases, with a high
1625       // probability such lane already can be vectorized effectively.
1626       bool AllUndefs = true;
1627       unsigned NumOpsWithSameOpcodeParent = 0;
1628       Instruction *OpcodeI = nullptr;
1629       BasicBlock *Parent = nullptr;
1630       unsigned Hash = 0;
1631       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1632         const OperandData &OpData = getData(OpIdx, Lane);
1633         if (OpData.APO)
1634           ++CntTrue;
1635         // Use Boyer-Moore majority voting for finding the majority opcode and
1636         // the number of times it occurs.
1637         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1638           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1639               I->getParent() != Parent) {
1640             if (NumOpsWithSameOpcodeParent == 0) {
1641               NumOpsWithSameOpcodeParent = 1;
1642               OpcodeI = I;
1643               Parent = I->getParent();
1644             } else {
1645               --NumOpsWithSameOpcodeParent;
1646             }
1647           } else {
1648             ++NumOpsWithSameOpcodeParent;
1649           }
1650         }
1651         Hash = hash_combine(
1652             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1653         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1654       }
1655       if (AllUndefs)
1656         return {};
1657       OperandsOrderData Data;
1658       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1659       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1660       Data.Hash = Hash;
1661       return Data;
1662     }
1663 
1664     /// Go through the instructions in VL and append their operands.
1665     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1666       assert(!VL.empty() && "Bad VL");
1667       assert((empty() || VL.size() == getNumLanes()) &&
1668              "Expected same number of lanes");
1669       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1670       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1671       OpsVec.resize(NumOperands);
1672       unsigned NumLanes = VL.size();
1673       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1674         OpsVec[OpIdx].resize(NumLanes);
1675         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1676           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1677           // Our tree has just 3 nodes: the root and two operands.
1678           // It is therefore trivial to get the APO. We only need to check the
1679           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1680           // RHS operand. The LHS operand of both add and sub is never attached
1681           // to an inversese operation in the linearized form, therefore its APO
1682           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1683 
1684           // Since operand reordering is performed on groups of commutative
1685           // operations or alternating sequences (e.g., +, -), we can safely
1686           // tell the inverse operations by checking commutativity.
1687           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1688           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1689           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1690                                  APO, false};
1691         }
1692       }
1693     }
1694 
1695     /// \returns the number of operands.
1696     unsigned getNumOperands() const { return OpsVec.size(); }
1697 
1698     /// \returns the number of lanes.
1699     unsigned getNumLanes() const { return OpsVec[0].size(); }
1700 
1701     /// \returns the operand value at \p OpIdx and \p Lane.
1702     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1703       return getData(OpIdx, Lane).V;
1704     }
1705 
1706     /// \returns true if the data structure is empty.
1707     bool empty() const { return OpsVec.empty(); }
1708 
1709     /// Clears the data.
1710     void clear() { OpsVec.clear(); }
1711 
1712     /// \Returns true if there are enough operands identical to \p Op to fill
1713     /// the whole vector.
1714     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1715     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1716       bool OpAPO = getData(OpIdx, Lane).APO;
1717       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1718         if (Ln == Lane)
1719           continue;
1720         // This is set to true if we found a candidate for broadcast at Lane.
1721         bool FoundCandidate = false;
1722         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1723           OperandData &Data = getData(OpI, Ln);
1724           if (Data.APO != OpAPO || Data.IsUsed)
1725             continue;
1726           if (Data.V == Op) {
1727             FoundCandidate = true;
1728             Data.IsUsed = true;
1729             break;
1730           }
1731         }
1732         if (!FoundCandidate)
1733           return false;
1734       }
1735       return true;
1736     }
1737 
1738   public:
1739     /// Initialize with all the operands of the instruction vector \p RootVL.
1740     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1741                ScalarEvolution &SE, const BoUpSLP &R)
1742         : DL(DL), SE(SE), R(R) {
1743       // Append all the operands of RootVL.
1744       appendOperandsOfVL(RootVL);
1745     }
1746 
1747     /// \Returns a value vector with the operands across all lanes for the
1748     /// opearnd at \p OpIdx.
1749     ValueList getVL(unsigned OpIdx) const {
1750       ValueList OpVL(OpsVec[OpIdx].size());
1751       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1752              "Expected same num of lanes across all operands");
1753       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1754         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1755       return OpVL;
1756     }
1757 
1758     // Performs operand reordering for 2 or more operands.
1759     // The original operands are in OrigOps[OpIdx][Lane].
1760     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1761     void reorder() {
1762       unsigned NumOperands = getNumOperands();
1763       unsigned NumLanes = getNumLanes();
1764       // Each operand has its own mode. We are using this mode to help us select
1765       // the instructions for each lane, so that they match best with the ones
1766       // we have selected so far.
1767       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1768 
1769       // This is a greedy single-pass algorithm. We are going over each lane
1770       // once and deciding on the best order right away with no back-tracking.
1771       // However, in order to increase its effectiveness, we start with the lane
1772       // that has operands that can move the least. For example, given the
1773       // following lanes:
1774       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1775       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1776       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1777       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1778       // we will start at Lane 1, since the operands of the subtraction cannot
1779       // be reordered. Then we will visit the rest of the lanes in a circular
1780       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1781 
1782       // Find the first lane that we will start our search from.
1783       unsigned FirstLane = getBestLaneToStartReordering();
1784 
1785       // Initialize the modes.
1786       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1787         Value *OpLane0 = getValue(OpIdx, FirstLane);
1788         // Keep track if we have instructions with all the same opcode on one
1789         // side.
1790         if (isa<LoadInst>(OpLane0))
1791           ReorderingModes[OpIdx] = ReorderingMode::Load;
1792         else if (isa<Instruction>(OpLane0)) {
1793           // Check if OpLane0 should be broadcast.
1794           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1795             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1796           else
1797             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1798         }
1799         else if (isa<Constant>(OpLane0))
1800           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1801         else if (isa<Argument>(OpLane0))
1802           // Our best hope is a Splat. It may save some cost in some cases.
1803           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1804         else
1805           // NOTE: This should be unreachable.
1806           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1807       }
1808 
1809       // Check that we don't have same operands. No need to reorder if operands
1810       // are just perfect diamond or shuffled diamond match. Do not do it only
1811       // for possible broadcasts or non-power of 2 number of scalars (just for
1812       // now).
1813       auto &&SkipReordering = [this]() {
1814         SmallPtrSet<Value *, 4> UniqueValues;
1815         ArrayRef<OperandData> Op0 = OpsVec.front();
1816         for (const OperandData &Data : Op0)
1817           UniqueValues.insert(Data.V);
1818         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1819           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1820                 return !UniqueValues.contains(Data.V);
1821               }))
1822             return false;
1823         }
1824         // TODO: Check if we can remove a check for non-power-2 number of
1825         // scalars after full support of non-power-2 vectorization.
1826         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1827       };
1828 
1829       // If the initial strategy fails for any of the operand indexes, then we
1830       // perform reordering again in a second pass. This helps avoid assigning
1831       // high priority to the failed strategy, and should improve reordering for
1832       // the non-failed operand indexes.
1833       for (int Pass = 0; Pass != 2; ++Pass) {
1834         // Check if no need to reorder operands since they're are perfect or
1835         // shuffled diamond match.
1836         // Need to to do it to avoid extra external use cost counting for
1837         // shuffled matches, which may cause regressions.
1838         if (SkipReordering())
1839           break;
1840         // Skip the second pass if the first pass did not fail.
1841         bool StrategyFailed = false;
1842         // Mark all operand data as free to use.
1843         clearUsed();
1844         // We keep the original operand order for the FirstLane, so reorder the
1845         // rest of the lanes. We are visiting the nodes in a circular fashion,
1846         // using FirstLane as the center point and increasing the radius
1847         // distance.
1848         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1849         for (unsigned I = 0; I < NumOperands; ++I)
1850           MainAltOps[I].push_back(getData(I, FirstLane).V);
1851 
1852         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1853           // Visit the lane on the right and then the lane on the left.
1854           for (int Direction : {+1, -1}) {
1855             int Lane = FirstLane + Direction * Distance;
1856             if (Lane < 0 || Lane >= (int)NumLanes)
1857               continue;
1858             int LastLane = Lane - Direction;
1859             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1860                    "Out of bounds");
1861             // Look for a good match for each operand.
1862             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1863               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1864               Optional<unsigned> BestIdx = getBestOperand(
1865                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1866               // By not selecting a value, we allow the operands that follow to
1867               // select a better matching value. We will get a non-null value in
1868               // the next run of getBestOperand().
1869               if (BestIdx) {
1870                 // Swap the current operand with the one returned by
1871                 // getBestOperand().
1872                 swap(OpIdx, BestIdx.getValue(), Lane);
1873               } else {
1874                 // We failed to find a best operand, set mode to 'Failed'.
1875                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1876                 // Enable the second pass.
1877                 StrategyFailed = true;
1878               }
1879               // Try to get the alternate opcode and follow it during analysis.
1880               if (MainAltOps[OpIdx].size() != 2) {
1881                 OperandData &AltOp = getData(OpIdx, Lane);
1882                 InstructionsState OpS =
1883                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1884                 if (OpS.getOpcode() && OpS.isAltShuffle())
1885                   MainAltOps[OpIdx].push_back(AltOp.V);
1886               }
1887             }
1888           }
1889         }
1890         // Skip second pass if the strategy did not fail.
1891         if (!StrategyFailed)
1892           break;
1893       }
1894     }
1895 
1896 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1897     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1898       switch (RMode) {
1899       case ReorderingMode::Load:
1900         return "Load";
1901       case ReorderingMode::Opcode:
1902         return "Opcode";
1903       case ReorderingMode::Constant:
1904         return "Constant";
1905       case ReorderingMode::Splat:
1906         return "Splat";
1907       case ReorderingMode::Failed:
1908         return "Failed";
1909       }
1910       llvm_unreachable("Unimplemented Reordering Type");
1911     }
1912 
1913     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1914                                                    raw_ostream &OS) {
1915       return OS << getModeStr(RMode);
1916     }
1917 
1918     /// Debug print.
1919     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1920       printMode(RMode, dbgs());
1921     }
1922 
1923     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1924       return printMode(RMode, OS);
1925     }
1926 
1927     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1928       const unsigned Indent = 2;
1929       unsigned Cnt = 0;
1930       for (const OperandDataVec &OpDataVec : OpsVec) {
1931         OS << "Operand " << Cnt++ << "\n";
1932         for (const OperandData &OpData : OpDataVec) {
1933           OS.indent(Indent) << "{";
1934           if (Value *V = OpData.V)
1935             OS << *V;
1936           else
1937             OS << "null";
1938           OS << ", APO:" << OpData.APO << "}\n";
1939         }
1940         OS << "\n";
1941       }
1942       return OS;
1943     }
1944 
1945     /// Debug print.
1946     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1947 #endif
1948   };
1949 
1950   /// Checks if the instruction is marked for deletion.
1951   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1952 
1953   /// Marks values operands for later deletion by replacing them with Undefs.
1954   void eraseInstructions(ArrayRef<Value *> AV);
1955 
1956   ~BoUpSLP();
1957 
1958 private:
1959   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1960   /// reordering (i.e. the operands can be reordered because they have only one
1961   /// user and reordarable).
1962   /// \param NonVectorized List of all gather nodes that require reordering
1963   /// (e.g., gather of extractlements or partially vectorizable loads).
1964   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1965   /// reordering, subset of \p NonVectorized.
1966   bool
1967   canReorderOperands(TreeEntry *UserTE,
1968                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1969                      ArrayRef<TreeEntry *> ReorderableGathers,
1970                      SmallVectorImpl<TreeEntry *> &GatherOps);
1971 
1972   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1973   /// if any. If it is not vectorized (gather node), returns nullptr.
1974   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1975     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1976     TreeEntry *TE = nullptr;
1977     const auto *It = find_if(VL, [this, &TE](Value *V) {
1978       TE = getTreeEntry(V);
1979       return TE;
1980     });
1981     if (It != VL.end() && TE->isSame(VL))
1982       return TE;
1983     return nullptr;
1984   }
1985 
1986   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1987   /// if any. If it is not vectorized (gather node), returns nullptr.
1988   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
1989                                         unsigned OpIdx) const {
1990     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
1991         const_cast<TreeEntry *>(UserTE), OpIdx);
1992   }
1993 
1994   /// Checks if all users of \p I are the part of the vectorization tree.
1995   bool areAllUsersVectorized(Instruction *I,
1996                              ArrayRef<Value *> VectorizedVals) const;
1997 
1998   /// \returns the cost of the vectorizable entry.
1999   InstructionCost getEntryCost(const TreeEntry *E,
2000                                ArrayRef<Value *> VectorizedVals);
2001 
2002   /// This is the recursive part of buildTree.
2003   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2004                      const EdgeInfo &EI);
2005 
2006   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2007   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2008   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2009   /// returns false, setting \p CurrentOrder to either an empty vector or a
2010   /// non-identity permutation that allows to reuse extract instructions.
2011   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2012                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2013 
2014   /// Vectorize a single entry in the tree.
2015   Value *vectorizeTree(TreeEntry *E);
2016 
2017   /// Vectorize a single entry in the tree, starting in \p VL.
2018   Value *vectorizeTree(ArrayRef<Value *> VL);
2019 
2020   /// Create a new vector from a list of scalar values.  Produces a sequence
2021   /// which exploits values reused across lanes, and arranges the inserts
2022   /// for ease of later optimization.
2023   Value *createBuildVector(ArrayRef<Value *> VL);
2024 
2025   /// \returns the scalarization cost for this type. Scalarization in this
2026   /// context means the creation of vectors from a group of scalars. If \p
2027   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2028   /// vector elements.
2029   InstructionCost getGatherCost(FixedVectorType *Ty,
2030                                 const APInt &ShuffledIndices,
2031                                 bool NeedToShuffle) const;
2032 
2033   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2034   /// tree entries.
2035   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2036   /// previous tree entries. \p Mask is filled with the shuffle mask.
2037   Optional<TargetTransformInfo::ShuffleKind>
2038   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2039                         SmallVectorImpl<const TreeEntry *> &Entries);
2040 
2041   /// \returns the scalarization cost for this list of values. Assuming that
2042   /// this subtree gets vectorized, we may need to extract the values from the
2043   /// roots. This method calculates the cost of extracting the values.
2044   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2045 
2046   /// Set the Builder insert point to one after the last instruction in
2047   /// the bundle
2048   void setInsertPointAfterBundle(const TreeEntry *E);
2049 
2050   /// \returns a vector from a collection of scalars in \p VL.
2051   Value *gather(ArrayRef<Value *> VL);
2052 
2053   /// \returns whether the VectorizableTree is fully vectorizable and will
2054   /// be beneficial even the tree height is tiny.
2055   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2056 
2057   /// Reorder commutative or alt operands to get better probability of
2058   /// generating vectorized code.
2059   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2060                                              SmallVectorImpl<Value *> &Left,
2061                                              SmallVectorImpl<Value *> &Right,
2062                                              const DataLayout &DL,
2063                                              ScalarEvolution &SE,
2064                                              const BoUpSLP &R);
2065   struct TreeEntry {
2066     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2067     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2068 
2069     /// \returns true if the scalars in VL are equal to this entry.
2070     bool isSame(ArrayRef<Value *> VL) const {
2071       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2072         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2073           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2074         return VL.size() == Mask.size() &&
2075                std::equal(VL.begin(), VL.end(), Mask.begin(),
2076                           [Scalars](Value *V, int Idx) {
2077                             return (isa<UndefValue>(V) &&
2078                                     Idx == UndefMaskElem) ||
2079                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2080                           });
2081       };
2082       if (!ReorderIndices.empty()) {
2083         // TODO: implement matching if the nodes are just reordered, still can
2084         // treat the vector as the same if the list of scalars matches VL
2085         // directly, without reordering.
2086         SmallVector<int> Mask;
2087         inversePermutation(ReorderIndices, Mask);
2088         if (VL.size() == Scalars.size())
2089           return IsSame(Scalars, Mask);
2090         if (VL.size() == ReuseShuffleIndices.size()) {
2091           ::addMask(Mask, ReuseShuffleIndices);
2092           return IsSame(Scalars, Mask);
2093         }
2094         return false;
2095       }
2096       return IsSame(Scalars, ReuseShuffleIndices);
2097     }
2098 
2099     /// \returns true if current entry has same operands as \p TE.
2100     bool hasEqualOperands(const TreeEntry &TE) const {
2101       if (TE.getNumOperands() != getNumOperands())
2102         return false;
2103       SmallBitVector Used(getNumOperands());
2104       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2105         unsigned PrevCount = Used.count();
2106         for (unsigned K = 0; K < E; ++K) {
2107           if (Used.test(K))
2108             continue;
2109           if (getOperand(K) == TE.getOperand(I)) {
2110             Used.set(K);
2111             break;
2112           }
2113         }
2114         // Check if we actually found the matching operand.
2115         if (PrevCount == Used.count())
2116           return false;
2117       }
2118       return true;
2119     }
2120 
2121     /// \return Final vectorization factor for the node. Defined by the total
2122     /// number of vectorized scalars, including those, used several times in the
2123     /// entry and counted in the \a ReuseShuffleIndices, if any.
2124     unsigned getVectorFactor() const {
2125       if (!ReuseShuffleIndices.empty())
2126         return ReuseShuffleIndices.size();
2127       return Scalars.size();
2128     };
2129 
2130     /// A vector of scalars.
2131     ValueList Scalars;
2132 
2133     /// The Scalars are vectorized into this value. It is initialized to Null.
2134     Value *VectorizedValue = nullptr;
2135 
2136     /// Do we need to gather this sequence or vectorize it
2137     /// (either with vector instruction or with scatter/gather
2138     /// intrinsics for store/load)?
2139     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2140     EntryState State;
2141 
2142     /// Does this sequence require some shuffling?
2143     SmallVector<int, 4> ReuseShuffleIndices;
2144 
2145     /// Does this entry require reordering?
2146     SmallVector<unsigned, 4> ReorderIndices;
2147 
2148     /// Points back to the VectorizableTree.
2149     ///
2150     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2151     /// to be a pointer and needs to be able to initialize the child iterator.
2152     /// Thus we need a reference back to the container to translate the indices
2153     /// to entries.
2154     VecTreeTy &Container;
2155 
2156     /// The TreeEntry index containing the user of this entry.  We can actually
2157     /// have multiple users so the data structure is not truly a tree.
2158     SmallVector<EdgeInfo, 1> UserTreeIndices;
2159 
2160     /// The index of this treeEntry in VectorizableTree.
2161     int Idx = -1;
2162 
2163   private:
2164     /// The operands of each instruction in each lane Operands[op_index][lane].
2165     /// Note: This helps avoid the replication of the code that performs the
2166     /// reordering of operands during buildTree_rec() and vectorizeTree().
2167     SmallVector<ValueList, 2> Operands;
2168 
2169     /// The main/alternate instruction.
2170     Instruction *MainOp = nullptr;
2171     Instruction *AltOp = nullptr;
2172 
2173   public:
2174     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2175     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2176       if (Operands.size() < OpIdx + 1)
2177         Operands.resize(OpIdx + 1);
2178       assert(Operands[OpIdx].empty() && "Already resized?");
2179       assert(OpVL.size() <= Scalars.size() &&
2180              "Number of operands is greater than the number of scalars.");
2181       Operands[OpIdx].resize(OpVL.size());
2182       copy(OpVL, Operands[OpIdx].begin());
2183     }
2184 
2185     /// Set the operands of this bundle in their original order.
2186     void setOperandsInOrder() {
2187       assert(Operands.empty() && "Already initialized?");
2188       auto *I0 = cast<Instruction>(Scalars[0]);
2189       Operands.resize(I0->getNumOperands());
2190       unsigned NumLanes = Scalars.size();
2191       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2192            OpIdx != NumOperands; ++OpIdx) {
2193         Operands[OpIdx].resize(NumLanes);
2194         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2195           auto *I = cast<Instruction>(Scalars[Lane]);
2196           assert(I->getNumOperands() == NumOperands &&
2197                  "Expected same number of operands");
2198           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2199         }
2200       }
2201     }
2202 
2203     /// Reorders operands of the node to the given mask \p Mask.
2204     void reorderOperands(ArrayRef<int> Mask) {
2205       for (ValueList &Operand : Operands)
2206         reorderScalars(Operand, Mask);
2207     }
2208 
2209     /// \returns the \p OpIdx operand of this TreeEntry.
2210     ValueList &getOperand(unsigned OpIdx) {
2211       assert(OpIdx < Operands.size() && "Off bounds");
2212       return Operands[OpIdx];
2213     }
2214 
2215     /// \returns the \p OpIdx operand of this TreeEntry.
2216     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2217       assert(OpIdx < Operands.size() && "Off bounds");
2218       return Operands[OpIdx];
2219     }
2220 
2221     /// \returns the number of operands.
2222     unsigned getNumOperands() const { return Operands.size(); }
2223 
2224     /// \return the single \p OpIdx operand.
2225     Value *getSingleOperand(unsigned OpIdx) const {
2226       assert(OpIdx < Operands.size() && "Off bounds");
2227       assert(!Operands[OpIdx].empty() && "No operand available");
2228       return Operands[OpIdx][0];
2229     }
2230 
2231     /// Some of the instructions in the list have alternate opcodes.
2232     bool isAltShuffle() const { return MainOp != AltOp; }
2233 
2234     bool isOpcodeOrAlt(Instruction *I) const {
2235       unsigned CheckedOpcode = I->getOpcode();
2236       return (getOpcode() == CheckedOpcode ||
2237               getAltOpcode() == CheckedOpcode);
2238     }
2239 
2240     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2241     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2242     /// \p OpValue.
2243     Value *isOneOf(Value *Op) const {
2244       auto *I = dyn_cast<Instruction>(Op);
2245       if (I && isOpcodeOrAlt(I))
2246         return Op;
2247       return MainOp;
2248     }
2249 
2250     void setOperations(const InstructionsState &S) {
2251       MainOp = S.MainOp;
2252       AltOp = S.AltOp;
2253     }
2254 
2255     Instruction *getMainOp() const {
2256       return MainOp;
2257     }
2258 
2259     Instruction *getAltOp() const {
2260       return AltOp;
2261     }
2262 
2263     /// The main/alternate opcodes for the list of instructions.
2264     unsigned getOpcode() const {
2265       return MainOp ? MainOp->getOpcode() : 0;
2266     }
2267 
2268     unsigned getAltOpcode() const {
2269       return AltOp ? AltOp->getOpcode() : 0;
2270     }
2271 
2272     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2273     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2274     int findLaneForValue(Value *V) const {
2275       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2276       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2277       if (!ReorderIndices.empty())
2278         FoundLane = ReorderIndices[FoundLane];
2279       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2280       if (!ReuseShuffleIndices.empty()) {
2281         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2282                                   find(ReuseShuffleIndices, FoundLane));
2283       }
2284       return FoundLane;
2285     }
2286 
2287 #ifndef NDEBUG
2288     /// Debug printer.
2289     LLVM_DUMP_METHOD void dump() const {
2290       dbgs() << Idx << ".\n";
2291       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2292         dbgs() << "Operand " << OpI << ":\n";
2293         for (const Value *V : Operands[OpI])
2294           dbgs().indent(2) << *V << "\n";
2295       }
2296       dbgs() << "Scalars: \n";
2297       for (Value *V : Scalars)
2298         dbgs().indent(2) << *V << "\n";
2299       dbgs() << "State: ";
2300       switch (State) {
2301       case Vectorize:
2302         dbgs() << "Vectorize\n";
2303         break;
2304       case ScatterVectorize:
2305         dbgs() << "ScatterVectorize\n";
2306         break;
2307       case NeedToGather:
2308         dbgs() << "NeedToGather\n";
2309         break;
2310       }
2311       dbgs() << "MainOp: ";
2312       if (MainOp)
2313         dbgs() << *MainOp << "\n";
2314       else
2315         dbgs() << "NULL\n";
2316       dbgs() << "AltOp: ";
2317       if (AltOp)
2318         dbgs() << *AltOp << "\n";
2319       else
2320         dbgs() << "NULL\n";
2321       dbgs() << "VectorizedValue: ";
2322       if (VectorizedValue)
2323         dbgs() << *VectorizedValue << "\n";
2324       else
2325         dbgs() << "NULL\n";
2326       dbgs() << "ReuseShuffleIndices: ";
2327       if (ReuseShuffleIndices.empty())
2328         dbgs() << "Empty";
2329       else
2330         for (int ReuseIdx : ReuseShuffleIndices)
2331           dbgs() << ReuseIdx << ", ";
2332       dbgs() << "\n";
2333       dbgs() << "ReorderIndices: ";
2334       for (unsigned ReorderIdx : ReorderIndices)
2335         dbgs() << ReorderIdx << ", ";
2336       dbgs() << "\n";
2337       dbgs() << "UserTreeIndices: ";
2338       for (const auto &EInfo : UserTreeIndices)
2339         dbgs() << EInfo << ", ";
2340       dbgs() << "\n";
2341     }
2342 #endif
2343   };
2344 
2345 #ifndef NDEBUG
2346   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2347                      InstructionCost VecCost,
2348                      InstructionCost ScalarCost) const {
2349     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2350     dbgs() << "SLP: Costs:\n";
2351     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2352     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2353     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2354     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2355                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2356   }
2357 #endif
2358 
2359   /// Create a new VectorizableTree entry.
2360   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2361                           const InstructionsState &S,
2362                           const EdgeInfo &UserTreeIdx,
2363                           ArrayRef<int> ReuseShuffleIndices = None,
2364                           ArrayRef<unsigned> ReorderIndices = None) {
2365     TreeEntry::EntryState EntryState =
2366         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2367     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2368                         ReuseShuffleIndices, ReorderIndices);
2369   }
2370 
2371   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2372                           TreeEntry::EntryState EntryState,
2373                           Optional<ScheduleData *> Bundle,
2374                           const InstructionsState &S,
2375                           const EdgeInfo &UserTreeIdx,
2376                           ArrayRef<int> ReuseShuffleIndices = None,
2377                           ArrayRef<unsigned> ReorderIndices = None) {
2378     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2379             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2380            "Need to vectorize gather entry?");
2381     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2382     TreeEntry *Last = VectorizableTree.back().get();
2383     Last->Idx = VectorizableTree.size() - 1;
2384     Last->State = EntryState;
2385     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2386                                      ReuseShuffleIndices.end());
2387     if (ReorderIndices.empty()) {
2388       Last->Scalars.assign(VL.begin(), VL.end());
2389       Last->setOperations(S);
2390     } else {
2391       // Reorder scalars and build final mask.
2392       Last->Scalars.assign(VL.size(), nullptr);
2393       transform(ReorderIndices, Last->Scalars.begin(),
2394                 [VL](unsigned Idx) -> Value * {
2395                   if (Idx >= VL.size())
2396                     return UndefValue::get(VL.front()->getType());
2397                   return VL[Idx];
2398                 });
2399       InstructionsState S = getSameOpcode(Last->Scalars);
2400       Last->setOperations(S);
2401       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2402     }
2403     if (Last->State != TreeEntry::NeedToGather) {
2404       for (Value *V : VL) {
2405         assert(!getTreeEntry(V) && "Scalar already in tree!");
2406         ScalarToTreeEntry[V] = Last;
2407       }
2408       // Update the scheduler bundle to point to this TreeEntry.
2409       ScheduleData *BundleMember = Bundle.getValue();
2410       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2411               isVectorLikeInstWithConstOps(S.MainOp) ||
2412               doesNotNeedToSchedule(VL)) &&
2413              "Bundle and VL out of sync");
2414       if (BundleMember) {
2415         for (Value *V : VL) {
2416           if (doesNotNeedToBeScheduled(V))
2417             continue;
2418           assert(BundleMember && "Unexpected end of bundle.");
2419           BundleMember->TE = Last;
2420           BundleMember = BundleMember->NextInBundle;
2421         }
2422       }
2423       assert(!BundleMember && "Bundle and VL out of sync");
2424     } else {
2425       MustGather.insert(VL.begin(), VL.end());
2426     }
2427 
2428     if (UserTreeIdx.UserTE)
2429       Last->UserTreeIndices.push_back(UserTreeIdx);
2430 
2431     return Last;
2432   }
2433 
2434   /// -- Vectorization State --
2435   /// Holds all of the tree entries.
2436   TreeEntry::VecTreeTy VectorizableTree;
2437 
2438 #ifndef NDEBUG
2439   /// Debug printer.
2440   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2441     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2442       VectorizableTree[Id]->dump();
2443       dbgs() << "\n";
2444     }
2445   }
2446 #endif
2447 
2448   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2449 
2450   const TreeEntry *getTreeEntry(Value *V) const {
2451     return ScalarToTreeEntry.lookup(V);
2452   }
2453 
2454   /// Maps a specific scalar to its tree entry.
2455   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2456 
2457   /// Maps a value to the proposed vectorizable size.
2458   SmallDenseMap<Value *, unsigned> InstrElementSize;
2459 
2460   /// A list of scalars that we found that we need to keep as scalars.
2461   ValueSet MustGather;
2462 
2463   /// This POD struct describes one external user in the vectorized tree.
2464   struct ExternalUser {
2465     ExternalUser(Value *S, llvm::User *U, int L)
2466         : Scalar(S), User(U), Lane(L) {}
2467 
2468     // Which scalar in our function.
2469     Value *Scalar;
2470 
2471     // Which user that uses the scalar.
2472     llvm::User *User;
2473 
2474     // Which lane does the scalar belong to.
2475     int Lane;
2476   };
2477   using UserList = SmallVector<ExternalUser, 16>;
2478 
2479   /// Checks if two instructions may access the same memory.
2480   ///
2481   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2482   /// is invariant in the calling loop.
2483   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2484                  Instruction *Inst2) {
2485     // First check if the result is already in the cache.
2486     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2487     Optional<bool> &result = AliasCache[key];
2488     if (result.hasValue()) {
2489       return result.getValue();
2490     }
2491     bool aliased = true;
2492     if (Loc1.Ptr && isSimple(Inst1))
2493       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2494     // Store the result in the cache.
2495     result = aliased;
2496     return aliased;
2497   }
2498 
2499   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2500 
2501   /// Cache for alias results.
2502   /// TODO: consider moving this to the AliasAnalysis itself.
2503   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2504 
2505   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2506   // globally through SLP because we don't perform any action which
2507   // invalidates capture results.
2508   BatchAAResults BatchAA;
2509 
2510   /// Removes an instruction from its block and eventually deletes it.
2511   /// It's like Instruction::eraseFromParent() except that the actual deletion
2512   /// is delayed until BoUpSLP is destructed.
2513   /// This is required to ensure that there are no incorrect collisions in the
2514   /// AliasCache, which can happen if a new instruction is allocated at the
2515   /// same address as a previously deleted instruction.
2516   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2517     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2518     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2519   }
2520 
2521   /// Temporary store for deleted instructions. Instructions will be deleted
2522   /// eventually when the BoUpSLP is destructed.
2523   DenseMap<Instruction *, bool> DeletedInstructions;
2524 
2525   /// A list of values that need to extracted out of the tree.
2526   /// This list holds pairs of (Internal Scalar : External User). External User
2527   /// can be nullptr, it means that this Internal Scalar will be used later,
2528   /// after vectorization.
2529   UserList ExternalUses;
2530 
2531   /// Values used only by @llvm.assume calls.
2532   SmallPtrSet<const Value *, 32> EphValues;
2533 
2534   /// Holds all of the instructions that we gathered.
2535   SetVector<Instruction *> GatherShuffleSeq;
2536 
2537   /// A list of blocks that we are going to CSE.
2538   SetVector<BasicBlock *> CSEBlocks;
2539 
2540   /// Contains all scheduling relevant data for an instruction.
2541   /// A ScheduleData either represents a single instruction or a member of an
2542   /// instruction bundle (= a group of instructions which is combined into a
2543   /// vector instruction).
2544   struct ScheduleData {
2545     // The initial value for the dependency counters. It means that the
2546     // dependencies are not calculated yet.
2547     enum { InvalidDeps = -1 };
2548 
2549     ScheduleData() = default;
2550 
2551     void init(int BlockSchedulingRegionID, Value *OpVal) {
2552       FirstInBundle = this;
2553       NextInBundle = nullptr;
2554       NextLoadStore = nullptr;
2555       IsScheduled = false;
2556       SchedulingRegionID = BlockSchedulingRegionID;
2557       clearDependencies();
2558       OpValue = OpVal;
2559       TE = nullptr;
2560     }
2561 
2562     /// Verify basic self consistency properties
2563     void verify() {
2564       if (hasValidDependencies()) {
2565         assert(UnscheduledDeps <= Dependencies && "invariant");
2566       } else {
2567         assert(UnscheduledDeps == Dependencies && "invariant");
2568       }
2569 
2570       if (IsScheduled) {
2571         assert(isSchedulingEntity() &&
2572                 "unexpected scheduled state");
2573         for (const ScheduleData *BundleMember = this; BundleMember;
2574              BundleMember = BundleMember->NextInBundle) {
2575           assert(BundleMember->hasValidDependencies() &&
2576                  BundleMember->UnscheduledDeps == 0 &&
2577                  "unexpected scheduled state");
2578           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2579                  "only bundle is marked scheduled");
2580         }
2581       }
2582 
2583       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2584              "all bundle members must be in same basic block");
2585     }
2586 
2587     /// Returns true if the dependency information has been calculated.
2588     /// Note that depenendency validity can vary between instructions within
2589     /// a single bundle.
2590     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2591 
2592     /// Returns true for single instructions and for bundle representatives
2593     /// (= the head of a bundle).
2594     bool isSchedulingEntity() const { return FirstInBundle == this; }
2595 
2596     /// Returns true if it represents an instruction bundle and not only a
2597     /// single instruction.
2598     bool isPartOfBundle() const {
2599       return NextInBundle != nullptr || FirstInBundle != this || TE;
2600     }
2601 
2602     /// Returns true if it is ready for scheduling, i.e. it has no more
2603     /// unscheduled depending instructions/bundles.
2604     bool isReady() const {
2605       assert(isSchedulingEntity() &&
2606              "can't consider non-scheduling entity for ready list");
2607       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2608     }
2609 
2610     /// Modifies the number of unscheduled dependencies for this instruction,
2611     /// and returns the number of remaining dependencies for the containing
2612     /// bundle.
2613     int incrementUnscheduledDeps(int Incr) {
2614       assert(hasValidDependencies() &&
2615              "increment of unscheduled deps would be meaningless");
2616       UnscheduledDeps += Incr;
2617       return FirstInBundle->unscheduledDepsInBundle();
2618     }
2619 
2620     /// Sets the number of unscheduled dependencies to the number of
2621     /// dependencies.
2622     void resetUnscheduledDeps() {
2623       UnscheduledDeps = Dependencies;
2624     }
2625 
2626     /// Clears all dependency information.
2627     void clearDependencies() {
2628       Dependencies = InvalidDeps;
2629       resetUnscheduledDeps();
2630       MemoryDependencies.clear();
2631       ControlDependencies.clear();
2632     }
2633 
2634     int unscheduledDepsInBundle() const {
2635       assert(isSchedulingEntity() && "only meaningful on the bundle");
2636       int Sum = 0;
2637       for (const ScheduleData *BundleMember = this; BundleMember;
2638            BundleMember = BundleMember->NextInBundle) {
2639         if (BundleMember->UnscheduledDeps == InvalidDeps)
2640           return InvalidDeps;
2641         Sum += BundleMember->UnscheduledDeps;
2642       }
2643       return Sum;
2644     }
2645 
2646     void dump(raw_ostream &os) const {
2647       if (!isSchedulingEntity()) {
2648         os << "/ " << *Inst;
2649       } else if (NextInBundle) {
2650         os << '[' << *Inst;
2651         ScheduleData *SD = NextInBundle;
2652         while (SD) {
2653           os << ';' << *SD->Inst;
2654           SD = SD->NextInBundle;
2655         }
2656         os << ']';
2657       } else {
2658         os << *Inst;
2659       }
2660     }
2661 
2662     Instruction *Inst = nullptr;
2663 
2664     /// Opcode of the current instruction in the schedule data.
2665     Value *OpValue = nullptr;
2666 
2667     /// The TreeEntry that this instruction corresponds to.
2668     TreeEntry *TE = nullptr;
2669 
2670     /// Points to the head in an instruction bundle (and always to this for
2671     /// single instructions).
2672     ScheduleData *FirstInBundle = nullptr;
2673 
2674     /// Single linked list of all instructions in a bundle. Null if it is a
2675     /// single instruction.
2676     ScheduleData *NextInBundle = nullptr;
2677 
2678     /// Single linked list of all memory instructions (e.g. load, store, call)
2679     /// in the block - until the end of the scheduling region.
2680     ScheduleData *NextLoadStore = nullptr;
2681 
2682     /// The dependent memory instructions.
2683     /// This list is derived on demand in calculateDependencies().
2684     SmallVector<ScheduleData *, 4> MemoryDependencies;
2685 
2686     /// List of instructions which this instruction could be control dependent
2687     /// on.  Allowing such nodes to be scheduled below this one could introduce
2688     /// a runtime fault which didn't exist in the original program.
2689     /// ex: this is a load or udiv following a readonly call which inf loops
2690     SmallVector<ScheduleData *, 4> ControlDependencies;
2691 
2692     /// This ScheduleData is in the current scheduling region if this matches
2693     /// the current SchedulingRegionID of BlockScheduling.
2694     int SchedulingRegionID = 0;
2695 
2696     /// Used for getting a "good" final ordering of instructions.
2697     int SchedulingPriority = 0;
2698 
2699     /// The number of dependencies. Constitutes of the number of users of the
2700     /// instruction plus the number of dependent memory instructions (if any).
2701     /// This value is calculated on demand.
2702     /// If InvalidDeps, the number of dependencies is not calculated yet.
2703     int Dependencies = InvalidDeps;
2704 
2705     /// The number of dependencies minus the number of dependencies of scheduled
2706     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2707     /// for scheduling.
2708     /// Note that this is negative as long as Dependencies is not calculated.
2709     int UnscheduledDeps = InvalidDeps;
2710 
2711     /// True if this instruction is scheduled (or considered as scheduled in the
2712     /// dry-run).
2713     bool IsScheduled = false;
2714   };
2715 
2716 #ifndef NDEBUG
2717   friend inline raw_ostream &operator<<(raw_ostream &os,
2718                                         const BoUpSLP::ScheduleData &SD) {
2719     SD.dump(os);
2720     return os;
2721   }
2722 #endif
2723 
2724   friend struct GraphTraits<BoUpSLP *>;
2725   friend struct DOTGraphTraits<BoUpSLP *>;
2726 
2727   /// Contains all scheduling data for a basic block.
2728   /// It does not schedules instructions, which are not memory read/write
2729   /// instructions and their operands are either constants, or arguments, or
2730   /// phis, or instructions from others blocks, or their users are phis or from
2731   /// the other blocks. The resulting vector instructions can be placed at the
2732   /// beginning of the basic block without scheduling (if operands does not need
2733   /// to be scheduled) or at the end of the block (if users are outside of the
2734   /// block). It allows to save some compile time and memory used by the
2735   /// compiler.
2736   /// ScheduleData is assigned for each instruction in between the boundaries of
2737   /// the tree entry, even for those, which are not part of the graph. It is
2738   /// required to correctly follow the dependencies between the instructions and
2739   /// their correct scheduling. The ScheduleData is not allocated for the
2740   /// instructions, which do not require scheduling, like phis, nodes with
2741   /// extractelements/insertelements only or nodes with instructions, with
2742   /// uses/operands outside of the block.
2743   struct BlockScheduling {
2744     BlockScheduling(BasicBlock *BB)
2745         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2746 
2747     void clear() {
2748       ReadyInsts.clear();
2749       ScheduleStart = nullptr;
2750       ScheduleEnd = nullptr;
2751       FirstLoadStoreInRegion = nullptr;
2752       LastLoadStoreInRegion = nullptr;
2753 
2754       // Reduce the maximum schedule region size by the size of the
2755       // previous scheduling run.
2756       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2757       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2758         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2759       ScheduleRegionSize = 0;
2760 
2761       // Make a new scheduling region, i.e. all existing ScheduleData is not
2762       // in the new region yet.
2763       ++SchedulingRegionID;
2764     }
2765 
2766     ScheduleData *getScheduleData(Instruction *I) {
2767       if (BB != I->getParent())
2768         // Avoid lookup if can't possibly be in map.
2769         return nullptr;
2770       ScheduleData *SD = ScheduleDataMap.lookup(I);
2771       if (SD && isInSchedulingRegion(SD))
2772         return SD;
2773       return nullptr;
2774     }
2775 
2776     ScheduleData *getScheduleData(Value *V) {
2777       if (auto *I = dyn_cast<Instruction>(V))
2778         return getScheduleData(I);
2779       return nullptr;
2780     }
2781 
2782     ScheduleData *getScheduleData(Value *V, Value *Key) {
2783       if (V == Key)
2784         return getScheduleData(V);
2785       auto I = ExtraScheduleDataMap.find(V);
2786       if (I != ExtraScheduleDataMap.end()) {
2787         ScheduleData *SD = I->second.lookup(Key);
2788         if (SD && isInSchedulingRegion(SD))
2789           return SD;
2790       }
2791       return nullptr;
2792     }
2793 
2794     bool isInSchedulingRegion(ScheduleData *SD) const {
2795       return SD->SchedulingRegionID == SchedulingRegionID;
2796     }
2797 
2798     /// Marks an instruction as scheduled and puts all dependent ready
2799     /// instructions into the ready-list.
2800     template <typename ReadyListType>
2801     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2802       SD->IsScheduled = true;
2803       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2804 
2805       for (ScheduleData *BundleMember = SD; BundleMember;
2806            BundleMember = BundleMember->NextInBundle) {
2807         if (BundleMember->Inst != BundleMember->OpValue)
2808           continue;
2809 
2810         // Handle the def-use chain dependencies.
2811 
2812         // Decrement the unscheduled counter and insert to ready list if ready.
2813         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2814           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2815             if (OpDef && OpDef->hasValidDependencies() &&
2816                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2817               // There are no more unscheduled dependencies after
2818               // decrementing, so we can put the dependent instruction
2819               // into the ready list.
2820               ScheduleData *DepBundle = OpDef->FirstInBundle;
2821               assert(!DepBundle->IsScheduled &&
2822                      "already scheduled bundle gets ready");
2823               ReadyList.insert(DepBundle);
2824               LLVM_DEBUG(dbgs()
2825                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2826             }
2827           });
2828         };
2829 
2830         // If BundleMember is a vector bundle, its operands may have been
2831         // reordered during buildTree(). We therefore need to get its operands
2832         // through the TreeEntry.
2833         if (TreeEntry *TE = BundleMember->TE) {
2834           // Need to search for the lane since the tree entry can be reordered.
2835           int Lane = std::distance(TE->Scalars.begin(),
2836                                    find(TE->Scalars, BundleMember->Inst));
2837           assert(Lane >= 0 && "Lane not set");
2838 
2839           // Since vectorization tree is being built recursively this assertion
2840           // ensures that the tree entry has all operands set before reaching
2841           // this code. Couple of exceptions known at the moment are extracts
2842           // where their second (immediate) operand is not added. Since
2843           // immediates do not affect scheduler behavior this is considered
2844           // okay.
2845           auto *In = BundleMember->Inst;
2846           assert(In &&
2847                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2848                   In->getNumOperands() == TE->getNumOperands()) &&
2849                  "Missed TreeEntry operands?");
2850           (void)In; // fake use to avoid build failure when assertions disabled
2851 
2852           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2853                OpIdx != NumOperands; ++OpIdx)
2854             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2855               DecrUnsched(I);
2856         } else {
2857           // If BundleMember is a stand-alone instruction, no operand reordering
2858           // has taken place, so we directly access its operands.
2859           for (Use &U : BundleMember->Inst->operands())
2860             if (auto *I = dyn_cast<Instruction>(U.get()))
2861               DecrUnsched(I);
2862         }
2863         // Handle the memory dependencies.
2864         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2865           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2866             // There are no more unscheduled dependencies after decrementing,
2867             // so we can put the dependent instruction into the ready list.
2868             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2869             assert(!DepBundle->IsScheduled &&
2870                    "already scheduled bundle gets ready");
2871             ReadyList.insert(DepBundle);
2872             LLVM_DEBUG(dbgs()
2873                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2874           }
2875         }
2876         // Handle the control dependencies.
2877         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2878           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2879             // There are no more unscheduled dependencies after decrementing,
2880             // so we can put the dependent instruction into the ready list.
2881             ScheduleData *DepBundle = DepSD->FirstInBundle;
2882             assert(!DepBundle->IsScheduled &&
2883                    "already scheduled bundle gets ready");
2884             ReadyList.insert(DepBundle);
2885             LLVM_DEBUG(dbgs()
2886                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2887           }
2888         }
2889 
2890       }
2891     }
2892 
2893     /// Verify basic self consistency properties of the data structure.
2894     void verify() {
2895       if (!ScheduleStart)
2896         return;
2897 
2898       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2899              ScheduleStart->comesBefore(ScheduleEnd) &&
2900              "Not a valid scheduling region?");
2901 
2902       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2903         auto *SD = getScheduleData(I);
2904         if (!SD)
2905           continue;
2906         assert(isInSchedulingRegion(SD) &&
2907                "primary schedule data not in window?");
2908         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2909                "entire bundle in window!");
2910         (void)SD;
2911         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2912       }
2913 
2914       for (auto *SD : ReadyInsts) {
2915         assert(SD->isSchedulingEntity() && SD->isReady() &&
2916                "item in ready list not ready?");
2917         (void)SD;
2918       }
2919     }
2920 
2921     void doForAllOpcodes(Value *V,
2922                          function_ref<void(ScheduleData *SD)> Action) {
2923       if (ScheduleData *SD = getScheduleData(V))
2924         Action(SD);
2925       auto I = ExtraScheduleDataMap.find(V);
2926       if (I != ExtraScheduleDataMap.end())
2927         for (auto &P : I->second)
2928           if (isInSchedulingRegion(P.second))
2929             Action(P.second);
2930     }
2931 
2932     /// Put all instructions into the ReadyList which are ready for scheduling.
2933     template <typename ReadyListType>
2934     void initialFillReadyList(ReadyListType &ReadyList) {
2935       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2936         doForAllOpcodes(I, [&](ScheduleData *SD) {
2937           if (SD->isSchedulingEntity() && SD->isReady()) {
2938             ReadyList.insert(SD);
2939             LLVM_DEBUG(dbgs()
2940                        << "SLP:    initially in ready list: " << *SD << "\n");
2941           }
2942         });
2943       }
2944     }
2945 
2946     /// Build a bundle from the ScheduleData nodes corresponding to the
2947     /// scalar instruction for each lane.
2948     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2949 
2950     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2951     /// cyclic dependencies. This is only a dry-run, no instructions are
2952     /// actually moved at this stage.
2953     /// \returns the scheduling bundle. The returned Optional value is non-None
2954     /// if \p VL is allowed to be scheduled.
2955     Optional<ScheduleData *>
2956     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2957                       const InstructionsState &S);
2958 
2959     /// Un-bundles a group of instructions.
2960     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2961 
2962     /// Allocates schedule data chunk.
2963     ScheduleData *allocateScheduleDataChunks();
2964 
2965     /// Extends the scheduling region so that V is inside the region.
2966     /// \returns true if the region size is within the limit.
2967     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2968 
2969     /// Initialize the ScheduleData structures for new instructions in the
2970     /// scheduling region.
2971     void initScheduleData(Instruction *FromI, Instruction *ToI,
2972                           ScheduleData *PrevLoadStore,
2973                           ScheduleData *NextLoadStore);
2974 
2975     /// Updates the dependency information of a bundle and of all instructions/
2976     /// bundles which depend on the original bundle.
2977     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2978                                BoUpSLP *SLP);
2979 
2980     /// Sets all instruction in the scheduling region to un-scheduled.
2981     void resetSchedule();
2982 
2983     BasicBlock *BB;
2984 
2985     /// Simple memory allocation for ScheduleData.
2986     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2987 
2988     /// The size of a ScheduleData array in ScheduleDataChunks.
2989     int ChunkSize;
2990 
2991     /// The allocator position in the current chunk, which is the last entry
2992     /// of ScheduleDataChunks.
2993     int ChunkPos;
2994 
2995     /// Attaches ScheduleData to Instruction.
2996     /// Note that the mapping survives during all vectorization iterations, i.e.
2997     /// ScheduleData structures are recycled.
2998     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
2999 
3000     /// Attaches ScheduleData to Instruction with the leading key.
3001     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3002         ExtraScheduleDataMap;
3003 
3004     /// The ready-list for scheduling (only used for the dry-run).
3005     SetVector<ScheduleData *> ReadyInsts;
3006 
3007     /// The first instruction of the scheduling region.
3008     Instruction *ScheduleStart = nullptr;
3009 
3010     /// The first instruction _after_ the scheduling region.
3011     Instruction *ScheduleEnd = nullptr;
3012 
3013     /// The first memory accessing instruction in the scheduling region
3014     /// (can be null).
3015     ScheduleData *FirstLoadStoreInRegion = nullptr;
3016 
3017     /// The last memory accessing instruction in the scheduling region
3018     /// (can be null).
3019     ScheduleData *LastLoadStoreInRegion = nullptr;
3020 
3021     /// The current size of the scheduling region.
3022     int ScheduleRegionSize = 0;
3023 
3024     /// The maximum size allowed for the scheduling region.
3025     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3026 
3027     /// The ID of the scheduling region. For a new vectorization iteration this
3028     /// is incremented which "removes" all ScheduleData from the region.
3029     /// Make sure that the initial SchedulingRegionID is greater than the
3030     /// initial SchedulingRegionID in ScheduleData (which is 0).
3031     int SchedulingRegionID = 1;
3032   };
3033 
3034   /// Attaches the BlockScheduling structures to basic blocks.
3035   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3036 
3037   /// Performs the "real" scheduling. Done before vectorization is actually
3038   /// performed in a basic block.
3039   void scheduleBlock(BlockScheduling *BS);
3040 
3041   /// List of users to ignore during scheduling and that don't need extracting.
3042   ArrayRef<Value *> UserIgnoreList;
3043 
3044   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3045   /// sorted SmallVectors of unsigned.
3046   struct OrdersTypeDenseMapInfo {
3047     static OrdersType getEmptyKey() {
3048       OrdersType V;
3049       V.push_back(~1U);
3050       return V;
3051     }
3052 
3053     static OrdersType getTombstoneKey() {
3054       OrdersType V;
3055       V.push_back(~2U);
3056       return V;
3057     }
3058 
3059     static unsigned getHashValue(const OrdersType &V) {
3060       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3061     }
3062 
3063     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3064       return LHS == RHS;
3065     }
3066   };
3067 
3068   // Analysis and block reference.
3069   Function *F;
3070   ScalarEvolution *SE;
3071   TargetTransformInfo *TTI;
3072   TargetLibraryInfo *TLI;
3073   LoopInfo *LI;
3074   DominatorTree *DT;
3075   AssumptionCache *AC;
3076   DemandedBits *DB;
3077   const DataLayout *DL;
3078   OptimizationRemarkEmitter *ORE;
3079 
3080   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3081   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3082 
3083   /// Instruction builder to construct the vectorized tree.
3084   IRBuilder<> Builder;
3085 
3086   /// A map of scalar integer values to the smallest bit width with which they
3087   /// can legally be represented. The values map to (width, signed) pairs,
3088   /// where "width" indicates the minimum bit width and "signed" is True if the
3089   /// value must be signed-extended, rather than zero-extended, back to its
3090   /// original width.
3091   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3092 };
3093 
3094 } // end namespace slpvectorizer
3095 
3096 template <> struct GraphTraits<BoUpSLP *> {
3097   using TreeEntry = BoUpSLP::TreeEntry;
3098 
3099   /// NodeRef has to be a pointer per the GraphWriter.
3100   using NodeRef = TreeEntry *;
3101 
3102   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3103 
3104   /// Add the VectorizableTree to the index iterator to be able to return
3105   /// TreeEntry pointers.
3106   struct ChildIteratorType
3107       : public iterator_adaptor_base<
3108             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3109     ContainerTy &VectorizableTree;
3110 
3111     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3112                       ContainerTy &VT)
3113         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3114 
3115     NodeRef operator*() { return I->UserTE; }
3116   };
3117 
3118   static NodeRef getEntryNode(BoUpSLP &R) {
3119     return R.VectorizableTree[0].get();
3120   }
3121 
3122   static ChildIteratorType child_begin(NodeRef N) {
3123     return {N->UserTreeIndices.begin(), N->Container};
3124   }
3125 
3126   static ChildIteratorType child_end(NodeRef N) {
3127     return {N->UserTreeIndices.end(), N->Container};
3128   }
3129 
3130   /// For the node iterator we just need to turn the TreeEntry iterator into a
3131   /// TreeEntry* iterator so that it dereferences to NodeRef.
3132   class nodes_iterator {
3133     using ItTy = ContainerTy::iterator;
3134     ItTy It;
3135 
3136   public:
3137     nodes_iterator(const ItTy &It2) : It(It2) {}
3138     NodeRef operator*() { return It->get(); }
3139     nodes_iterator operator++() {
3140       ++It;
3141       return *this;
3142     }
3143     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3144   };
3145 
3146   static nodes_iterator nodes_begin(BoUpSLP *R) {
3147     return nodes_iterator(R->VectorizableTree.begin());
3148   }
3149 
3150   static nodes_iterator nodes_end(BoUpSLP *R) {
3151     return nodes_iterator(R->VectorizableTree.end());
3152   }
3153 
3154   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3155 };
3156 
3157 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3158   using TreeEntry = BoUpSLP::TreeEntry;
3159 
3160   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3161 
3162   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3163     std::string Str;
3164     raw_string_ostream OS(Str);
3165     if (isSplat(Entry->Scalars))
3166       OS << "<splat> ";
3167     for (auto V : Entry->Scalars) {
3168       OS << *V;
3169       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3170             return EU.Scalar == V;
3171           }))
3172         OS << " <extract>";
3173       OS << "\n";
3174     }
3175     return Str;
3176   }
3177 
3178   static std::string getNodeAttributes(const TreeEntry *Entry,
3179                                        const BoUpSLP *) {
3180     if (Entry->State == TreeEntry::NeedToGather)
3181       return "color=red";
3182     return "";
3183   }
3184 };
3185 
3186 } // end namespace llvm
3187 
3188 BoUpSLP::~BoUpSLP() {
3189   for (const auto &Pair : DeletedInstructions) {
3190     // Replace operands of ignored instructions with Undefs in case if they were
3191     // marked for deletion.
3192     if (Pair.getSecond()) {
3193       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3194       Pair.getFirst()->replaceAllUsesWith(Undef);
3195     }
3196     Pair.getFirst()->dropAllReferences();
3197   }
3198   for (const auto &Pair : DeletedInstructions) {
3199     assert(Pair.getFirst()->use_empty() &&
3200            "trying to erase instruction with users.");
3201     Pair.getFirst()->eraseFromParent();
3202   }
3203 #ifdef EXPENSIVE_CHECKS
3204   // If we could guarantee that this call is not extremely slow, we could
3205   // remove the ifdef limitation (see PR47712).
3206   assert(!verifyFunction(*F, &dbgs()));
3207 #endif
3208 }
3209 
3210 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3211   for (auto *V : AV) {
3212     if (auto *I = dyn_cast<Instruction>(V))
3213       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3214   };
3215 }
3216 
3217 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3218 /// contains original mask for the scalars reused in the node. Procedure
3219 /// transform this mask in accordance with the given \p Mask.
3220 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3221   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3222          "Expected non-empty mask.");
3223   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3224   Prev.swap(Reuses);
3225   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3226     if (Mask[I] != UndefMaskElem)
3227       Reuses[Mask[I]] = Prev[I];
3228 }
3229 
3230 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3231 /// the original order of the scalars. Procedure transforms the provided order
3232 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3233 /// identity order, \p Order is cleared.
3234 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3235   assert(!Mask.empty() && "Expected non-empty mask.");
3236   SmallVector<int> MaskOrder;
3237   if (Order.empty()) {
3238     MaskOrder.resize(Mask.size());
3239     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3240   } else {
3241     inversePermutation(Order, MaskOrder);
3242   }
3243   reorderReuses(MaskOrder, Mask);
3244   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3245     Order.clear();
3246     return;
3247   }
3248   Order.assign(Mask.size(), Mask.size());
3249   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3250     if (MaskOrder[I] != UndefMaskElem)
3251       Order[MaskOrder[I]] = I;
3252   fixupOrderingIndices(Order);
3253 }
3254 
3255 Optional<BoUpSLP::OrdersType>
3256 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3257   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3258   unsigned NumScalars = TE.Scalars.size();
3259   OrdersType CurrentOrder(NumScalars, NumScalars);
3260   SmallVector<int> Positions;
3261   SmallBitVector UsedPositions(NumScalars);
3262   const TreeEntry *STE = nullptr;
3263   // Try to find all gathered scalars that are gets vectorized in other
3264   // vectorize node. Here we can have only one single tree vector node to
3265   // correctly identify order of the gathered scalars.
3266   for (unsigned I = 0; I < NumScalars; ++I) {
3267     Value *V = TE.Scalars[I];
3268     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3269       continue;
3270     if (const auto *LocalSTE = getTreeEntry(V)) {
3271       if (!STE)
3272         STE = LocalSTE;
3273       else if (STE != LocalSTE)
3274         // Take the order only from the single vector node.
3275         return None;
3276       unsigned Lane =
3277           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3278       if (Lane >= NumScalars)
3279         return None;
3280       if (CurrentOrder[Lane] != NumScalars) {
3281         if (Lane != I)
3282           continue;
3283         UsedPositions.reset(CurrentOrder[Lane]);
3284       }
3285       // The partial identity (where only some elements of the gather node are
3286       // in the identity order) is good.
3287       CurrentOrder[Lane] = I;
3288       UsedPositions.set(I);
3289     }
3290   }
3291   // Need to keep the order if we have a vector entry and at least 2 scalars or
3292   // the vectorized entry has just 2 scalars.
3293   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3294     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3295       for (unsigned I = 0; I < NumScalars; ++I)
3296         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3297           return false;
3298       return true;
3299     };
3300     if (IsIdentityOrder(CurrentOrder)) {
3301       CurrentOrder.clear();
3302       return CurrentOrder;
3303     }
3304     auto *It = CurrentOrder.begin();
3305     for (unsigned I = 0; I < NumScalars;) {
3306       if (UsedPositions.test(I)) {
3307         ++I;
3308         continue;
3309       }
3310       if (*It == NumScalars) {
3311         *It = I;
3312         ++I;
3313       }
3314       ++It;
3315     }
3316     return CurrentOrder;
3317   }
3318   return None;
3319 }
3320 
3321 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3322                                                          bool TopToBottom) {
3323   // No need to reorder if need to shuffle reuses, still need to shuffle the
3324   // node.
3325   if (!TE.ReuseShuffleIndices.empty())
3326     return None;
3327   if (TE.State == TreeEntry::Vectorize &&
3328       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3329        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3330       !TE.isAltShuffle())
3331     return TE.ReorderIndices;
3332   if (TE.State == TreeEntry::NeedToGather) {
3333     // TODO: add analysis of other gather nodes with extractelement
3334     // instructions and other values/instructions, not only undefs.
3335     if (((TE.getOpcode() == Instruction::ExtractElement &&
3336           !TE.isAltShuffle()) ||
3337          (all_of(TE.Scalars,
3338                  [](Value *V) {
3339                    return isa<UndefValue, ExtractElementInst>(V);
3340                  }) &&
3341           any_of(TE.Scalars,
3342                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3343         all_of(TE.Scalars,
3344                [](Value *V) {
3345                  auto *EE = dyn_cast<ExtractElementInst>(V);
3346                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3347                }) &&
3348         allSameType(TE.Scalars)) {
3349       // Check that gather of extractelements can be represented as
3350       // just a shuffle of a single vector.
3351       OrdersType CurrentOrder;
3352       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3353       if (Reuse || !CurrentOrder.empty()) {
3354         if (!CurrentOrder.empty())
3355           fixupOrderingIndices(CurrentOrder);
3356         return CurrentOrder;
3357       }
3358     }
3359     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3360       return CurrentOrder;
3361   }
3362   return None;
3363 }
3364 
3365 void BoUpSLP::reorderTopToBottom() {
3366   // Maps VF to the graph nodes.
3367   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3368   // ExtractElement gather nodes which can be vectorized and need to handle
3369   // their ordering.
3370   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3371   // Find all reorderable nodes with the given VF.
3372   // Currently the are vectorized stores,loads,extracts + some gathering of
3373   // extracts.
3374   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3375                                  const std::unique_ptr<TreeEntry> &TE) {
3376     if (Optional<OrdersType> CurrentOrder =
3377             getReorderingData(*TE, /*TopToBottom=*/true)) {
3378       // Do not include ordering for nodes used in the alt opcode vectorization,
3379       // better to reorder them during bottom-to-top stage. If follow the order
3380       // here, it causes reordering of the whole graph though actually it is
3381       // profitable just to reorder the subgraph that starts from the alternate
3382       // opcode vectorization node. Such nodes already end-up with the shuffle
3383       // instruction and it is just enough to change this shuffle rather than
3384       // rotate the scalars for the whole graph.
3385       unsigned Cnt = 0;
3386       const TreeEntry *UserTE = TE.get();
3387       while (UserTE && Cnt < RecursionMaxDepth) {
3388         if (UserTE->UserTreeIndices.size() != 1)
3389           break;
3390         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3391               return EI.UserTE->State == TreeEntry::Vectorize &&
3392                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3393             }))
3394           return;
3395         if (UserTE->UserTreeIndices.empty())
3396           UserTE = nullptr;
3397         else
3398           UserTE = UserTE->UserTreeIndices.back().UserTE;
3399         ++Cnt;
3400       }
3401       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3402       if (TE->State != TreeEntry::Vectorize)
3403         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3404     }
3405   });
3406 
3407   // Reorder the graph nodes according to their vectorization factor.
3408   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3409        VF /= 2) {
3410     auto It = VFToOrderedEntries.find(VF);
3411     if (It == VFToOrderedEntries.end())
3412       continue;
3413     // Try to find the most profitable order. We just are looking for the most
3414     // used order and reorder scalar elements in the nodes according to this
3415     // mostly used order.
3416     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3417     // All operands are reordered and used only in this node - propagate the
3418     // most used order to the user node.
3419     MapVector<OrdersType, unsigned,
3420               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3421         OrdersUses;
3422     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3423     for (const TreeEntry *OpTE : OrderedEntries) {
3424       // No need to reorder this nodes, still need to extend and to use shuffle,
3425       // just need to merge reordering shuffle and the reuse shuffle.
3426       if (!OpTE->ReuseShuffleIndices.empty())
3427         continue;
3428       // Count number of orders uses.
3429       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3430         if (OpTE->State == TreeEntry::NeedToGather)
3431           return GathersToOrders.find(OpTE)->second;
3432         return OpTE->ReorderIndices;
3433       }();
3434       // Stores actually store the mask, not the order, need to invert.
3435       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3436           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3437         SmallVector<int> Mask;
3438         inversePermutation(Order, Mask);
3439         unsigned E = Order.size();
3440         OrdersType CurrentOrder(E, E);
3441         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3442           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3443         });
3444         fixupOrderingIndices(CurrentOrder);
3445         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3446       } else {
3447         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3448       }
3449     }
3450     // Set order of the user node.
3451     if (OrdersUses.empty())
3452       continue;
3453     // Choose the most used order.
3454     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3455     unsigned Cnt = OrdersUses.front().second;
3456     for (const auto &Pair : drop_begin(OrdersUses)) {
3457       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3458         BestOrder = Pair.first;
3459         Cnt = Pair.second;
3460       }
3461     }
3462     // Set order of the user node.
3463     if (BestOrder.empty())
3464       continue;
3465     SmallVector<int> Mask;
3466     inversePermutation(BestOrder, Mask);
3467     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3468     unsigned E = BestOrder.size();
3469     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3470       return I < E ? static_cast<int>(I) : UndefMaskElem;
3471     });
3472     // Do an actual reordering, if profitable.
3473     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3474       // Just do the reordering for the nodes with the given VF.
3475       if (TE->Scalars.size() != VF) {
3476         if (TE->ReuseShuffleIndices.size() == VF) {
3477           // Need to reorder the reuses masks of the operands with smaller VF to
3478           // be able to find the match between the graph nodes and scalar
3479           // operands of the given node during vectorization/cost estimation.
3480           assert(all_of(TE->UserTreeIndices,
3481                         [VF, &TE](const EdgeInfo &EI) {
3482                           return EI.UserTE->Scalars.size() == VF ||
3483                                  EI.UserTE->Scalars.size() ==
3484                                      TE->Scalars.size();
3485                         }) &&
3486                  "All users must be of VF size.");
3487           // Update ordering of the operands with the smaller VF than the given
3488           // one.
3489           reorderReuses(TE->ReuseShuffleIndices, Mask);
3490         }
3491         continue;
3492       }
3493       if (TE->State == TreeEntry::Vectorize &&
3494           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3495               InsertElementInst>(TE->getMainOp()) &&
3496           !TE->isAltShuffle()) {
3497         // Build correct orders for extract{element,value}, loads and
3498         // stores.
3499         reorderOrder(TE->ReorderIndices, Mask);
3500         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3501           TE->reorderOperands(Mask);
3502       } else {
3503         // Reorder the node and its operands.
3504         TE->reorderOperands(Mask);
3505         assert(TE->ReorderIndices.empty() &&
3506                "Expected empty reorder sequence.");
3507         reorderScalars(TE->Scalars, Mask);
3508       }
3509       if (!TE->ReuseShuffleIndices.empty()) {
3510         // Apply reversed order to keep the original ordering of the reused
3511         // elements to avoid extra reorder indices shuffling.
3512         OrdersType CurrentOrder;
3513         reorderOrder(CurrentOrder, MaskOrder);
3514         SmallVector<int> NewReuses;
3515         inversePermutation(CurrentOrder, NewReuses);
3516         addMask(NewReuses, TE->ReuseShuffleIndices);
3517         TE->ReuseShuffleIndices.swap(NewReuses);
3518       }
3519     }
3520   }
3521 }
3522 
3523 bool BoUpSLP::canReorderOperands(
3524     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3525     ArrayRef<TreeEntry *> ReorderableGathers,
3526     SmallVectorImpl<TreeEntry *> &GatherOps) {
3527   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3528     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3529           return OpData.first == I &&
3530                  OpData.second->State == TreeEntry::Vectorize;
3531         }))
3532       continue;
3533     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3534       // Do not reorder if operand node is used by many user nodes.
3535       if (any_of(TE->UserTreeIndices,
3536                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3537         return false;
3538       // Add the node to the list of the ordered nodes with the identity
3539       // order.
3540       Edges.emplace_back(I, TE);
3541       continue;
3542     }
3543     ArrayRef<Value *> VL = UserTE->getOperand(I);
3544     TreeEntry *Gather = nullptr;
3545     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3546           assert(TE->State != TreeEntry::Vectorize &&
3547                  "Only non-vectorized nodes are expected.");
3548           if (TE->isSame(VL)) {
3549             Gather = TE;
3550             return true;
3551           }
3552           return false;
3553         }) > 1)
3554       return false;
3555     if (Gather)
3556       GatherOps.push_back(Gather);
3557   }
3558   return true;
3559 }
3560 
3561 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3562   SetVector<TreeEntry *> OrderedEntries;
3563   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3564   // Find all reorderable leaf nodes with the given VF.
3565   // Currently the are vectorized loads,extracts without alternate operands +
3566   // some gathering of extracts.
3567   SmallVector<TreeEntry *> NonVectorized;
3568   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3569                               &NonVectorized](
3570                                  const std::unique_ptr<TreeEntry> &TE) {
3571     if (TE->State != TreeEntry::Vectorize)
3572       NonVectorized.push_back(TE.get());
3573     if (Optional<OrdersType> CurrentOrder =
3574             getReorderingData(*TE, /*TopToBottom=*/false)) {
3575       OrderedEntries.insert(TE.get());
3576       if (TE->State != TreeEntry::Vectorize)
3577         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3578     }
3579   });
3580 
3581   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3582   // I.e., if the node has operands, that are reordered, try to make at least
3583   // one operand order in the natural order and reorder others + reorder the
3584   // user node itself.
3585   SmallPtrSet<const TreeEntry *, 4> Visited;
3586   while (!OrderedEntries.empty()) {
3587     // 1. Filter out only reordered nodes.
3588     // 2. If the entry has multiple uses - skip it and jump to the next node.
3589     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3590     SmallVector<TreeEntry *> Filtered;
3591     for (TreeEntry *TE : OrderedEntries) {
3592       if (!(TE->State == TreeEntry::Vectorize ||
3593             (TE->State == TreeEntry::NeedToGather &&
3594              GathersToOrders.count(TE))) ||
3595           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3596           !all_of(drop_begin(TE->UserTreeIndices),
3597                   [TE](const EdgeInfo &EI) {
3598                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3599                   }) ||
3600           !Visited.insert(TE).second) {
3601         Filtered.push_back(TE);
3602         continue;
3603       }
3604       // Build a map between user nodes and their operands order to speedup
3605       // search. The graph currently does not provide this dependency directly.
3606       for (EdgeInfo &EI : TE->UserTreeIndices) {
3607         TreeEntry *UserTE = EI.UserTE;
3608         auto It = Users.find(UserTE);
3609         if (It == Users.end())
3610           It = Users.insert({UserTE, {}}).first;
3611         It->second.emplace_back(EI.EdgeIdx, TE);
3612       }
3613     }
3614     // Erase filtered entries.
3615     for_each(Filtered,
3616              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3617     for (auto &Data : Users) {
3618       // Check that operands are used only in the User node.
3619       SmallVector<TreeEntry *> GatherOps;
3620       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3621                               GatherOps)) {
3622         for_each(Data.second,
3623                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3624                    OrderedEntries.remove(Op.second);
3625                  });
3626         continue;
3627       }
3628       // All operands are reordered and used only in this node - propagate the
3629       // most used order to the user node.
3630       MapVector<OrdersType, unsigned,
3631                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3632           OrdersUses;
3633       // Do the analysis for each tree entry only once, otherwise the order of
3634       // the same node my be considered several times, though might be not
3635       // profitable.
3636       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3637       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3638       for (const auto &Op : Data.second) {
3639         TreeEntry *OpTE = Op.second;
3640         if (!VisitedOps.insert(OpTE).second)
3641           continue;
3642         if (!OpTE->ReuseShuffleIndices.empty() ||
3643             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3644           continue;
3645         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3646           if (OpTE->State == TreeEntry::NeedToGather)
3647             return GathersToOrders.find(OpTE)->second;
3648           return OpTE->ReorderIndices;
3649         }();
3650         unsigned NumOps = count_if(
3651             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3652               return P.second == OpTE;
3653             });
3654         // Stores actually store the mask, not the order, need to invert.
3655         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3656             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3657           SmallVector<int> Mask;
3658           inversePermutation(Order, Mask);
3659           unsigned E = Order.size();
3660           OrdersType CurrentOrder(E, E);
3661           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3662             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3663           });
3664           fixupOrderingIndices(CurrentOrder);
3665           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3666               NumOps;
3667         } else {
3668           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3669         }
3670         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3671         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3672                                             const TreeEntry *TE) {
3673           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3674               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3675               (IgnoreReorder && TE->Idx == 0))
3676             return true;
3677           if (TE->State == TreeEntry::NeedToGather) {
3678             auto It = GathersToOrders.find(TE);
3679             if (It != GathersToOrders.end())
3680               return !It->second.empty();
3681             return true;
3682           }
3683           return false;
3684         };
3685         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3686           TreeEntry *UserTE = EI.UserTE;
3687           if (!VisitedUsers.insert(UserTE).second)
3688             continue;
3689           // May reorder user node if it requires reordering, has reused
3690           // scalars, is an alternate op vectorize node or its op nodes require
3691           // reordering.
3692           if (AllowsReordering(UserTE))
3693             continue;
3694           // Check if users allow reordering.
3695           // Currently look up just 1 level of operands to avoid increase of
3696           // the compile time.
3697           // Profitable to reorder if definitely more operands allow
3698           // reordering rather than those with natural order.
3699           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3700           if (static_cast<unsigned>(count_if(
3701                   Ops, [UserTE, &AllowsReordering](
3702                            const std::pair<unsigned, TreeEntry *> &Op) {
3703                     return AllowsReordering(Op.second) &&
3704                            all_of(Op.second->UserTreeIndices,
3705                                   [UserTE](const EdgeInfo &EI) {
3706                                     return EI.UserTE == UserTE;
3707                                   });
3708                   })) <= Ops.size() / 2)
3709             ++Res.first->second;
3710         }
3711       }
3712       // If no orders - skip current nodes and jump to the next one, if any.
3713       if (OrdersUses.empty()) {
3714         for_each(Data.second,
3715                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3716                    OrderedEntries.remove(Op.second);
3717                  });
3718         continue;
3719       }
3720       // Choose the best order.
3721       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3722       unsigned Cnt = OrdersUses.front().second;
3723       for (const auto &Pair : drop_begin(OrdersUses)) {
3724         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3725           BestOrder = Pair.first;
3726           Cnt = Pair.second;
3727         }
3728       }
3729       // Set order of the user node (reordering of operands and user nodes).
3730       if (BestOrder.empty()) {
3731         for_each(Data.second,
3732                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3733                    OrderedEntries.remove(Op.second);
3734                  });
3735         continue;
3736       }
3737       // Erase operands from OrderedEntries list and adjust their orders.
3738       VisitedOps.clear();
3739       SmallVector<int> Mask;
3740       inversePermutation(BestOrder, Mask);
3741       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3742       unsigned E = BestOrder.size();
3743       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3744         return I < E ? static_cast<int>(I) : UndefMaskElem;
3745       });
3746       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3747         TreeEntry *TE = Op.second;
3748         OrderedEntries.remove(TE);
3749         if (!VisitedOps.insert(TE).second)
3750           continue;
3751         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3752           // Just reorder reuses indices.
3753           reorderReuses(TE->ReuseShuffleIndices, Mask);
3754           continue;
3755         }
3756         // Gathers are processed separately.
3757         if (TE->State != TreeEntry::Vectorize)
3758           continue;
3759         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3760                 TE->ReorderIndices.empty()) &&
3761                "Non-matching sizes of user/operand entries.");
3762         reorderOrder(TE->ReorderIndices, Mask);
3763       }
3764       // For gathers just need to reorder its scalars.
3765       for (TreeEntry *Gather : GatherOps) {
3766         assert(Gather->ReorderIndices.empty() &&
3767                "Unexpected reordering of gathers.");
3768         if (!Gather->ReuseShuffleIndices.empty()) {
3769           // Just reorder reuses indices.
3770           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3771           continue;
3772         }
3773         reorderScalars(Gather->Scalars, Mask);
3774         OrderedEntries.remove(Gather);
3775       }
3776       // Reorder operands of the user node and set the ordering for the user
3777       // node itself.
3778       if (Data.first->State != TreeEntry::Vectorize ||
3779           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3780               Data.first->getMainOp()) ||
3781           Data.first->isAltShuffle())
3782         Data.first->reorderOperands(Mask);
3783       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3784           Data.first->isAltShuffle()) {
3785         reorderScalars(Data.first->Scalars, Mask);
3786         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3787         if (Data.first->ReuseShuffleIndices.empty() &&
3788             !Data.first->ReorderIndices.empty() &&
3789             !Data.first->isAltShuffle()) {
3790           // Insert user node to the list to try to sink reordering deeper in
3791           // the graph.
3792           OrderedEntries.insert(Data.first);
3793         }
3794       } else {
3795         reorderOrder(Data.first->ReorderIndices, Mask);
3796       }
3797     }
3798   }
3799   // If the reordering is unnecessary, just remove the reorder.
3800   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3801       VectorizableTree.front()->ReuseShuffleIndices.empty())
3802     VectorizableTree.front()->ReorderIndices.clear();
3803 }
3804 
3805 void BoUpSLP::buildExternalUses(
3806     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3807   // Collect the values that we need to extract from the tree.
3808   for (auto &TEPtr : VectorizableTree) {
3809     TreeEntry *Entry = TEPtr.get();
3810 
3811     // No need to handle users of gathered values.
3812     if (Entry->State == TreeEntry::NeedToGather)
3813       continue;
3814 
3815     // For each lane:
3816     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3817       Value *Scalar = Entry->Scalars[Lane];
3818       int FoundLane = Entry->findLaneForValue(Scalar);
3819 
3820       // Check if the scalar is externally used as an extra arg.
3821       auto ExtI = ExternallyUsedValues.find(Scalar);
3822       if (ExtI != ExternallyUsedValues.end()) {
3823         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3824                           << Lane << " from " << *Scalar << ".\n");
3825         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3826       }
3827       for (User *U : Scalar->users()) {
3828         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3829 
3830         Instruction *UserInst = dyn_cast<Instruction>(U);
3831         if (!UserInst)
3832           continue;
3833 
3834         if (isDeleted(UserInst))
3835           continue;
3836 
3837         // Skip in-tree scalars that become vectors
3838         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3839           Value *UseScalar = UseEntry->Scalars[0];
3840           // Some in-tree scalars will remain as scalar in vectorized
3841           // instructions. If that is the case, the one in Lane 0 will
3842           // be used.
3843           if (UseScalar != U ||
3844               UseEntry->State == TreeEntry::ScatterVectorize ||
3845               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3846             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3847                               << ".\n");
3848             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3849             continue;
3850           }
3851         }
3852 
3853         // Ignore users in the user ignore list.
3854         if (is_contained(UserIgnoreList, UserInst))
3855           continue;
3856 
3857         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3858                           << Lane << " from " << *Scalar << ".\n");
3859         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3860       }
3861     }
3862   }
3863 }
3864 
3865 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3866                         ArrayRef<Value *> UserIgnoreLst) {
3867   deleteTree();
3868   UserIgnoreList = UserIgnoreLst;
3869   if (!allSameType(Roots))
3870     return;
3871   buildTree_rec(Roots, 0, EdgeInfo());
3872 }
3873 
3874 namespace {
3875 /// Tracks the state we can represent the loads in the given sequence.
3876 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3877 } // anonymous namespace
3878 
3879 /// Checks if the given array of loads can be represented as a vectorized,
3880 /// scatter or just simple gather.
3881 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3882                                     const TargetTransformInfo &TTI,
3883                                     const DataLayout &DL, ScalarEvolution &SE,
3884                                     SmallVectorImpl<unsigned> &Order,
3885                                     SmallVectorImpl<Value *> &PointerOps) {
3886   // Check that a vectorized load would load the same memory as a scalar
3887   // load. For example, we don't want to vectorize loads that are smaller
3888   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3889   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3890   // from such a struct, we read/write packed bits disagreeing with the
3891   // unvectorized version.
3892   Type *ScalarTy = VL0->getType();
3893 
3894   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3895     return LoadsState::Gather;
3896 
3897   // Make sure all loads in the bundle are simple - we can't vectorize
3898   // atomic or volatile loads.
3899   PointerOps.clear();
3900   PointerOps.resize(VL.size());
3901   auto *POIter = PointerOps.begin();
3902   for (Value *V : VL) {
3903     auto *L = cast<LoadInst>(V);
3904     if (!L->isSimple())
3905       return LoadsState::Gather;
3906     *POIter = L->getPointerOperand();
3907     ++POIter;
3908   }
3909 
3910   Order.clear();
3911   // Check the order of pointer operands.
3912   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3913     Value *Ptr0;
3914     Value *PtrN;
3915     if (Order.empty()) {
3916       Ptr0 = PointerOps.front();
3917       PtrN = PointerOps.back();
3918     } else {
3919       Ptr0 = PointerOps[Order.front()];
3920       PtrN = PointerOps[Order.back()];
3921     }
3922     Optional<int> Diff =
3923         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3924     // Check that the sorted loads are consecutive.
3925     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3926       return LoadsState::Vectorize;
3927     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3928     for (Value *V : VL)
3929       CommonAlignment =
3930           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3931     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3932                                 CommonAlignment))
3933       return LoadsState::ScatterVectorize;
3934   }
3935 
3936   return LoadsState::Gather;
3937 }
3938 
3939 /// \return true if the specified list of values has only one instruction that
3940 /// requires scheduling, false otherwise.
3941 #ifndef NDEBUG
3942 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3943   Value *NeedsScheduling = nullptr;
3944   for (Value *V : VL) {
3945     if (doesNotNeedToBeScheduled(V))
3946       continue;
3947     if (!NeedsScheduling) {
3948       NeedsScheduling = V;
3949       continue;
3950     }
3951     return false;
3952   }
3953   return NeedsScheduling;
3954 }
3955 #endif
3956 
3957 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3958                             const EdgeInfo &UserTreeIdx) {
3959   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3960 
3961   SmallVector<int> ReuseShuffleIndicies;
3962   SmallVector<Value *> UniqueValues;
3963   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3964                                 &UserTreeIdx,
3965                                 this](const InstructionsState &S) {
3966     // Check that every instruction appears once in this bundle.
3967     DenseMap<Value *, unsigned> UniquePositions;
3968     for (Value *V : VL) {
3969       if (isConstant(V)) {
3970         ReuseShuffleIndicies.emplace_back(
3971             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3972         UniqueValues.emplace_back(V);
3973         continue;
3974       }
3975       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3976       ReuseShuffleIndicies.emplace_back(Res.first->second);
3977       if (Res.second)
3978         UniqueValues.emplace_back(V);
3979     }
3980     size_t NumUniqueScalarValues = UniqueValues.size();
3981     if (NumUniqueScalarValues == VL.size()) {
3982       ReuseShuffleIndicies.clear();
3983     } else {
3984       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3985       if (NumUniqueScalarValues <= 1 ||
3986           (UniquePositions.size() == 1 && all_of(UniqueValues,
3987                                                  [](Value *V) {
3988                                                    return isa<UndefValue>(V) ||
3989                                                           !isConstant(V);
3990                                                  })) ||
3991           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3992         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3993         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3994         return false;
3995       }
3996       VL = UniqueValues;
3997     }
3998     return true;
3999   };
4000 
4001   InstructionsState S = getSameOpcode(VL);
4002   if (Depth == RecursionMaxDepth) {
4003     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4004     if (TryToFindDuplicates(S))
4005       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4006                    ReuseShuffleIndicies);
4007     return;
4008   }
4009 
4010   // Don't handle scalable vectors
4011   if (S.getOpcode() == Instruction::ExtractElement &&
4012       isa<ScalableVectorType>(
4013           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4014     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4015     if (TryToFindDuplicates(S))
4016       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4017                    ReuseShuffleIndicies);
4018     return;
4019   }
4020 
4021   // Don't handle vectors.
4022   if (S.OpValue->getType()->isVectorTy() &&
4023       !isa<InsertElementInst>(S.OpValue)) {
4024     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4025     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4026     return;
4027   }
4028 
4029   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4030     if (SI->getValueOperand()->getType()->isVectorTy()) {
4031       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4032       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4033       return;
4034     }
4035 
4036   // If all of the operands are identical or constant we have a simple solution.
4037   // If we deal with insert/extract instructions, they all must have constant
4038   // indices, otherwise we should gather them, not try to vectorize.
4039   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4040       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4041        !all_of(VL, isVectorLikeInstWithConstOps))) {
4042     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4043     if (TryToFindDuplicates(S))
4044       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4045                    ReuseShuffleIndicies);
4046     return;
4047   }
4048 
4049   // We now know that this is a vector of instructions of the same type from
4050   // the same block.
4051 
4052   // Don't vectorize ephemeral values.
4053   for (Value *V : VL) {
4054     if (EphValues.count(V)) {
4055       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4056                         << ") is ephemeral.\n");
4057       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4058       return;
4059     }
4060   }
4061 
4062   // Check if this is a duplicate of another entry.
4063   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4064     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4065     if (!E->isSame(VL)) {
4066       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4067       if (TryToFindDuplicates(S))
4068         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4069                      ReuseShuffleIndicies);
4070       return;
4071     }
4072     // Record the reuse of the tree node.  FIXME, currently this is only used to
4073     // properly draw the graph rather than for the actual vectorization.
4074     E->UserTreeIndices.push_back(UserTreeIdx);
4075     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4076                       << ".\n");
4077     return;
4078   }
4079 
4080   // Check that none of the instructions in the bundle are already in the tree.
4081   for (Value *V : VL) {
4082     auto *I = dyn_cast<Instruction>(V);
4083     if (!I)
4084       continue;
4085     if (getTreeEntry(I)) {
4086       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4087                         << ") is already in tree.\n");
4088       if (TryToFindDuplicates(S))
4089         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4090                      ReuseShuffleIndicies);
4091       return;
4092     }
4093   }
4094 
4095   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4096   for (Value *V : VL) {
4097     if (is_contained(UserIgnoreList, V)) {
4098       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4099       if (TryToFindDuplicates(S))
4100         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4101                      ReuseShuffleIndicies);
4102       return;
4103     }
4104   }
4105 
4106   // Check that all of the users of the scalars that we want to vectorize are
4107   // schedulable.
4108   auto *VL0 = cast<Instruction>(S.OpValue);
4109   BasicBlock *BB = VL0->getParent();
4110 
4111   if (!DT->isReachableFromEntry(BB)) {
4112     // Don't go into unreachable blocks. They may contain instructions with
4113     // dependency cycles which confuse the final scheduling.
4114     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4115     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4116     return;
4117   }
4118 
4119   // Check that every instruction appears once in this bundle.
4120   if (!TryToFindDuplicates(S))
4121     return;
4122 
4123   auto &BSRef = BlocksSchedules[BB];
4124   if (!BSRef)
4125     BSRef = std::make_unique<BlockScheduling>(BB);
4126 
4127   BlockScheduling &BS = *BSRef;
4128 
4129   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4130 #ifdef EXPENSIVE_CHECKS
4131   // Make sure we didn't break any internal invariants
4132   BS.verify();
4133 #endif
4134   if (!Bundle) {
4135     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4136     assert((!BS.getScheduleData(VL0) ||
4137             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4138            "tryScheduleBundle should cancelScheduling on failure");
4139     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4140                  ReuseShuffleIndicies);
4141     return;
4142   }
4143   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4144 
4145   unsigned ShuffleOrOp = S.isAltShuffle() ?
4146                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4147   switch (ShuffleOrOp) {
4148     case Instruction::PHI: {
4149       auto *PH = cast<PHINode>(VL0);
4150 
4151       // Check for terminator values (e.g. invoke).
4152       for (Value *V : VL)
4153         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4154           Instruction *Term = dyn_cast<Instruction>(Incoming);
4155           if (Term && Term->isTerminator()) {
4156             LLVM_DEBUG(dbgs()
4157                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4158             BS.cancelScheduling(VL, VL0);
4159             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4160                          ReuseShuffleIndicies);
4161             return;
4162           }
4163         }
4164 
4165       TreeEntry *TE =
4166           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4167       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4168 
4169       // Keeps the reordered operands to avoid code duplication.
4170       SmallVector<ValueList, 2> OperandsVec;
4171       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4172         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4173           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4174           TE->setOperand(I, Operands);
4175           OperandsVec.push_back(Operands);
4176           continue;
4177         }
4178         ValueList Operands;
4179         // Prepare the operand vector.
4180         for (Value *V : VL)
4181           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4182               PH->getIncomingBlock(I)));
4183         TE->setOperand(I, Operands);
4184         OperandsVec.push_back(Operands);
4185       }
4186       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4187         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4188       return;
4189     }
4190     case Instruction::ExtractValue:
4191     case Instruction::ExtractElement: {
4192       OrdersType CurrentOrder;
4193       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4194       if (Reuse) {
4195         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4196         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4197                      ReuseShuffleIndicies);
4198         // This is a special case, as it does not gather, but at the same time
4199         // we are not extending buildTree_rec() towards the operands.
4200         ValueList Op0;
4201         Op0.assign(VL.size(), VL0->getOperand(0));
4202         VectorizableTree.back()->setOperand(0, Op0);
4203         return;
4204       }
4205       if (!CurrentOrder.empty()) {
4206         LLVM_DEBUG({
4207           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4208                     "with order";
4209           for (unsigned Idx : CurrentOrder)
4210             dbgs() << " " << Idx;
4211           dbgs() << "\n";
4212         });
4213         fixupOrderingIndices(CurrentOrder);
4214         // Insert new order with initial value 0, if it does not exist,
4215         // otherwise return the iterator to the existing one.
4216         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4217                      ReuseShuffleIndicies, CurrentOrder);
4218         // This is a special case, as it does not gather, but at the same time
4219         // we are not extending buildTree_rec() towards the operands.
4220         ValueList Op0;
4221         Op0.assign(VL.size(), VL0->getOperand(0));
4222         VectorizableTree.back()->setOperand(0, Op0);
4223         return;
4224       }
4225       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4226       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4227                    ReuseShuffleIndicies);
4228       BS.cancelScheduling(VL, VL0);
4229       return;
4230     }
4231     case Instruction::InsertElement: {
4232       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4233 
4234       // Check that we have a buildvector and not a shuffle of 2 or more
4235       // different vectors.
4236       ValueSet SourceVectors;
4237       for (Value *V : VL) {
4238         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4239         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4240       }
4241 
4242       if (count_if(VL, [&SourceVectors](Value *V) {
4243             return !SourceVectors.contains(V);
4244           }) >= 2) {
4245         // Found 2nd source vector - cancel.
4246         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4247                              "different source vectors.\n");
4248         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4249         BS.cancelScheduling(VL, VL0);
4250         return;
4251       }
4252 
4253       auto OrdCompare = [](const std::pair<int, int> &P1,
4254                            const std::pair<int, int> &P2) {
4255         return P1.first > P2.first;
4256       };
4257       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4258                     decltype(OrdCompare)>
4259           Indices(OrdCompare);
4260       for (int I = 0, E = VL.size(); I < E; ++I) {
4261         unsigned Idx = *getInsertIndex(VL[I]);
4262         Indices.emplace(Idx, I);
4263       }
4264       OrdersType CurrentOrder(VL.size(), VL.size());
4265       bool IsIdentity = true;
4266       for (int I = 0, E = VL.size(); I < E; ++I) {
4267         CurrentOrder[Indices.top().second] = I;
4268         IsIdentity &= Indices.top().second == I;
4269         Indices.pop();
4270       }
4271       if (IsIdentity)
4272         CurrentOrder.clear();
4273       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4274                                    None, CurrentOrder);
4275       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4276 
4277       constexpr int NumOps = 2;
4278       ValueList VectorOperands[NumOps];
4279       for (int I = 0; I < NumOps; ++I) {
4280         for (Value *V : VL)
4281           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4282 
4283         TE->setOperand(I, VectorOperands[I]);
4284       }
4285       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4286       return;
4287     }
4288     case Instruction::Load: {
4289       // Check that a vectorized load would load the same memory as a scalar
4290       // load. For example, we don't want to vectorize loads that are smaller
4291       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4292       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4293       // from such a struct, we read/write packed bits disagreeing with the
4294       // unvectorized version.
4295       SmallVector<Value *> PointerOps;
4296       OrdersType CurrentOrder;
4297       TreeEntry *TE = nullptr;
4298       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4299                                 PointerOps)) {
4300       case LoadsState::Vectorize:
4301         if (CurrentOrder.empty()) {
4302           // Original loads are consecutive and does not require reordering.
4303           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4304                             ReuseShuffleIndicies);
4305           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4306         } else {
4307           fixupOrderingIndices(CurrentOrder);
4308           // Need to reorder.
4309           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4310                             ReuseShuffleIndicies, CurrentOrder);
4311           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4312         }
4313         TE->setOperandsInOrder();
4314         break;
4315       case LoadsState::ScatterVectorize:
4316         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4317         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4318                           UserTreeIdx, ReuseShuffleIndicies);
4319         TE->setOperandsInOrder();
4320         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4321         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4322         break;
4323       case LoadsState::Gather:
4324         BS.cancelScheduling(VL, VL0);
4325         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4326                      ReuseShuffleIndicies);
4327 #ifndef NDEBUG
4328         Type *ScalarTy = VL0->getType();
4329         if (DL->getTypeSizeInBits(ScalarTy) !=
4330             DL->getTypeAllocSizeInBits(ScalarTy))
4331           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4332         else if (any_of(VL, [](Value *V) {
4333                    return !cast<LoadInst>(V)->isSimple();
4334                  }))
4335           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4336         else
4337           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4338 #endif // NDEBUG
4339         break;
4340       }
4341       return;
4342     }
4343     case Instruction::ZExt:
4344     case Instruction::SExt:
4345     case Instruction::FPToUI:
4346     case Instruction::FPToSI:
4347     case Instruction::FPExt:
4348     case Instruction::PtrToInt:
4349     case Instruction::IntToPtr:
4350     case Instruction::SIToFP:
4351     case Instruction::UIToFP:
4352     case Instruction::Trunc:
4353     case Instruction::FPTrunc:
4354     case Instruction::BitCast: {
4355       Type *SrcTy = VL0->getOperand(0)->getType();
4356       for (Value *V : VL) {
4357         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4358         if (Ty != SrcTy || !isValidElementType(Ty)) {
4359           BS.cancelScheduling(VL, VL0);
4360           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4361                        ReuseShuffleIndicies);
4362           LLVM_DEBUG(dbgs()
4363                      << "SLP: Gathering casts with different src types.\n");
4364           return;
4365         }
4366       }
4367       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4368                                    ReuseShuffleIndicies);
4369       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4370 
4371       TE->setOperandsInOrder();
4372       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4373         ValueList Operands;
4374         // Prepare the operand vector.
4375         for (Value *V : VL)
4376           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4377 
4378         buildTree_rec(Operands, Depth + 1, {TE, i});
4379       }
4380       return;
4381     }
4382     case Instruction::ICmp:
4383     case Instruction::FCmp: {
4384       // Check that all of the compares have the same predicate.
4385       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4386       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4387       Type *ComparedTy = VL0->getOperand(0)->getType();
4388       for (Value *V : VL) {
4389         CmpInst *Cmp = cast<CmpInst>(V);
4390         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4391             Cmp->getOperand(0)->getType() != ComparedTy) {
4392           BS.cancelScheduling(VL, VL0);
4393           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4394                        ReuseShuffleIndicies);
4395           LLVM_DEBUG(dbgs()
4396                      << "SLP: Gathering cmp with different predicate.\n");
4397           return;
4398         }
4399       }
4400 
4401       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4402                                    ReuseShuffleIndicies);
4403       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4404 
4405       ValueList Left, Right;
4406       if (cast<CmpInst>(VL0)->isCommutative()) {
4407         // Commutative predicate - collect + sort operands of the instructions
4408         // so that each side is more likely to have the same opcode.
4409         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4410         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4411       } else {
4412         // Collect operands - commute if it uses the swapped predicate.
4413         for (Value *V : VL) {
4414           auto *Cmp = cast<CmpInst>(V);
4415           Value *LHS = Cmp->getOperand(0);
4416           Value *RHS = Cmp->getOperand(1);
4417           if (Cmp->getPredicate() != P0)
4418             std::swap(LHS, RHS);
4419           Left.push_back(LHS);
4420           Right.push_back(RHS);
4421         }
4422       }
4423       TE->setOperand(0, Left);
4424       TE->setOperand(1, Right);
4425       buildTree_rec(Left, Depth + 1, {TE, 0});
4426       buildTree_rec(Right, Depth + 1, {TE, 1});
4427       return;
4428     }
4429     case Instruction::Select:
4430     case Instruction::FNeg:
4431     case Instruction::Add:
4432     case Instruction::FAdd:
4433     case Instruction::Sub:
4434     case Instruction::FSub:
4435     case Instruction::Mul:
4436     case Instruction::FMul:
4437     case Instruction::UDiv:
4438     case Instruction::SDiv:
4439     case Instruction::FDiv:
4440     case Instruction::URem:
4441     case Instruction::SRem:
4442     case Instruction::FRem:
4443     case Instruction::Shl:
4444     case Instruction::LShr:
4445     case Instruction::AShr:
4446     case Instruction::And:
4447     case Instruction::Or:
4448     case Instruction::Xor: {
4449       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4450                                    ReuseShuffleIndicies);
4451       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4452 
4453       // Sort operands of the instructions so that each side is more likely to
4454       // have the same opcode.
4455       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4456         ValueList Left, Right;
4457         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4458         TE->setOperand(0, Left);
4459         TE->setOperand(1, Right);
4460         buildTree_rec(Left, Depth + 1, {TE, 0});
4461         buildTree_rec(Right, Depth + 1, {TE, 1});
4462         return;
4463       }
4464 
4465       TE->setOperandsInOrder();
4466       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4467         ValueList Operands;
4468         // Prepare the operand vector.
4469         for (Value *V : VL)
4470           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4471 
4472         buildTree_rec(Operands, Depth + 1, {TE, i});
4473       }
4474       return;
4475     }
4476     case Instruction::GetElementPtr: {
4477       // We don't combine GEPs with complicated (nested) indexing.
4478       for (Value *V : VL) {
4479         if (cast<Instruction>(V)->getNumOperands() != 2) {
4480           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4481           BS.cancelScheduling(VL, VL0);
4482           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4483                        ReuseShuffleIndicies);
4484           return;
4485         }
4486       }
4487 
4488       // We can't combine several GEPs into one vector if they operate on
4489       // different types.
4490       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4491       for (Value *V : VL) {
4492         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4493         if (Ty0 != CurTy) {
4494           LLVM_DEBUG(dbgs()
4495                      << "SLP: not-vectorizable GEP (different types).\n");
4496           BS.cancelScheduling(VL, VL0);
4497           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4498                        ReuseShuffleIndicies);
4499           return;
4500         }
4501       }
4502 
4503       // We don't combine GEPs with non-constant indexes.
4504       Type *Ty1 = VL0->getOperand(1)->getType();
4505       for (Value *V : VL) {
4506         auto Op = cast<Instruction>(V)->getOperand(1);
4507         if (!isa<ConstantInt>(Op) ||
4508             (Op->getType() != Ty1 &&
4509              Op->getType()->getScalarSizeInBits() >
4510                  DL->getIndexSizeInBits(
4511                      V->getType()->getPointerAddressSpace()))) {
4512           LLVM_DEBUG(dbgs()
4513                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4514           BS.cancelScheduling(VL, VL0);
4515           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4516                        ReuseShuffleIndicies);
4517           return;
4518         }
4519       }
4520 
4521       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4522                                    ReuseShuffleIndicies);
4523       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4524       SmallVector<ValueList, 2> Operands(2);
4525       // Prepare the operand vector for pointer operands.
4526       for (Value *V : VL)
4527         Operands.front().push_back(
4528             cast<GetElementPtrInst>(V)->getPointerOperand());
4529       TE->setOperand(0, Operands.front());
4530       // Need to cast all indices to the same type before vectorization to
4531       // avoid crash.
4532       // Required to be able to find correct matches between different gather
4533       // nodes and reuse the vectorized values rather than trying to gather them
4534       // again.
4535       int IndexIdx = 1;
4536       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4537       Type *Ty = all_of(VL,
4538                         [VL0Ty, IndexIdx](Value *V) {
4539                           return VL0Ty == cast<GetElementPtrInst>(V)
4540                                               ->getOperand(IndexIdx)
4541                                               ->getType();
4542                         })
4543                      ? VL0Ty
4544                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4545                                             ->getPointerOperandType()
4546                                             ->getScalarType());
4547       // Prepare the operand vector.
4548       for (Value *V : VL) {
4549         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4550         auto *CI = cast<ConstantInt>(Op);
4551         Operands.back().push_back(ConstantExpr::getIntegerCast(
4552             CI, Ty, CI->getValue().isSignBitSet()));
4553       }
4554       TE->setOperand(IndexIdx, Operands.back());
4555 
4556       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4557         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4558       return;
4559     }
4560     case Instruction::Store: {
4561       // Check if the stores are consecutive or if we need to swizzle them.
4562       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4563       // Avoid types that are padded when being allocated as scalars, while
4564       // being packed together in a vector (such as i1).
4565       if (DL->getTypeSizeInBits(ScalarTy) !=
4566           DL->getTypeAllocSizeInBits(ScalarTy)) {
4567         BS.cancelScheduling(VL, VL0);
4568         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4569                      ReuseShuffleIndicies);
4570         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4571         return;
4572       }
4573       // Make sure all stores in the bundle are simple - we can't vectorize
4574       // atomic or volatile stores.
4575       SmallVector<Value *, 4> PointerOps(VL.size());
4576       ValueList Operands(VL.size());
4577       auto POIter = PointerOps.begin();
4578       auto OIter = Operands.begin();
4579       for (Value *V : VL) {
4580         auto *SI = cast<StoreInst>(V);
4581         if (!SI->isSimple()) {
4582           BS.cancelScheduling(VL, VL0);
4583           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4584                        ReuseShuffleIndicies);
4585           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4586           return;
4587         }
4588         *POIter = SI->getPointerOperand();
4589         *OIter = SI->getValueOperand();
4590         ++POIter;
4591         ++OIter;
4592       }
4593 
4594       OrdersType CurrentOrder;
4595       // Check the order of pointer operands.
4596       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4597         Value *Ptr0;
4598         Value *PtrN;
4599         if (CurrentOrder.empty()) {
4600           Ptr0 = PointerOps.front();
4601           PtrN = PointerOps.back();
4602         } else {
4603           Ptr0 = PointerOps[CurrentOrder.front()];
4604           PtrN = PointerOps[CurrentOrder.back()];
4605         }
4606         Optional<int> Dist =
4607             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4608         // Check that the sorted pointer operands are consecutive.
4609         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4610           if (CurrentOrder.empty()) {
4611             // Original stores are consecutive and does not require reordering.
4612             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4613                                          UserTreeIdx, ReuseShuffleIndicies);
4614             TE->setOperandsInOrder();
4615             buildTree_rec(Operands, Depth + 1, {TE, 0});
4616             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4617           } else {
4618             fixupOrderingIndices(CurrentOrder);
4619             TreeEntry *TE =
4620                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4621                              ReuseShuffleIndicies, CurrentOrder);
4622             TE->setOperandsInOrder();
4623             buildTree_rec(Operands, Depth + 1, {TE, 0});
4624             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4625           }
4626           return;
4627         }
4628       }
4629 
4630       BS.cancelScheduling(VL, VL0);
4631       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4632                    ReuseShuffleIndicies);
4633       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4634       return;
4635     }
4636     case Instruction::Call: {
4637       // Check if the calls are all to the same vectorizable intrinsic or
4638       // library function.
4639       CallInst *CI = cast<CallInst>(VL0);
4640       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4641 
4642       VFShape Shape = VFShape::get(
4643           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4644           false /*HasGlobalPred*/);
4645       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4646 
4647       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4648         BS.cancelScheduling(VL, VL0);
4649         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4650                      ReuseShuffleIndicies);
4651         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4652         return;
4653       }
4654       Function *F = CI->getCalledFunction();
4655       unsigned NumArgs = CI->arg_size();
4656       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4657       for (unsigned j = 0; j != NumArgs; ++j)
4658         if (hasVectorInstrinsicScalarOpd(ID, j))
4659           ScalarArgs[j] = CI->getArgOperand(j);
4660       for (Value *V : VL) {
4661         CallInst *CI2 = dyn_cast<CallInst>(V);
4662         if (!CI2 || CI2->getCalledFunction() != F ||
4663             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4664             (VecFunc &&
4665              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4666             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4667           BS.cancelScheduling(VL, VL0);
4668           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4669                        ReuseShuffleIndicies);
4670           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4671                             << "\n");
4672           return;
4673         }
4674         // Some intrinsics have scalar arguments and should be same in order for
4675         // them to be vectorized.
4676         for (unsigned j = 0; j != NumArgs; ++j) {
4677           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4678             Value *A1J = CI2->getArgOperand(j);
4679             if (ScalarArgs[j] != A1J) {
4680               BS.cancelScheduling(VL, VL0);
4681               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4682                            ReuseShuffleIndicies);
4683               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4684                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4685                                 << "\n");
4686               return;
4687             }
4688           }
4689         }
4690         // Verify that the bundle operands are identical between the two calls.
4691         if (CI->hasOperandBundles() &&
4692             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4693                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4694                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4695           BS.cancelScheduling(VL, VL0);
4696           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4697                        ReuseShuffleIndicies);
4698           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4699                             << *CI << "!=" << *V << '\n');
4700           return;
4701         }
4702       }
4703 
4704       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4705                                    ReuseShuffleIndicies);
4706       TE->setOperandsInOrder();
4707       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4708         // For scalar operands no need to to create an entry since no need to
4709         // vectorize it.
4710         if (hasVectorInstrinsicScalarOpd(ID, i))
4711           continue;
4712         ValueList Operands;
4713         // Prepare the operand vector.
4714         for (Value *V : VL) {
4715           auto *CI2 = cast<CallInst>(V);
4716           Operands.push_back(CI2->getArgOperand(i));
4717         }
4718         buildTree_rec(Operands, Depth + 1, {TE, i});
4719       }
4720       return;
4721     }
4722     case Instruction::ShuffleVector: {
4723       // If this is not an alternate sequence of opcode like add-sub
4724       // then do not vectorize this instruction.
4725       if (!S.isAltShuffle()) {
4726         BS.cancelScheduling(VL, VL0);
4727         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4728                      ReuseShuffleIndicies);
4729         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4730         return;
4731       }
4732       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4733                                    ReuseShuffleIndicies);
4734       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4735 
4736       // Reorder operands if reordering would enable vectorization.
4737       auto *CI = dyn_cast<CmpInst>(VL0);
4738       if (isa<BinaryOperator>(VL0) || CI) {
4739         ValueList Left, Right;
4740         if (!CI || all_of(VL, [](Value *V) {
4741               return cast<CmpInst>(V)->isCommutative();
4742             })) {
4743           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4744         } else {
4745           CmpInst::Predicate P0 = CI->getPredicate();
4746           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4747           assert(P0 != AltP0 &&
4748                  "Expected different main/alternate predicates.");
4749           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4750           Value *BaseOp0 = VL0->getOperand(0);
4751           Value *BaseOp1 = VL0->getOperand(1);
4752           // Collect operands - commute if it uses the swapped predicate or
4753           // alternate operation.
4754           for (Value *V : VL) {
4755             auto *Cmp = cast<CmpInst>(V);
4756             Value *LHS = Cmp->getOperand(0);
4757             Value *RHS = Cmp->getOperand(1);
4758             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4759             if (P0 == AltP0Swapped) {
4760               if (CI != Cmp && S.AltOp != Cmp &&
4761                   ((P0 == CurrentPred &&
4762                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4763                    (AltP0 == CurrentPred &&
4764                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4765                 std::swap(LHS, RHS);
4766             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4767               std::swap(LHS, RHS);
4768             }
4769             Left.push_back(LHS);
4770             Right.push_back(RHS);
4771           }
4772         }
4773         TE->setOperand(0, Left);
4774         TE->setOperand(1, Right);
4775         buildTree_rec(Left, Depth + 1, {TE, 0});
4776         buildTree_rec(Right, Depth + 1, {TE, 1});
4777         return;
4778       }
4779 
4780       TE->setOperandsInOrder();
4781       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4782         ValueList Operands;
4783         // Prepare the operand vector.
4784         for (Value *V : VL)
4785           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4786 
4787         buildTree_rec(Operands, Depth + 1, {TE, i});
4788       }
4789       return;
4790     }
4791     default:
4792       BS.cancelScheduling(VL, VL0);
4793       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4794                    ReuseShuffleIndicies);
4795       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4796       return;
4797   }
4798 }
4799 
4800 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4801   unsigned N = 1;
4802   Type *EltTy = T;
4803 
4804   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4805          isa<VectorType>(EltTy)) {
4806     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4807       // Check that struct is homogeneous.
4808       for (const auto *Ty : ST->elements())
4809         if (Ty != *ST->element_begin())
4810           return 0;
4811       N *= ST->getNumElements();
4812       EltTy = *ST->element_begin();
4813     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4814       N *= AT->getNumElements();
4815       EltTy = AT->getElementType();
4816     } else {
4817       auto *VT = cast<FixedVectorType>(EltTy);
4818       N *= VT->getNumElements();
4819       EltTy = VT->getElementType();
4820     }
4821   }
4822 
4823   if (!isValidElementType(EltTy))
4824     return 0;
4825   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4826   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4827     return 0;
4828   return N;
4829 }
4830 
4831 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4832                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4833   const auto *It = find_if(VL, [](Value *V) {
4834     return isa<ExtractElementInst, ExtractValueInst>(V);
4835   });
4836   assert(It != VL.end() && "Expected at least one extract instruction.");
4837   auto *E0 = cast<Instruction>(*It);
4838   assert(all_of(VL,
4839                 [](Value *V) {
4840                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4841                       V);
4842                 }) &&
4843          "Invalid opcode");
4844   // Check if all of the extracts come from the same vector and from the
4845   // correct offset.
4846   Value *Vec = E0->getOperand(0);
4847 
4848   CurrentOrder.clear();
4849 
4850   // We have to extract from a vector/aggregate with the same number of elements.
4851   unsigned NElts;
4852   if (E0->getOpcode() == Instruction::ExtractValue) {
4853     const DataLayout &DL = E0->getModule()->getDataLayout();
4854     NElts = canMapToVector(Vec->getType(), DL);
4855     if (!NElts)
4856       return false;
4857     // Check if load can be rewritten as load of vector.
4858     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4859     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4860       return false;
4861   } else {
4862     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4863   }
4864 
4865   if (NElts != VL.size())
4866     return false;
4867 
4868   // Check that all of the indices extract from the correct offset.
4869   bool ShouldKeepOrder = true;
4870   unsigned E = VL.size();
4871   // Assign to all items the initial value E + 1 so we can check if the extract
4872   // instruction index was used already.
4873   // Also, later we can check that all the indices are used and we have a
4874   // consecutive access in the extract instructions, by checking that no
4875   // element of CurrentOrder still has value E + 1.
4876   CurrentOrder.assign(E, E);
4877   unsigned I = 0;
4878   for (; I < E; ++I) {
4879     auto *Inst = dyn_cast<Instruction>(VL[I]);
4880     if (!Inst)
4881       continue;
4882     if (Inst->getOperand(0) != Vec)
4883       break;
4884     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4885       if (isa<UndefValue>(EE->getIndexOperand()))
4886         continue;
4887     Optional<unsigned> Idx = getExtractIndex(Inst);
4888     if (!Idx)
4889       break;
4890     const unsigned ExtIdx = *Idx;
4891     if (ExtIdx != I) {
4892       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4893         break;
4894       ShouldKeepOrder = false;
4895       CurrentOrder[ExtIdx] = I;
4896     } else {
4897       if (CurrentOrder[I] != E)
4898         break;
4899       CurrentOrder[I] = I;
4900     }
4901   }
4902   if (I < E) {
4903     CurrentOrder.clear();
4904     return false;
4905   }
4906   if (ShouldKeepOrder)
4907     CurrentOrder.clear();
4908 
4909   return ShouldKeepOrder;
4910 }
4911 
4912 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4913                                     ArrayRef<Value *> VectorizedVals) const {
4914   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4915          all_of(I->users(), [this](User *U) {
4916            return ScalarToTreeEntry.count(U) > 0 ||
4917                   isVectorLikeInstWithConstOps(U) ||
4918                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4919          });
4920 }
4921 
4922 static std::pair<InstructionCost, InstructionCost>
4923 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4924                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4925   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4926 
4927   // Calculate the cost of the scalar and vector calls.
4928   SmallVector<Type *, 4> VecTys;
4929   for (Use &Arg : CI->args())
4930     VecTys.push_back(
4931         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4932   FastMathFlags FMF;
4933   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4934     FMF = FPCI->getFastMathFlags();
4935   SmallVector<const Value *> Arguments(CI->args());
4936   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4937                                     dyn_cast<IntrinsicInst>(CI));
4938   auto IntrinsicCost =
4939     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4940 
4941   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4942                                      VecTy->getNumElements())),
4943                             false /*HasGlobalPred*/);
4944   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4945   auto LibCost = IntrinsicCost;
4946   if (!CI->isNoBuiltin() && VecFunc) {
4947     // Calculate the cost of the vector library call.
4948     // If the corresponding vector call is cheaper, return its cost.
4949     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4950                                     TTI::TCK_RecipThroughput);
4951   }
4952   return {IntrinsicCost, LibCost};
4953 }
4954 
4955 /// Compute the cost of creating a vector of type \p VecTy containing the
4956 /// extracted values from \p VL.
4957 static InstructionCost
4958 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4959                    TargetTransformInfo::ShuffleKind ShuffleKind,
4960                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4961   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4962 
4963   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4964       VecTy->getNumElements() < NumOfParts)
4965     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4966 
4967   bool AllConsecutive = true;
4968   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4969   unsigned Idx = -1;
4970   InstructionCost Cost = 0;
4971 
4972   // Process extracts in blocks of EltsPerVector to check if the source vector
4973   // operand can be re-used directly. If not, add the cost of creating a shuffle
4974   // to extract the values into a vector register.
4975   for (auto *V : VL) {
4976     ++Idx;
4977 
4978     // Need to exclude undefs from analysis.
4979     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4980       continue;
4981 
4982     // Reached the start of a new vector registers.
4983     if (Idx % EltsPerVector == 0) {
4984       AllConsecutive = true;
4985       continue;
4986     }
4987 
4988     // Check all extracts for a vector register on the target directly
4989     // extract values in order.
4990     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4991     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4992       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4993       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4994                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4995     }
4996 
4997     if (AllConsecutive)
4998       continue;
4999 
5000     // Skip all indices, except for the last index per vector block.
5001     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5002       continue;
5003 
5004     // If we have a series of extracts which are not consecutive and hence
5005     // cannot re-use the source vector register directly, compute the shuffle
5006     // cost to extract the a vector with EltsPerVector elements.
5007     Cost += TTI.getShuffleCost(
5008         TargetTransformInfo::SK_PermuteSingleSrc,
5009         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5010   }
5011   return Cost;
5012 }
5013 
5014 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5015 /// operations operands.
5016 static void
5017 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5018                       ArrayRef<int> ReusesIndices,
5019                       const function_ref<bool(Instruction *)> IsAltOp,
5020                       SmallVectorImpl<int> &Mask,
5021                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5022                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5023   unsigned Sz = VL.size();
5024   Mask.assign(Sz, UndefMaskElem);
5025   SmallVector<int> OrderMask;
5026   if (!ReorderIndices.empty())
5027     inversePermutation(ReorderIndices, OrderMask);
5028   for (unsigned I = 0; I < Sz; ++I) {
5029     unsigned Idx = I;
5030     if (!ReorderIndices.empty())
5031       Idx = OrderMask[I];
5032     auto *OpInst = cast<Instruction>(VL[Idx]);
5033     if (IsAltOp(OpInst)) {
5034       Mask[I] = Sz + Idx;
5035       if (AltScalars)
5036         AltScalars->push_back(OpInst);
5037     } else {
5038       Mask[I] = Idx;
5039       if (OpScalars)
5040         OpScalars->push_back(OpInst);
5041     }
5042   }
5043   if (!ReusesIndices.empty()) {
5044     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5045     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5046       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5047     });
5048     Mask.swap(NewMask);
5049   }
5050 }
5051 
5052 /// Checks if the specified instruction \p I is an alternate operation for the
5053 /// given \p MainOp and \p AltOp instructions.
5054 static bool isAlternateInstruction(const Instruction *I,
5055                                    const Instruction *MainOp,
5056                                    const Instruction *AltOp) {
5057   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5058     auto *AltCI0 = cast<CmpInst>(AltOp);
5059     auto *CI = cast<CmpInst>(I);
5060     CmpInst::Predicate P0 = CI0->getPredicate();
5061     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5062     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5063     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5064     CmpInst::Predicate CurrentPred = CI->getPredicate();
5065     if (P0 == AltP0Swapped)
5066       return I == AltCI0 ||
5067              (I != MainOp &&
5068               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5069                                    CI->getOperand(0), CI->getOperand(1)));
5070     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5071   }
5072   return I->getOpcode() == AltOp->getOpcode();
5073 }
5074 
5075 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5076                                       ArrayRef<Value *> VectorizedVals) {
5077   ArrayRef<Value*> VL = E->Scalars;
5078 
5079   Type *ScalarTy = VL[0]->getType();
5080   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5081     ScalarTy = SI->getValueOperand()->getType();
5082   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5083     ScalarTy = CI->getOperand(0)->getType();
5084   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5085     ScalarTy = IE->getOperand(1)->getType();
5086   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5087   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5088 
5089   // If we have computed a smaller type for the expression, update VecTy so
5090   // that the costs will be accurate.
5091   if (MinBWs.count(VL[0]))
5092     VecTy = FixedVectorType::get(
5093         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5094   unsigned EntryVF = E->getVectorFactor();
5095   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5096 
5097   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5098   // FIXME: it tries to fix a problem with MSVC buildbots.
5099   TargetTransformInfo &TTIRef = *TTI;
5100   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5101                                VectorizedVals, E](InstructionCost &Cost) {
5102     DenseMap<Value *, int> ExtractVectorsTys;
5103     SmallPtrSet<Value *, 4> CheckedExtracts;
5104     for (auto *V : VL) {
5105       if (isa<UndefValue>(V))
5106         continue;
5107       // If all users of instruction are going to be vectorized and this
5108       // instruction itself is not going to be vectorized, consider this
5109       // instruction as dead and remove its cost from the final cost of the
5110       // vectorized tree.
5111       // Also, avoid adjusting the cost for extractelements with multiple uses
5112       // in different graph entries.
5113       const TreeEntry *VE = getTreeEntry(V);
5114       if (!CheckedExtracts.insert(V).second ||
5115           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5116           (VE && VE != E))
5117         continue;
5118       auto *EE = cast<ExtractElementInst>(V);
5119       Optional<unsigned> EEIdx = getExtractIndex(EE);
5120       if (!EEIdx)
5121         continue;
5122       unsigned Idx = *EEIdx;
5123       if (TTIRef.getNumberOfParts(VecTy) !=
5124           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5125         auto It =
5126             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5127         It->getSecond() = std::min<int>(It->second, Idx);
5128       }
5129       // Take credit for instruction that will become dead.
5130       if (EE->hasOneUse()) {
5131         Instruction *Ext = EE->user_back();
5132         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5133             all_of(Ext->users(),
5134                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5135           // Use getExtractWithExtendCost() to calculate the cost of
5136           // extractelement/ext pair.
5137           Cost -=
5138               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5139                                               EE->getVectorOperandType(), Idx);
5140           // Add back the cost of s|zext which is subtracted separately.
5141           Cost += TTIRef.getCastInstrCost(
5142               Ext->getOpcode(), Ext->getType(), EE->getType(),
5143               TTI::getCastContextHint(Ext), CostKind, Ext);
5144           continue;
5145         }
5146       }
5147       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5148                                         EE->getVectorOperandType(), Idx);
5149     }
5150     // Add a cost for subvector extracts/inserts if required.
5151     for (const auto &Data : ExtractVectorsTys) {
5152       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5153       unsigned NumElts = VecTy->getNumElements();
5154       if (Data.second % NumElts == 0)
5155         continue;
5156       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5157         unsigned Idx = (Data.second / NumElts) * NumElts;
5158         unsigned EENumElts = EEVTy->getNumElements();
5159         if (Idx + NumElts <= EENumElts) {
5160           Cost +=
5161               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5162                                     EEVTy, None, Idx, VecTy);
5163         } else {
5164           // Need to round up the subvector type vectorization factor to avoid a
5165           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5166           // <= EENumElts.
5167           auto *SubVT =
5168               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5169           Cost +=
5170               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5171                                     EEVTy, None, Idx, SubVT);
5172         }
5173       } else {
5174         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5175                                       VecTy, None, 0, EEVTy);
5176       }
5177     }
5178   };
5179   if (E->State == TreeEntry::NeedToGather) {
5180     if (allConstant(VL))
5181       return 0;
5182     if (isa<InsertElementInst>(VL[0]))
5183       return InstructionCost::getInvalid();
5184     SmallVector<int> Mask;
5185     SmallVector<const TreeEntry *> Entries;
5186     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5187         isGatherShuffledEntry(E, Mask, Entries);
5188     if (Shuffle.hasValue()) {
5189       InstructionCost GatherCost = 0;
5190       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5191         // Perfect match in the graph, will reuse the previously vectorized
5192         // node. Cost is 0.
5193         LLVM_DEBUG(
5194             dbgs()
5195             << "SLP: perfect diamond match for gather bundle that starts with "
5196             << *VL.front() << ".\n");
5197         if (NeedToShuffleReuses)
5198           GatherCost =
5199               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5200                                   FinalVecTy, E->ReuseShuffleIndices);
5201       } else {
5202         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5203                           << " entries for bundle that starts with "
5204                           << *VL.front() << ".\n");
5205         // Detected that instead of gather we can emit a shuffle of single/two
5206         // previously vectorized nodes. Add the cost of the permutation rather
5207         // than gather.
5208         ::addMask(Mask, E->ReuseShuffleIndices);
5209         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5210       }
5211       return GatherCost;
5212     }
5213     if ((E->getOpcode() == Instruction::ExtractElement ||
5214          all_of(E->Scalars,
5215                 [](Value *V) {
5216                   return isa<ExtractElementInst, UndefValue>(V);
5217                 })) &&
5218         allSameType(VL)) {
5219       // Check that gather of extractelements can be represented as just a
5220       // shuffle of a single/two vectors the scalars are extracted from.
5221       SmallVector<int> Mask;
5222       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5223           isFixedVectorShuffle(VL, Mask);
5224       if (ShuffleKind.hasValue()) {
5225         // Found the bunch of extractelement instructions that must be gathered
5226         // into a vector and can be represented as a permutation elements in a
5227         // single input vector or of 2 input vectors.
5228         InstructionCost Cost =
5229             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5230         AdjustExtractsCost(Cost);
5231         if (NeedToShuffleReuses)
5232           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5233                                       FinalVecTy, E->ReuseShuffleIndices);
5234         return Cost;
5235       }
5236     }
5237     if (isSplat(VL)) {
5238       // Found the broadcasting of the single scalar, calculate the cost as the
5239       // broadcast.
5240       assert(VecTy == FinalVecTy &&
5241              "No reused scalars expected for broadcast.");
5242       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
5243     }
5244     InstructionCost ReuseShuffleCost = 0;
5245     if (NeedToShuffleReuses)
5246       ReuseShuffleCost = TTI->getShuffleCost(
5247           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5248     // Improve gather cost for gather of loads, if we can group some of the
5249     // loads into vector loads.
5250     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5251         !E->isAltShuffle()) {
5252       BoUpSLP::ValueSet VectorizedLoads;
5253       unsigned StartIdx = 0;
5254       unsigned VF = VL.size() / 2;
5255       unsigned VectorizedCnt = 0;
5256       unsigned ScatterVectorizeCnt = 0;
5257       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5258       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5259         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5260              Cnt += VF) {
5261           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5262           if (!VectorizedLoads.count(Slice.front()) &&
5263               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5264             SmallVector<Value *> PointerOps;
5265             OrdersType CurrentOrder;
5266             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5267                                               *SE, CurrentOrder, PointerOps);
5268             switch (LS) {
5269             case LoadsState::Vectorize:
5270             case LoadsState::ScatterVectorize:
5271               // Mark the vectorized loads so that we don't vectorize them
5272               // again.
5273               if (LS == LoadsState::Vectorize)
5274                 ++VectorizedCnt;
5275               else
5276                 ++ScatterVectorizeCnt;
5277               VectorizedLoads.insert(Slice.begin(), Slice.end());
5278               // If we vectorized initial block, no need to try to vectorize it
5279               // again.
5280               if (Cnt == StartIdx)
5281                 StartIdx += VF;
5282               break;
5283             case LoadsState::Gather:
5284               break;
5285             }
5286           }
5287         }
5288         // Check if the whole array was vectorized already - exit.
5289         if (StartIdx >= VL.size())
5290           break;
5291         // Found vectorizable parts - exit.
5292         if (!VectorizedLoads.empty())
5293           break;
5294       }
5295       if (!VectorizedLoads.empty()) {
5296         InstructionCost GatherCost = 0;
5297         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5298         bool NeedInsertSubvectorAnalysis =
5299             !NumParts || (VL.size() / VF) > NumParts;
5300         // Get the cost for gathered loads.
5301         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5302           if (VectorizedLoads.contains(VL[I]))
5303             continue;
5304           GatherCost += getGatherCost(VL.slice(I, VF));
5305         }
5306         // The cost for vectorized loads.
5307         InstructionCost ScalarsCost = 0;
5308         for (Value *V : VectorizedLoads) {
5309           auto *LI = cast<LoadInst>(V);
5310           ScalarsCost += TTI->getMemoryOpCost(
5311               Instruction::Load, LI->getType(), LI->getAlign(),
5312               LI->getPointerAddressSpace(), CostKind, LI);
5313         }
5314         auto *LI = cast<LoadInst>(E->getMainOp());
5315         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5316         Align Alignment = LI->getAlign();
5317         GatherCost +=
5318             VectorizedCnt *
5319             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5320                                  LI->getPointerAddressSpace(), CostKind, LI);
5321         GatherCost += ScatterVectorizeCnt *
5322                       TTI->getGatherScatterOpCost(
5323                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5324                           /*VariableMask=*/false, Alignment, CostKind, LI);
5325         if (NeedInsertSubvectorAnalysis) {
5326           // Add the cost for the subvectors insert.
5327           for (int I = VF, E = VL.size(); I < E; I += VF)
5328             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5329                                               None, I, LoadTy);
5330         }
5331         return ReuseShuffleCost + GatherCost - ScalarsCost;
5332       }
5333     }
5334     return ReuseShuffleCost + getGatherCost(VL);
5335   }
5336   InstructionCost CommonCost = 0;
5337   SmallVector<int> Mask;
5338   if (!E->ReorderIndices.empty()) {
5339     SmallVector<int> NewMask;
5340     if (E->getOpcode() == Instruction::Store) {
5341       // For stores the order is actually a mask.
5342       NewMask.resize(E->ReorderIndices.size());
5343       copy(E->ReorderIndices, NewMask.begin());
5344     } else {
5345       inversePermutation(E->ReorderIndices, NewMask);
5346     }
5347     ::addMask(Mask, NewMask);
5348   }
5349   if (NeedToShuffleReuses)
5350     ::addMask(Mask, E->ReuseShuffleIndices);
5351   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5352     CommonCost =
5353         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5354   assert((E->State == TreeEntry::Vectorize ||
5355           E->State == TreeEntry::ScatterVectorize) &&
5356          "Unhandled state");
5357   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5358   Instruction *VL0 = E->getMainOp();
5359   unsigned ShuffleOrOp =
5360       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5361   switch (ShuffleOrOp) {
5362     case Instruction::PHI:
5363       return 0;
5364 
5365     case Instruction::ExtractValue:
5366     case Instruction::ExtractElement: {
5367       // The common cost of removal ExtractElement/ExtractValue instructions +
5368       // the cost of shuffles, if required to resuffle the original vector.
5369       if (NeedToShuffleReuses) {
5370         unsigned Idx = 0;
5371         for (unsigned I : E->ReuseShuffleIndices) {
5372           if (ShuffleOrOp == Instruction::ExtractElement) {
5373             auto *EE = cast<ExtractElementInst>(VL[I]);
5374             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5375                                                   EE->getVectorOperandType(),
5376                                                   *getExtractIndex(EE));
5377           } else {
5378             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5379                                                   VecTy, Idx);
5380             ++Idx;
5381           }
5382         }
5383         Idx = EntryVF;
5384         for (Value *V : VL) {
5385           if (ShuffleOrOp == Instruction::ExtractElement) {
5386             auto *EE = cast<ExtractElementInst>(V);
5387             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5388                                                   EE->getVectorOperandType(),
5389                                                   *getExtractIndex(EE));
5390           } else {
5391             --Idx;
5392             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5393                                                   VecTy, Idx);
5394           }
5395         }
5396       }
5397       if (ShuffleOrOp == Instruction::ExtractValue) {
5398         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5399           auto *EI = cast<Instruction>(VL[I]);
5400           // Take credit for instruction that will become dead.
5401           if (EI->hasOneUse()) {
5402             Instruction *Ext = EI->user_back();
5403             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5404                 all_of(Ext->users(),
5405                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5406               // Use getExtractWithExtendCost() to calculate the cost of
5407               // extractelement/ext pair.
5408               CommonCost -= TTI->getExtractWithExtendCost(
5409                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5410               // Add back the cost of s|zext which is subtracted separately.
5411               CommonCost += TTI->getCastInstrCost(
5412                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5413                   TTI::getCastContextHint(Ext), CostKind, Ext);
5414               continue;
5415             }
5416           }
5417           CommonCost -=
5418               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5419         }
5420       } else {
5421         AdjustExtractsCost(CommonCost);
5422       }
5423       return CommonCost;
5424     }
5425     case Instruction::InsertElement: {
5426       assert(E->ReuseShuffleIndices.empty() &&
5427              "Unique insertelements only are expected.");
5428       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5429 
5430       unsigned const NumElts = SrcVecTy->getNumElements();
5431       unsigned const NumScalars = VL.size();
5432       APInt DemandedElts = APInt::getZero(NumElts);
5433       // TODO: Add support for Instruction::InsertValue.
5434       SmallVector<int> Mask;
5435       if (!E->ReorderIndices.empty()) {
5436         inversePermutation(E->ReorderIndices, Mask);
5437         Mask.append(NumElts - NumScalars, UndefMaskElem);
5438       } else {
5439         Mask.assign(NumElts, UndefMaskElem);
5440         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5441       }
5442       unsigned Offset = *getInsertIndex(VL0);
5443       bool IsIdentity = true;
5444       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5445       Mask.swap(PrevMask);
5446       for (unsigned I = 0; I < NumScalars; ++I) {
5447         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5448         DemandedElts.setBit(InsertIdx);
5449         IsIdentity &= InsertIdx - Offset == I;
5450         Mask[InsertIdx - Offset] = I;
5451       }
5452       assert(Offset < NumElts && "Failed to find vector index offset");
5453 
5454       InstructionCost Cost = 0;
5455       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5456                                             /*Insert*/ true, /*Extract*/ false);
5457 
5458       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5459         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5460         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5461         Cost += TTI->getShuffleCost(
5462             TargetTransformInfo::SK_PermuteSingleSrc,
5463             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5464       } else if (!IsIdentity) {
5465         auto *FirstInsert =
5466             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5467               return !is_contained(E->Scalars,
5468                                    cast<Instruction>(V)->getOperand(0));
5469             }));
5470         if (isUndefVector(FirstInsert->getOperand(0))) {
5471           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5472         } else {
5473           SmallVector<int> InsertMask(NumElts);
5474           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5475           for (unsigned I = 0; I < NumElts; I++) {
5476             if (Mask[I] != UndefMaskElem)
5477               InsertMask[Offset + I] = NumElts + I;
5478           }
5479           Cost +=
5480               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5481         }
5482       }
5483 
5484       return Cost;
5485     }
5486     case Instruction::ZExt:
5487     case Instruction::SExt:
5488     case Instruction::FPToUI:
5489     case Instruction::FPToSI:
5490     case Instruction::FPExt:
5491     case Instruction::PtrToInt:
5492     case Instruction::IntToPtr:
5493     case Instruction::SIToFP:
5494     case Instruction::UIToFP:
5495     case Instruction::Trunc:
5496     case Instruction::FPTrunc:
5497     case Instruction::BitCast: {
5498       Type *SrcTy = VL0->getOperand(0)->getType();
5499       InstructionCost ScalarEltCost =
5500           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5501                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5502       if (NeedToShuffleReuses) {
5503         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5504       }
5505 
5506       // Calculate the cost of this instruction.
5507       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5508 
5509       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5510       InstructionCost VecCost = 0;
5511       // Check if the values are candidates to demote.
5512       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5513         VecCost = CommonCost + TTI->getCastInstrCost(
5514                                    E->getOpcode(), VecTy, SrcVecTy,
5515                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5516       }
5517       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5518       return VecCost - ScalarCost;
5519     }
5520     case Instruction::FCmp:
5521     case Instruction::ICmp:
5522     case Instruction::Select: {
5523       // Calculate the cost of this instruction.
5524       InstructionCost ScalarEltCost =
5525           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5526                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5527       if (NeedToShuffleReuses) {
5528         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5529       }
5530       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5531       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5532 
5533       // Check if all entries in VL are either compares or selects with compares
5534       // as condition that have the same predicates.
5535       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5536       bool First = true;
5537       for (auto *V : VL) {
5538         CmpInst::Predicate CurrentPred;
5539         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5540         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5541              !match(V, MatchCmp)) ||
5542             (!First && VecPred != CurrentPred)) {
5543           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5544           break;
5545         }
5546         First = false;
5547         VecPred = CurrentPred;
5548       }
5549 
5550       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5551           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5552       // Check if it is possible and profitable to use min/max for selects in
5553       // VL.
5554       //
5555       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5556       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5557         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5558                                           {VecTy, VecTy});
5559         InstructionCost IntrinsicCost =
5560             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5561         // If the selects are the only uses of the compares, they will be dead
5562         // and we can adjust the cost by removing their cost.
5563         if (IntrinsicAndUse.second)
5564           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5565                                                    MaskTy, VecPred, CostKind);
5566         VecCost = std::min(VecCost, IntrinsicCost);
5567       }
5568       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5569       return CommonCost + VecCost - ScalarCost;
5570     }
5571     case Instruction::FNeg:
5572     case Instruction::Add:
5573     case Instruction::FAdd:
5574     case Instruction::Sub:
5575     case Instruction::FSub:
5576     case Instruction::Mul:
5577     case Instruction::FMul:
5578     case Instruction::UDiv:
5579     case Instruction::SDiv:
5580     case Instruction::FDiv:
5581     case Instruction::URem:
5582     case Instruction::SRem:
5583     case Instruction::FRem:
5584     case Instruction::Shl:
5585     case Instruction::LShr:
5586     case Instruction::AShr:
5587     case Instruction::And:
5588     case Instruction::Or:
5589     case Instruction::Xor: {
5590       // Certain instructions can be cheaper to vectorize if they have a
5591       // constant second vector operand.
5592       TargetTransformInfo::OperandValueKind Op1VK =
5593           TargetTransformInfo::OK_AnyValue;
5594       TargetTransformInfo::OperandValueKind Op2VK =
5595           TargetTransformInfo::OK_UniformConstantValue;
5596       TargetTransformInfo::OperandValueProperties Op1VP =
5597           TargetTransformInfo::OP_None;
5598       TargetTransformInfo::OperandValueProperties Op2VP =
5599           TargetTransformInfo::OP_PowerOf2;
5600 
5601       // If all operands are exactly the same ConstantInt then set the
5602       // operand kind to OK_UniformConstantValue.
5603       // If instead not all operands are constants, then set the operand kind
5604       // to OK_AnyValue. If all operands are constants but not the same,
5605       // then set the operand kind to OK_NonUniformConstantValue.
5606       ConstantInt *CInt0 = nullptr;
5607       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5608         const Instruction *I = cast<Instruction>(VL[i]);
5609         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5610         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5611         if (!CInt) {
5612           Op2VK = TargetTransformInfo::OK_AnyValue;
5613           Op2VP = TargetTransformInfo::OP_None;
5614           break;
5615         }
5616         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5617             !CInt->getValue().isPowerOf2())
5618           Op2VP = TargetTransformInfo::OP_None;
5619         if (i == 0) {
5620           CInt0 = CInt;
5621           continue;
5622         }
5623         if (CInt0 != CInt)
5624           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5625       }
5626 
5627       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5628       InstructionCost ScalarEltCost =
5629           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5630                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5631       if (NeedToShuffleReuses) {
5632         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5633       }
5634       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5635       InstructionCost VecCost =
5636           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5637                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5638       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5639       return CommonCost + VecCost - ScalarCost;
5640     }
5641     case Instruction::GetElementPtr: {
5642       TargetTransformInfo::OperandValueKind Op1VK =
5643           TargetTransformInfo::OK_AnyValue;
5644       TargetTransformInfo::OperandValueKind Op2VK =
5645           TargetTransformInfo::OK_UniformConstantValue;
5646 
5647       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5648           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5649       if (NeedToShuffleReuses) {
5650         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5651       }
5652       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5653       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5654           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5655       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5656       return CommonCost + VecCost - ScalarCost;
5657     }
5658     case Instruction::Load: {
5659       // Cost of wide load - cost of scalar loads.
5660       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5661       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5662           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5663       if (NeedToShuffleReuses) {
5664         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5665       }
5666       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5667       InstructionCost VecLdCost;
5668       if (E->State == TreeEntry::Vectorize) {
5669         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5670                                          CostKind, VL0);
5671       } else {
5672         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5673         Align CommonAlignment = Alignment;
5674         for (Value *V : VL)
5675           CommonAlignment =
5676               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5677         VecLdCost = TTI->getGatherScatterOpCost(
5678             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5679             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5680       }
5681       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5682       return CommonCost + VecLdCost - ScalarLdCost;
5683     }
5684     case Instruction::Store: {
5685       // We know that we can merge the stores. Calculate the cost.
5686       bool IsReorder = !E->ReorderIndices.empty();
5687       auto *SI =
5688           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5689       Align Alignment = SI->getAlign();
5690       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5691           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5692       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5693       InstructionCost VecStCost = TTI->getMemoryOpCost(
5694           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5695       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5696       return CommonCost + VecStCost - ScalarStCost;
5697     }
5698     case Instruction::Call: {
5699       CallInst *CI = cast<CallInst>(VL0);
5700       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5701 
5702       // Calculate the cost of the scalar and vector calls.
5703       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5704       InstructionCost ScalarEltCost =
5705           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5706       if (NeedToShuffleReuses) {
5707         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5708       }
5709       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5710 
5711       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5712       InstructionCost VecCallCost =
5713           std::min(VecCallCosts.first, VecCallCosts.second);
5714 
5715       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5716                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5717                         << " for " << *CI << "\n");
5718 
5719       return CommonCost + VecCallCost - ScalarCallCost;
5720     }
5721     case Instruction::ShuffleVector: {
5722       assert(E->isAltShuffle() &&
5723              ((Instruction::isBinaryOp(E->getOpcode()) &&
5724                Instruction::isBinaryOp(E->getAltOpcode())) ||
5725               (Instruction::isCast(E->getOpcode()) &&
5726                Instruction::isCast(E->getAltOpcode())) ||
5727               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5728              "Invalid Shuffle Vector Operand");
5729       InstructionCost ScalarCost = 0;
5730       if (NeedToShuffleReuses) {
5731         for (unsigned Idx : E->ReuseShuffleIndices) {
5732           Instruction *I = cast<Instruction>(VL[Idx]);
5733           CommonCost -= TTI->getInstructionCost(I, CostKind);
5734         }
5735         for (Value *V : VL) {
5736           Instruction *I = cast<Instruction>(V);
5737           CommonCost += TTI->getInstructionCost(I, CostKind);
5738         }
5739       }
5740       for (Value *V : VL) {
5741         Instruction *I = cast<Instruction>(V);
5742         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5743         ScalarCost += TTI->getInstructionCost(I, CostKind);
5744       }
5745       // VecCost is equal to sum of the cost of creating 2 vectors
5746       // and the cost of creating shuffle.
5747       InstructionCost VecCost = 0;
5748       // Try to find the previous shuffle node with the same operands and same
5749       // main/alternate ops.
5750       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5751         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5752           if (TE.get() == E)
5753             break;
5754           if (TE->isAltShuffle() &&
5755               ((TE->getOpcode() == E->getOpcode() &&
5756                 TE->getAltOpcode() == E->getAltOpcode()) ||
5757                (TE->getOpcode() == E->getAltOpcode() &&
5758                 TE->getAltOpcode() == E->getOpcode())) &&
5759               TE->hasEqualOperands(*E))
5760             return true;
5761         }
5762         return false;
5763       };
5764       if (TryFindNodeWithEqualOperands()) {
5765         LLVM_DEBUG({
5766           dbgs() << "SLP: diamond match for alternate node found.\n";
5767           E->dump();
5768         });
5769         // No need to add new vector costs here since we're going to reuse
5770         // same main/alternate vector ops, just do different shuffling.
5771       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5772         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5773         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5774                                                CostKind);
5775       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5776         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5777                                           Builder.getInt1Ty(),
5778                                           CI0->getPredicate(), CostKind, VL0);
5779         VecCost += TTI->getCmpSelInstrCost(
5780             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5781             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5782             E->getAltOp());
5783       } else {
5784         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5785         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5786         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5787         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5788         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5789                                         TTI::CastContextHint::None, CostKind);
5790         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5791                                          TTI::CastContextHint::None, CostKind);
5792       }
5793 
5794       SmallVector<int> Mask;
5795       buildShuffleEntryMask(
5796           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5797           [E](Instruction *I) {
5798             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5799             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5800           },
5801           Mask);
5802       CommonCost =
5803           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5804       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5805       return CommonCost + VecCost - ScalarCost;
5806     }
5807     default:
5808       llvm_unreachable("Unknown instruction");
5809   }
5810 }
5811 
5812 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5813   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5814                     << VectorizableTree.size() << " is fully vectorizable .\n");
5815 
5816   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5817     SmallVector<int> Mask;
5818     return TE->State == TreeEntry::NeedToGather &&
5819            !any_of(TE->Scalars,
5820                    [this](Value *V) { return EphValues.contains(V); }) &&
5821            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5822             TE->Scalars.size() < Limit ||
5823             ((TE->getOpcode() == Instruction::ExtractElement ||
5824               all_of(TE->Scalars,
5825                      [](Value *V) {
5826                        return isa<ExtractElementInst, UndefValue>(V);
5827                      })) &&
5828              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5829             (TE->State == TreeEntry::NeedToGather &&
5830              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5831   };
5832 
5833   // We only handle trees of heights 1 and 2.
5834   if (VectorizableTree.size() == 1 &&
5835       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5836        (ForReduction &&
5837         AreVectorizableGathers(VectorizableTree[0].get(),
5838                                VectorizableTree[0]->Scalars.size()) &&
5839         VectorizableTree[0]->getVectorFactor() > 2)))
5840     return true;
5841 
5842   if (VectorizableTree.size() != 2)
5843     return false;
5844 
5845   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5846   // with the second gather nodes if they have less scalar operands rather than
5847   // the initial tree element (may be profitable to shuffle the second gather)
5848   // or they are extractelements, which form shuffle.
5849   SmallVector<int> Mask;
5850   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5851       AreVectorizableGathers(VectorizableTree[1].get(),
5852                              VectorizableTree[0]->Scalars.size()))
5853     return true;
5854 
5855   // Gathering cost would be too much for tiny trees.
5856   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5857       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5858        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5859     return false;
5860 
5861   return true;
5862 }
5863 
5864 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5865                                        TargetTransformInfo *TTI,
5866                                        bool MustMatchOrInst) {
5867   // Look past the root to find a source value. Arbitrarily follow the
5868   // path through operand 0 of any 'or'. Also, peek through optional
5869   // shift-left-by-multiple-of-8-bits.
5870   Value *ZextLoad = Root;
5871   const APInt *ShAmtC;
5872   bool FoundOr = false;
5873   while (!isa<ConstantExpr>(ZextLoad) &&
5874          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5875           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5876            ShAmtC->urem(8) == 0))) {
5877     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5878     ZextLoad = BinOp->getOperand(0);
5879     if (BinOp->getOpcode() == Instruction::Or)
5880       FoundOr = true;
5881   }
5882   // Check if the input is an extended load of the required or/shift expression.
5883   Value *Load;
5884   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5885       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5886     return false;
5887 
5888   // Require that the total load bit width is a legal integer type.
5889   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5890   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5891   Type *SrcTy = Load->getType();
5892   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5893   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5894     return false;
5895 
5896   // Everything matched - assume that we can fold the whole sequence using
5897   // load combining.
5898   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5899              << *(cast<Instruction>(Root)) << "\n");
5900 
5901   return true;
5902 }
5903 
5904 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5905   if (RdxKind != RecurKind::Or)
5906     return false;
5907 
5908   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5909   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5910   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5911                                     /* MatchOr */ false);
5912 }
5913 
5914 bool BoUpSLP::isLoadCombineCandidate() const {
5915   // Peek through a final sequence of stores and check if all operations are
5916   // likely to be load-combined.
5917   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5918   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5919     Value *X;
5920     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5921         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5922       return false;
5923   }
5924   return true;
5925 }
5926 
5927 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5928   // No need to vectorize inserts of gathered values.
5929   if (VectorizableTree.size() == 2 &&
5930       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5931       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5932     return true;
5933 
5934   // We can vectorize the tree if its size is greater than or equal to the
5935   // minimum size specified by the MinTreeSize command line option.
5936   if (VectorizableTree.size() >= MinTreeSize)
5937     return false;
5938 
5939   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5940   // can vectorize it if we can prove it fully vectorizable.
5941   if (isFullyVectorizableTinyTree(ForReduction))
5942     return false;
5943 
5944   assert(VectorizableTree.empty()
5945              ? ExternalUses.empty()
5946              : true && "We shouldn't have any external users");
5947 
5948   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5949   // vectorizable.
5950   return true;
5951 }
5952 
5953 InstructionCost BoUpSLP::getSpillCost() const {
5954   // Walk from the bottom of the tree to the top, tracking which values are
5955   // live. When we see a call instruction that is not part of our tree,
5956   // query TTI to see if there is a cost to keeping values live over it
5957   // (for example, if spills and fills are required).
5958   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5959   InstructionCost Cost = 0;
5960 
5961   SmallPtrSet<Instruction*, 4> LiveValues;
5962   Instruction *PrevInst = nullptr;
5963 
5964   // The entries in VectorizableTree are not necessarily ordered by their
5965   // position in basic blocks. Collect them and order them by dominance so later
5966   // instructions are guaranteed to be visited first. For instructions in
5967   // different basic blocks, we only scan to the beginning of the block, so
5968   // their order does not matter, as long as all instructions in a basic block
5969   // are grouped together. Using dominance ensures a deterministic order.
5970   SmallVector<Instruction *, 16> OrderedScalars;
5971   for (const auto &TEPtr : VectorizableTree) {
5972     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5973     if (!Inst)
5974       continue;
5975     OrderedScalars.push_back(Inst);
5976   }
5977   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5978     auto *NodeA = DT->getNode(A->getParent());
5979     auto *NodeB = DT->getNode(B->getParent());
5980     assert(NodeA && "Should only process reachable instructions");
5981     assert(NodeB && "Should only process reachable instructions");
5982     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5983            "Different nodes should have different DFS numbers");
5984     if (NodeA != NodeB)
5985       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5986     return B->comesBefore(A);
5987   });
5988 
5989   for (Instruction *Inst : OrderedScalars) {
5990     if (!PrevInst) {
5991       PrevInst = Inst;
5992       continue;
5993     }
5994 
5995     // Update LiveValues.
5996     LiveValues.erase(PrevInst);
5997     for (auto &J : PrevInst->operands()) {
5998       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5999         LiveValues.insert(cast<Instruction>(&*J));
6000     }
6001 
6002     LLVM_DEBUG({
6003       dbgs() << "SLP: #LV: " << LiveValues.size();
6004       for (auto *X : LiveValues)
6005         dbgs() << " " << X->getName();
6006       dbgs() << ", Looking at ";
6007       Inst->dump();
6008     });
6009 
6010     // Now find the sequence of instructions between PrevInst and Inst.
6011     unsigned NumCalls = 0;
6012     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6013                                  PrevInstIt =
6014                                      PrevInst->getIterator().getReverse();
6015     while (InstIt != PrevInstIt) {
6016       if (PrevInstIt == PrevInst->getParent()->rend()) {
6017         PrevInstIt = Inst->getParent()->rbegin();
6018         continue;
6019       }
6020 
6021       // Debug information does not impact spill cost.
6022       if ((isa<CallInst>(&*PrevInstIt) &&
6023            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6024           &*PrevInstIt != PrevInst)
6025         NumCalls++;
6026 
6027       ++PrevInstIt;
6028     }
6029 
6030     if (NumCalls) {
6031       SmallVector<Type*, 4> V;
6032       for (auto *II : LiveValues) {
6033         auto *ScalarTy = II->getType();
6034         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6035           ScalarTy = VectorTy->getElementType();
6036         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6037       }
6038       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6039     }
6040 
6041     PrevInst = Inst;
6042   }
6043 
6044   return Cost;
6045 }
6046 
6047 /// Check if two insertelement instructions are from the same buildvector.
6048 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6049                                             InsertElementInst *V) {
6050   // Instructions must be from the same basic blocks.
6051   if (VU->getParent() != V->getParent())
6052     return false;
6053   // Checks if 2 insertelements are from the same buildvector.
6054   if (VU->getType() != V->getType())
6055     return false;
6056   // Multiple used inserts are separate nodes.
6057   if (!VU->hasOneUse() && !V->hasOneUse())
6058     return false;
6059   auto *IE1 = VU;
6060   auto *IE2 = V;
6061   // Go through the vector operand of insertelement instructions trying to find
6062   // either VU as the original vector for IE2 or V as the original vector for
6063   // IE1.
6064   do {
6065     if (IE2 == VU || IE1 == V)
6066       return true;
6067     if (IE1) {
6068       if (IE1 != VU && !IE1->hasOneUse())
6069         IE1 = nullptr;
6070       else
6071         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6072     }
6073     if (IE2) {
6074       if (IE2 != V && !IE2->hasOneUse())
6075         IE2 = nullptr;
6076       else
6077         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6078     }
6079   } while (IE1 || IE2);
6080   return false;
6081 }
6082 
6083 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6084   InstructionCost Cost = 0;
6085   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6086                     << VectorizableTree.size() << ".\n");
6087 
6088   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6089 
6090   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6091     TreeEntry &TE = *VectorizableTree[I];
6092 
6093     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6094     Cost += C;
6095     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6096                       << " for bundle that starts with " << *TE.Scalars[0]
6097                       << ".\n"
6098                       << "SLP: Current total cost = " << Cost << "\n");
6099   }
6100 
6101   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6102   InstructionCost ExtractCost = 0;
6103   SmallVector<unsigned> VF;
6104   SmallVector<SmallVector<int>> ShuffleMask;
6105   SmallVector<Value *> FirstUsers;
6106   SmallVector<APInt> DemandedElts;
6107   for (ExternalUser &EU : ExternalUses) {
6108     // We only add extract cost once for the same scalar.
6109     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6110         !ExtractCostCalculated.insert(EU.Scalar).second)
6111       continue;
6112 
6113     // Uses by ephemeral values are free (because the ephemeral value will be
6114     // removed prior to code generation, and so the extraction will be
6115     // removed as well).
6116     if (EphValues.count(EU.User))
6117       continue;
6118 
6119     // No extract cost for vector "scalar"
6120     if (isa<FixedVectorType>(EU.Scalar->getType()))
6121       continue;
6122 
6123     // Already counted the cost for external uses when tried to adjust the cost
6124     // for extractelements, no need to add it again.
6125     if (isa<ExtractElementInst>(EU.Scalar))
6126       continue;
6127 
6128     // If found user is an insertelement, do not calculate extract cost but try
6129     // to detect it as a final shuffled/identity match.
6130     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6131       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6132         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6133         if (InsertIdx) {
6134           auto *It = find_if(FirstUsers, [VU](Value *V) {
6135             return areTwoInsertFromSameBuildVector(VU,
6136                                                    cast<InsertElementInst>(V));
6137           });
6138           int VecId = -1;
6139           if (It == FirstUsers.end()) {
6140             VF.push_back(FTy->getNumElements());
6141             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6142             // Find the insertvector, vectorized in tree, if any.
6143             Value *Base = VU;
6144             while (isa<InsertElementInst>(Base)) {
6145               // Build the mask for the vectorized insertelement instructions.
6146               if (const TreeEntry *E = getTreeEntry(Base)) {
6147                 VU = cast<InsertElementInst>(Base);
6148                 do {
6149                   int Idx = E->findLaneForValue(Base);
6150                   ShuffleMask.back()[Idx] = Idx;
6151                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6152                 } while (E == getTreeEntry(Base));
6153                 break;
6154               }
6155               Base = cast<InsertElementInst>(Base)->getOperand(0);
6156             }
6157             FirstUsers.push_back(VU);
6158             DemandedElts.push_back(APInt::getZero(VF.back()));
6159             VecId = FirstUsers.size() - 1;
6160           } else {
6161             VecId = std::distance(FirstUsers.begin(), It);
6162           }
6163           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6164           DemandedElts[VecId].setBit(*InsertIdx);
6165           continue;
6166         }
6167       }
6168     }
6169 
6170     // If we plan to rewrite the tree in a smaller type, we will need to sign
6171     // extend the extracted value back to the original type. Here, we account
6172     // for the extract and the added cost of the sign extend if needed.
6173     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6174     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6175     if (MinBWs.count(ScalarRoot)) {
6176       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6177       auto Extend =
6178           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6179       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6180       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6181                                                    VecTy, EU.Lane);
6182     } else {
6183       ExtractCost +=
6184           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6185     }
6186   }
6187 
6188   InstructionCost SpillCost = getSpillCost();
6189   Cost += SpillCost + ExtractCost;
6190   if (FirstUsers.size() == 1) {
6191     int Limit = ShuffleMask.front().size() * 2;
6192     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6193         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6194       InstructionCost C = TTI->getShuffleCost(
6195           TTI::SK_PermuteSingleSrc,
6196           cast<FixedVectorType>(FirstUsers.front()->getType()),
6197           ShuffleMask.front());
6198       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6199                         << " for final shuffle of insertelement external users "
6200                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6201                         << "SLP: Current total cost = " << Cost << "\n");
6202       Cost += C;
6203     }
6204     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6205         cast<FixedVectorType>(FirstUsers.front()->getType()),
6206         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6207     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6208                       << " for insertelements gather.\n"
6209                       << "SLP: Current total cost = " << Cost << "\n");
6210     Cost -= InsertCost;
6211   } else if (FirstUsers.size() >= 2) {
6212     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6213     // Combined masks of the first 2 vectors.
6214     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6215     copy(ShuffleMask.front(), CombinedMask.begin());
6216     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6217     auto *VecTy = FixedVectorType::get(
6218         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6219         MaxVF);
6220     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6221       if (ShuffleMask[1][I] != UndefMaskElem) {
6222         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6223         CombinedDemandedElts.setBit(I);
6224       }
6225     }
6226     InstructionCost C =
6227         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6228     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6229                       << " for final shuffle of vector node and external "
6230                          "insertelement users "
6231                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6232                       << "SLP: Current total cost = " << Cost << "\n");
6233     Cost += C;
6234     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6235         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6236     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6237                       << " for insertelements gather.\n"
6238                       << "SLP: Current total cost = " << Cost << "\n");
6239     Cost -= InsertCost;
6240     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6241       // Other elements - permutation of 2 vectors (the initial one and the
6242       // next Ith incoming vector).
6243       unsigned VF = ShuffleMask[I].size();
6244       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6245         int Mask = ShuffleMask[I][Idx];
6246         if (Mask != UndefMaskElem)
6247           CombinedMask[Idx] = MaxVF + Mask;
6248         else if (CombinedMask[Idx] != UndefMaskElem)
6249           CombinedMask[Idx] = Idx;
6250       }
6251       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6252         if (CombinedMask[Idx] != UndefMaskElem)
6253           CombinedMask[Idx] = Idx;
6254       InstructionCost C =
6255           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6256       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6257                         << " for final shuffle of vector node and external "
6258                            "insertelement users "
6259                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6260                         << "SLP: Current total cost = " << Cost << "\n");
6261       Cost += C;
6262       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6263           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6264           /*Insert*/ true, /*Extract*/ false);
6265       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6266                         << " for insertelements gather.\n"
6267                         << "SLP: Current total cost = " << Cost << "\n");
6268       Cost -= InsertCost;
6269     }
6270   }
6271 
6272 #ifndef NDEBUG
6273   SmallString<256> Str;
6274   {
6275     raw_svector_ostream OS(Str);
6276     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6277        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6278        << "SLP: Total Cost = " << Cost << ".\n";
6279   }
6280   LLVM_DEBUG(dbgs() << Str);
6281   if (ViewSLPTree)
6282     ViewGraph(this, "SLP" + F->getName(), false, Str);
6283 #endif
6284 
6285   return Cost;
6286 }
6287 
6288 Optional<TargetTransformInfo::ShuffleKind>
6289 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6290                                SmallVectorImpl<const TreeEntry *> &Entries) {
6291   // TODO: currently checking only for Scalars in the tree entry, need to count
6292   // reused elements too for better cost estimation.
6293   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6294   Entries.clear();
6295   // Build a lists of values to tree entries.
6296   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6297   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6298     if (EntryPtr.get() == TE)
6299       break;
6300     if (EntryPtr->State != TreeEntry::NeedToGather)
6301       continue;
6302     for (Value *V : EntryPtr->Scalars)
6303       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6304   }
6305   // Find all tree entries used by the gathered values. If no common entries
6306   // found - not a shuffle.
6307   // Here we build a set of tree nodes for each gathered value and trying to
6308   // find the intersection between these sets. If we have at least one common
6309   // tree node for each gathered value - we have just a permutation of the
6310   // single vector. If we have 2 different sets, we're in situation where we
6311   // have a permutation of 2 input vectors.
6312   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6313   DenseMap<Value *, int> UsedValuesEntry;
6314   for (Value *V : TE->Scalars) {
6315     if (isa<UndefValue>(V))
6316       continue;
6317     // Build a list of tree entries where V is used.
6318     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6319     auto It = ValueToTEs.find(V);
6320     if (It != ValueToTEs.end())
6321       VToTEs = It->second;
6322     if (const TreeEntry *VTE = getTreeEntry(V))
6323       VToTEs.insert(VTE);
6324     if (VToTEs.empty())
6325       return None;
6326     if (UsedTEs.empty()) {
6327       // The first iteration, just insert the list of nodes to vector.
6328       UsedTEs.push_back(VToTEs);
6329     } else {
6330       // Need to check if there are any previously used tree nodes which use V.
6331       // If there are no such nodes, consider that we have another one input
6332       // vector.
6333       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6334       unsigned Idx = 0;
6335       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6336         // Do we have a non-empty intersection of previously listed tree entries
6337         // and tree entries using current V?
6338         set_intersect(VToTEs, Set);
6339         if (!VToTEs.empty()) {
6340           // Yes, write the new subset and continue analysis for the next
6341           // scalar.
6342           Set.swap(VToTEs);
6343           break;
6344         }
6345         VToTEs = SavedVToTEs;
6346         ++Idx;
6347       }
6348       // No non-empty intersection found - need to add a second set of possible
6349       // source vectors.
6350       if (Idx == UsedTEs.size()) {
6351         // If the number of input vectors is greater than 2 - not a permutation,
6352         // fallback to the regular gather.
6353         if (UsedTEs.size() == 2)
6354           return None;
6355         UsedTEs.push_back(SavedVToTEs);
6356         Idx = UsedTEs.size() - 1;
6357       }
6358       UsedValuesEntry.try_emplace(V, Idx);
6359     }
6360   }
6361 
6362   unsigned VF = 0;
6363   if (UsedTEs.size() == 1) {
6364     // Try to find the perfect match in another gather node at first.
6365     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6366       return EntryPtr->isSame(TE->Scalars);
6367     });
6368     if (It != UsedTEs.front().end()) {
6369       Entries.push_back(*It);
6370       std::iota(Mask.begin(), Mask.end(), 0);
6371       return TargetTransformInfo::SK_PermuteSingleSrc;
6372     }
6373     // No perfect match, just shuffle, so choose the first tree node.
6374     Entries.push_back(*UsedTEs.front().begin());
6375   } else {
6376     // Try to find nodes with the same vector factor.
6377     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6378     DenseMap<int, const TreeEntry *> VFToTE;
6379     for (const TreeEntry *TE : UsedTEs.front())
6380       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6381     for (const TreeEntry *TE : UsedTEs.back()) {
6382       auto It = VFToTE.find(TE->getVectorFactor());
6383       if (It != VFToTE.end()) {
6384         VF = It->first;
6385         Entries.push_back(It->second);
6386         Entries.push_back(TE);
6387         break;
6388       }
6389     }
6390     // No 2 source vectors with the same vector factor - give up and do regular
6391     // gather.
6392     if (Entries.empty())
6393       return None;
6394   }
6395 
6396   // Build a shuffle mask for better cost estimation and vector emission.
6397   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6398     Value *V = TE->Scalars[I];
6399     if (isa<UndefValue>(V))
6400       continue;
6401     unsigned Idx = UsedValuesEntry.lookup(V);
6402     const TreeEntry *VTE = Entries[Idx];
6403     int FoundLane = VTE->findLaneForValue(V);
6404     Mask[I] = Idx * VF + FoundLane;
6405     // Extra check required by isSingleSourceMaskImpl function (called by
6406     // ShuffleVectorInst::isSingleSourceMask).
6407     if (Mask[I] >= 2 * E)
6408       return None;
6409   }
6410   switch (Entries.size()) {
6411   case 1:
6412     return TargetTransformInfo::SK_PermuteSingleSrc;
6413   case 2:
6414     return TargetTransformInfo::SK_PermuteTwoSrc;
6415   default:
6416     break;
6417   }
6418   return None;
6419 }
6420 
6421 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6422                                        const APInt &ShuffledIndices,
6423                                        bool NeedToShuffle) const {
6424   InstructionCost Cost =
6425       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6426                                     /*Extract*/ false);
6427   if (NeedToShuffle)
6428     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6429   return Cost;
6430 }
6431 
6432 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6433   // Find the type of the operands in VL.
6434   Type *ScalarTy = VL[0]->getType();
6435   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6436     ScalarTy = SI->getValueOperand()->getType();
6437   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6438   bool DuplicateNonConst = false;
6439   // Find the cost of inserting/extracting values from the vector.
6440   // Check if the same elements are inserted several times and count them as
6441   // shuffle candidates.
6442   APInt ShuffledElements = APInt::getZero(VL.size());
6443   DenseSet<Value *> UniqueElements;
6444   // Iterate in reverse order to consider insert elements with the high cost.
6445   for (unsigned I = VL.size(); I > 0; --I) {
6446     unsigned Idx = I - 1;
6447     // No need to shuffle duplicates for constants.
6448     if (isConstant(VL[Idx])) {
6449       ShuffledElements.setBit(Idx);
6450       continue;
6451     }
6452     if (!UniqueElements.insert(VL[Idx]).second) {
6453       DuplicateNonConst = true;
6454       ShuffledElements.setBit(Idx);
6455     }
6456   }
6457   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6458 }
6459 
6460 // Perform operand reordering on the instructions in VL and return the reordered
6461 // operands in Left and Right.
6462 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6463                                              SmallVectorImpl<Value *> &Left,
6464                                              SmallVectorImpl<Value *> &Right,
6465                                              const DataLayout &DL,
6466                                              ScalarEvolution &SE,
6467                                              const BoUpSLP &R) {
6468   if (VL.empty())
6469     return;
6470   VLOperands Ops(VL, DL, SE, R);
6471   // Reorder the operands in place.
6472   Ops.reorder();
6473   Left = Ops.getVL(0);
6474   Right = Ops.getVL(1);
6475 }
6476 
6477 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6478   // Get the basic block this bundle is in. All instructions in the bundle
6479   // should be in this block.
6480   auto *Front = E->getMainOp();
6481   auto *BB = Front->getParent();
6482   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6483     auto *I = cast<Instruction>(V);
6484     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6485   }));
6486 
6487   auto &&FindLastInst = [E, Front]() {
6488     Instruction *LastInst = Front;
6489     for (Value *V : E->Scalars) {
6490       auto *I = dyn_cast<Instruction>(V);
6491       if (!I)
6492         continue;
6493       if (LastInst->comesBefore(I))
6494         LastInst = I;
6495     }
6496     return LastInst;
6497   };
6498 
6499   auto &&FindFirstInst = [E, Front]() {
6500     Instruction *FirstInst = Front;
6501     for (Value *V : E->Scalars) {
6502       auto *I = dyn_cast<Instruction>(V);
6503       if (!I)
6504         continue;
6505       if (I->comesBefore(FirstInst))
6506         FirstInst = I;
6507     }
6508     return FirstInst;
6509   };
6510 
6511   // Set the insert point to the beginning of the basic block if the entry
6512   // should not be scheduled.
6513   if (E->State != TreeEntry::NeedToGather &&
6514       doesNotNeedToSchedule(E->Scalars)) {
6515     BasicBlock::iterator InsertPt;
6516     if (all_of(E->Scalars, isUsedOutsideBlock))
6517       InsertPt = FindLastInst()->getIterator();
6518     else
6519       InsertPt = FindFirstInst()->getIterator();
6520     Builder.SetInsertPoint(BB, InsertPt);
6521     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6522     return;
6523   }
6524 
6525   // The last instruction in the bundle in program order.
6526   Instruction *LastInst = nullptr;
6527 
6528   // Find the last instruction. The common case should be that BB has been
6529   // scheduled, and the last instruction is VL.back(). So we start with
6530   // VL.back() and iterate over schedule data until we reach the end of the
6531   // bundle. The end of the bundle is marked by null ScheduleData.
6532   if (BlocksSchedules.count(BB)) {
6533     Value *V = E->isOneOf(E->Scalars.back());
6534     if (doesNotNeedToBeScheduled(V))
6535       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6536     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6537     if (Bundle && Bundle->isPartOfBundle())
6538       for (; Bundle; Bundle = Bundle->NextInBundle)
6539         if (Bundle->OpValue == Bundle->Inst)
6540           LastInst = Bundle->Inst;
6541   }
6542 
6543   // LastInst can still be null at this point if there's either not an entry
6544   // for BB in BlocksSchedules or there's no ScheduleData available for
6545   // VL.back(). This can be the case if buildTree_rec aborts for various
6546   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6547   // size is reached, etc.). ScheduleData is initialized in the scheduling
6548   // "dry-run".
6549   //
6550   // If this happens, we can still find the last instruction by brute force. We
6551   // iterate forwards from Front (inclusive) until we either see all
6552   // instructions in the bundle or reach the end of the block. If Front is the
6553   // last instruction in program order, LastInst will be set to Front, and we
6554   // will visit all the remaining instructions in the block.
6555   //
6556   // One of the reasons we exit early from buildTree_rec is to place an upper
6557   // bound on compile-time. Thus, taking an additional compile-time hit here is
6558   // not ideal. However, this should be exceedingly rare since it requires that
6559   // we both exit early from buildTree_rec and that the bundle be out-of-order
6560   // (causing us to iterate all the way to the end of the block).
6561   if (!LastInst)
6562     LastInst = FindLastInst();
6563   assert(LastInst && "Failed to find last instruction in bundle");
6564 
6565   // Set the insertion point after the last instruction in the bundle. Set the
6566   // debug location to Front.
6567   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6568   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6569 }
6570 
6571 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6572   // List of instructions/lanes from current block and/or the blocks which are
6573   // part of the current loop. These instructions will be inserted at the end to
6574   // make it possible to optimize loops and hoist invariant instructions out of
6575   // the loops body with better chances for success.
6576   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6577   SmallSet<int, 4> PostponedIndices;
6578   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6579   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6580     SmallPtrSet<BasicBlock *, 4> Visited;
6581     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6582       InsertBB = InsertBB->getSinglePredecessor();
6583     return InsertBB && InsertBB == InstBB;
6584   };
6585   for (int I = 0, E = VL.size(); I < E; ++I) {
6586     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6587       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6588            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6589           PostponedIndices.insert(I).second)
6590         PostponedInsts.emplace_back(Inst, I);
6591   }
6592 
6593   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6594     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6595     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6596     if (!InsElt)
6597       return Vec;
6598     GatherShuffleSeq.insert(InsElt);
6599     CSEBlocks.insert(InsElt->getParent());
6600     // Add to our 'need-to-extract' list.
6601     if (TreeEntry *Entry = getTreeEntry(V)) {
6602       // Find which lane we need to extract.
6603       unsigned FoundLane = Entry->findLaneForValue(V);
6604       ExternalUses.emplace_back(V, InsElt, FoundLane);
6605     }
6606     return Vec;
6607   };
6608   Value *Val0 =
6609       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6610   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6611   Value *Vec = PoisonValue::get(VecTy);
6612   SmallVector<int> NonConsts;
6613   // Insert constant values at first.
6614   for (int I = 0, E = VL.size(); I < E; ++I) {
6615     if (PostponedIndices.contains(I))
6616       continue;
6617     if (!isConstant(VL[I])) {
6618       NonConsts.push_back(I);
6619       continue;
6620     }
6621     Vec = CreateInsertElement(Vec, VL[I], I);
6622   }
6623   // Insert non-constant values.
6624   for (int I : NonConsts)
6625     Vec = CreateInsertElement(Vec, VL[I], I);
6626   // Append instructions, which are/may be part of the loop, in the end to make
6627   // it possible to hoist non-loop-based instructions.
6628   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6629     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6630 
6631   return Vec;
6632 }
6633 
6634 namespace {
6635 /// Merges shuffle masks and emits final shuffle instruction, if required.
6636 class ShuffleInstructionBuilder {
6637   IRBuilderBase &Builder;
6638   const unsigned VF = 0;
6639   bool IsFinalized = false;
6640   SmallVector<int, 4> Mask;
6641   /// Holds all of the instructions that we gathered.
6642   SetVector<Instruction *> &GatherShuffleSeq;
6643   /// A list of blocks that we are going to CSE.
6644   SetVector<BasicBlock *> &CSEBlocks;
6645 
6646 public:
6647   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6648                             SetVector<Instruction *> &GatherShuffleSeq,
6649                             SetVector<BasicBlock *> &CSEBlocks)
6650       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6651         CSEBlocks(CSEBlocks) {}
6652 
6653   /// Adds a mask, inverting it before applying.
6654   void addInversedMask(ArrayRef<unsigned> SubMask) {
6655     if (SubMask.empty())
6656       return;
6657     SmallVector<int, 4> NewMask;
6658     inversePermutation(SubMask, NewMask);
6659     addMask(NewMask);
6660   }
6661 
6662   /// Functions adds masks, merging them into  single one.
6663   void addMask(ArrayRef<unsigned> SubMask) {
6664     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6665     addMask(NewMask);
6666   }
6667 
6668   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6669 
6670   Value *finalize(Value *V) {
6671     IsFinalized = true;
6672     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6673     if (VF == ValueVF && Mask.empty())
6674       return V;
6675     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6676     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6677     addMask(NormalizedMask);
6678 
6679     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6680       return V;
6681     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6682     if (auto *I = dyn_cast<Instruction>(Vec)) {
6683       GatherShuffleSeq.insert(I);
6684       CSEBlocks.insert(I->getParent());
6685     }
6686     return Vec;
6687   }
6688 
6689   ~ShuffleInstructionBuilder() {
6690     assert((IsFinalized || Mask.empty()) &&
6691            "Shuffle construction must be finalized.");
6692   }
6693 };
6694 } // namespace
6695 
6696 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6697   const unsigned VF = VL.size();
6698   InstructionsState S = getSameOpcode(VL);
6699   if (S.getOpcode()) {
6700     if (TreeEntry *E = getTreeEntry(S.OpValue))
6701       if (E->isSame(VL)) {
6702         Value *V = vectorizeTree(E);
6703         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6704           if (!E->ReuseShuffleIndices.empty()) {
6705             // Reshuffle to get only unique values.
6706             // If some of the scalars are duplicated in the vectorization tree
6707             // entry, we do not vectorize them but instead generate a mask for
6708             // the reuses. But if there are several users of the same entry,
6709             // they may have different vectorization factors. This is especially
6710             // important for PHI nodes. In this case, we need to adapt the
6711             // resulting instruction for the user vectorization factor and have
6712             // to reshuffle it again to take only unique elements of the vector.
6713             // Without this code the function incorrectly returns reduced vector
6714             // instruction with the same elements, not with the unique ones.
6715 
6716             // block:
6717             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6718             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6719             // ... (use %2)
6720             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6721             // br %block
6722             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6723             SmallSet<int, 4> UsedIdxs;
6724             int Pos = 0;
6725             int Sz = VL.size();
6726             for (int Idx : E->ReuseShuffleIndices) {
6727               if (Idx != Sz && Idx != UndefMaskElem &&
6728                   UsedIdxs.insert(Idx).second)
6729                 UniqueIdxs[Idx] = Pos;
6730               ++Pos;
6731             }
6732             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6733                                             "less than original vector size.");
6734             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6735             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6736           } else {
6737             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6738                    "Expected vectorization factor less "
6739                    "than original vector size.");
6740             SmallVector<int> UniformMask(VF, 0);
6741             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6742             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6743           }
6744           if (auto *I = dyn_cast<Instruction>(V)) {
6745             GatherShuffleSeq.insert(I);
6746             CSEBlocks.insert(I->getParent());
6747           }
6748         }
6749         return V;
6750       }
6751   }
6752 
6753   // Can't vectorize this, so simply build a new vector with each lane
6754   // corresponding to the requested value.
6755   return createBuildVector(VL);
6756 }
6757 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6758   unsigned VF = VL.size();
6759   // Exploit possible reuse of values across lanes.
6760   SmallVector<int> ReuseShuffleIndicies;
6761   SmallVector<Value *> UniqueValues;
6762   if (VL.size() > 2) {
6763     DenseMap<Value *, unsigned> UniquePositions;
6764     unsigned NumValues =
6765         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6766                                     return !isa<UndefValue>(V);
6767                                   }).base());
6768     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6769     int UniqueVals = 0;
6770     for (Value *V : VL.drop_back(VL.size() - VF)) {
6771       if (isa<UndefValue>(V)) {
6772         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6773         continue;
6774       }
6775       if (isConstant(V)) {
6776         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6777         UniqueValues.emplace_back(V);
6778         continue;
6779       }
6780       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6781       ReuseShuffleIndicies.emplace_back(Res.first->second);
6782       if (Res.second) {
6783         UniqueValues.emplace_back(V);
6784         ++UniqueVals;
6785       }
6786     }
6787     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6788       // Emit pure splat vector.
6789       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6790                                   UndefMaskElem);
6791     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6792       ReuseShuffleIndicies.clear();
6793       UniqueValues.clear();
6794       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6795     }
6796     UniqueValues.append(VF - UniqueValues.size(),
6797                         PoisonValue::get(VL[0]->getType()));
6798     VL = UniqueValues;
6799   }
6800 
6801   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6802                                            CSEBlocks);
6803   Value *Vec = gather(VL);
6804   if (!ReuseShuffleIndicies.empty()) {
6805     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6806     Vec = ShuffleBuilder.finalize(Vec);
6807   }
6808   return Vec;
6809 }
6810 
6811 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6812   IRBuilder<>::InsertPointGuard Guard(Builder);
6813 
6814   if (E->VectorizedValue) {
6815     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6816     return E->VectorizedValue;
6817   }
6818 
6819   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6820   unsigned VF = E->getVectorFactor();
6821   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6822                                            CSEBlocks);
6823   if (E->State == TreeEntry::NeedToGather) {
6824     if (E->getMainOp())
6825       setInsertPointAfterBundle(E);
6826     Value *Vec;
6827     SmallVector<int> Mask;
6828     SmallVector<const TreeEntry *> Entries;
6829     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6830         isGatherShuffledEntry(E, Mask, Entries);
6831     if (Shuffle.hasValue()) {
6832       assert((Entries.size() == 1 || Entries.size() == 2) &&
6833              "Expected shuffle of 1 or 2 entries.");
6834       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6835                                         Entries.back()->VectorizedValue, Mask);
6836       if (auto *I = dyn_cast<Instruction>(Vec)) {
6837         GatherShuffleSeq.insert(I);
6838         CSEBlocks.insert(I->getParent());
6839       }
6840     } else {
6841       Vec = gather(E->Scalars);
6842     }
6843     if (NeedToShuffleReuses) {
6844       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6845       Vec = ShuffleBuilder.finalize(Vec);
6846     }
6847     E->VectorizedValue = Vec;
6848     return Vec;
6849   }
6850 
6851   assert((E->State == TreeEntry::Vectorize ||
6852           E->State == TreeEntry::ScatterVectorize) &&
6853          "Unhandled state");
6854   unsigned ShuffleOrOp =
6855       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6856   Instruction *VL0 = E->getMainOp();
6857   Type *ScalarTy = VL0->getType();
6858   if (auto *Store = dyn_cast<StoreInst>(VL0))
6859     ScalarTy = Store->getValueOperand()->getType();
6860   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6861     ScalarTy = IE->getOperand(1)->getType();
6862   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6863   switch (ShuffleOrOp) {
6864     case Instruction::PHI: {
6865       assert(
6866           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6867           "PHI reordering is free.");
6868       auto *PH = cast<PHINode>(VL0);
6869       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6870       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6871       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6872       Value *V = NewPhi;
6873 
6874       // Adjust insertion point once all PHI's have been generated.
6875       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6876       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6877 
6878       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6879       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6880       V = ShuffleBuilder.finalize(V);
6881 
6882       E->VectorizedValue = V;
6883 
6884       // PHINodes may have multiple entries from the same block. We want to
6885       // visit every block once.
6886       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6887 
6888       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6889         ValueList Operands;
6890         BasicBlock *IBB = PH->getIncomingBlock(i);
6891 
6892         if (!VisitedBBs.insert(IBB).second) {
6893           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6894           continue;
6895         }
6896 
6897         Builder.SetInsertPoint(IBB->getTerminator());
6898         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6899         Value *Vec = vectorizeTree(E->getOperand(i));
6900         NewPhi->addIncoming(Vec, IBB);
6901       }
6902 
6903       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6904              "Invalid number of incoming values");
6905       return V;
6906     }
6907 
6908     case Instruction::ExtractElement: {
6909       Value *V = E->getSingleOperand(0);
6910       Builder.SetInsertPoint(VL0);
6911       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6912       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6913       V = ShuffleBuilder.finalize(V);
6914       E->VectorizedValue = V;
6915       return V;
6916     }
6917     case Instruction::ExtractValue: {
6918       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6919       Builder.SetInsertPoint(LI);
6920       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6921       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6922       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6923       Value *NewV = propagateMetadata(V, E->Scalars);
6924       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6925       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6926       NewV = ShuffleBuilder.finalize(NewV);
6927       E->VectorizedValue = NewV;
6928       return NewV;
6929     }
6930     case Instruction::InsertElement: {
6931       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6932       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6933       Value *V = vectorizeTree(E->getOperand(1));
6934 
6935       // Create InsertVector shuffle if necessary
6936       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6937         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6938       }));
6939       const unsigned NumElts =
6940           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6941       const unsigned NumScalars = E->Scalars.size();
6942 
6943       unsigned Offset = *getInsertIndex(VL0);
6944       assert(Offset < NumElts && "Failed to find vector index offset");
6945 
6946       // Create shuffle to resize vector
6947       SmallVector<int> Mask;
6948       if (!E->ReorderIndices.empty()) {
6949         inversePermutation(E->ReorderIndices, Mask);
6950         Mask.append(NumElts - NumScalars, UndefMaskElem);
6951       } else {
6952         Mask.assign(NumElts, UndefMaskElem);
6953         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6954       }
6955       // Create InsertVector shuffle if necessary
6956       bool IsIdentity = true;
6957       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6958       Mask.swap(PrevMask);
6959       for (unsigned I = 0; I < NumScalars; ++I) {
6960         Value *Scalar = E->Scalars[PrevMask[I]];
6961         unsigned InsertIdx = *getInsertIndex(Scalar);
6962         IsIdentity &= InsertIdx - Offset == I;
6963         Mask[InsertIdx - Offset] = I;
6964       }
6965       if (!IsIdentity || NumElts != NumScalars) {
6966         V = Builder.CreateShuffleVector(V, Mask);
6967         if (auto *I = dyn_cast<Instruction>(V)) {
6968           GatherShuffleSeq.insert(I);
6969           CSEBlocks.insert(I->getParent());
6970         }
6971       }
6972 
6973       if ((!IsIdentity || Offset != 0 ||
6974            !isUndefVector(FirstInsert->getOperand(0))) &&
6975           NumElts != NumScalars) {
6976         SmallVector<int> InsertMask(NumElts);
6977         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6978         for (unsigned I = 0; I < NumElts; I++) {
6979           if (Mask[I] != UndefMaskElem)
6980             InsertMask[Offset + I] = NumElts + I;
6981         }
6982 
6983         V = Builder.CreateShuffleVector(
6984             FirstInsert->getOperand(0), V, InsertMask,
6985             cast<Instruction>(E->Scalars.back())->getName());
6986         if (auto *I = dyn_cast<Instruction>(V)) {
6987           GatherShuffleSeq.insert(I);
6988           CSEBlocks.insert(I->getParent());
6989         }
6990       }
6991 
6992       ++NumVectorInstructions;
6993       E->VectorizedValue = V;
6994       return V;
6995     }
6996     case Instruction::ZExt:
6997     case Instruction::SExt:
6998     case Instruction::FPToUI:
6999     case Instruction::FPToSI:
7000     case Instruction::FPExt:
7001     case Instruction::PtrToInt:
7002     case Instruction::IntToPtr:
7003     case Instruction::SIToFP:
7004     case Instruction::UIToFP:
7005     case Instruction::Trunc:
7006     case Instruction::FPTrunc:
7007     case Instruction::BitCast: {
7008       setInsertPointAfterBundle(E);
7009 
7010       Value *InVec = vectorizeTree(E->getOperand(0));
7011 
7012       if (E->VectorizedValue) {
7013         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7014         return E->VectorizedValue;
7015       }
7016 
7017       auto *CI = cast<CastInst>(VL0);
7018       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7019       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7020       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7021       V = ShuffleBuilder.finalize(V);
7022 
7023       E->VectorizedValue = V;
7024       ++NumVectorInstructions;
7025       return V;
7026     }
7027     case Instruction::FCmp:
7028     case Instruction::ICmp: {
7029       setInsertPointAfterBundle(E);
7030 
7031       Value *L = vectorizeTree(E->getOperand(0));
7032       Value *R = vectorizeTree(E->getOperand(1));
7033 
7034       if (E->VectorizedValue) {
7035         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7036         return E->VectorizedValue;
7037       }
7038 
7039       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7040       Value *V = Builder.CreateCmp(P0, L, R);
7041       propagateIRFlags(V, E->Scalars, VL0);
7042       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7043       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7044       V = ShuffleBuilder.finalize(V);
7045 
7046       E->VectorizedValue = V;
7047       ++NumVectorInstructions;
7048       return V;
7049     }
7050     case Instruction::Select: {
7051       setInsertPointAfterBundle(E);
7052 
7053       Value *Cond = vectorizeTree(E->getOperand(0));
7054       Value *True = vectorizeTree(E->getOperand(1));
7055       Value *False = vectorizeTree(E->getOperand(2));
7056 
7057       if (E->VectorizedValue) {
7058         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7059         return E->VectorizedValue;
7060       }
7061 
7062       Value *V = Builder.CreateSelect(Cond, True, False);
7063       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7064       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7065       V = ShuffleBuilder.finalize(V);
7066 
7067       E->VectorizedValue = V;
7068       ++NumVectorInstructions;
7069       return V;
7070     }
7071     case Instruction::FNeg: {
7072       setInsertPointAfterBundle(E);
7073 
7074       Value *Op = vectorizeTree(E->getOperand(0));
7075 
7076       if (E->VectorizedValue) {
7077         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7078         return E->VectorizedValue;
7079       }
7080 
7081       Value *V = Builder.CreateUnOp(
7082           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7083       propagateIRFlags(V, E->Scalars, VL0);
7084       if (auto *I = dyn_cast<Instruction>(V))
7085         V = propagateMetadata(I, E->Scalars);
7086 
7087       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7088       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7089       V = ShuffleBuilder.finalize(V);
7090 
7091       E->VectorizedValue = V;
7092       ++NumVectorInstructions;
7093 
7094       return V;
7095     }
7096     case Instruction::Add:
7097     case Instruction::FAdd:
7098     case Instruction::Sub:
7099     case Instruction::FSub:
7100     case Instruction::Mul:
7101     case Instruction::FMul:
7102     case Instruction::UDiv:
7103     case Instruction::SDiv:
7104     case Instruction::FDiv:
7105     case Instruction::URem:
7106     case Instruction::SRem:
7107     case Instruction::FRem:
7108     case Instruction::Shl:
7109     case Instruction::LShr:
7110     case Instruction::AShr:
7111     case Instruction::And:
7112     case Instruction::Or:
7113     case Instruction::Xor: {
7114       setInsertPointAfterBundle(E);
7115 
7116       Value *LHS = vectorizeTree(E->getOperand(0));
7117       Value *RHS = vectorizeTree(E->getOperand(1));
7118 
7119       if (E->VectorizedValue) {
7120         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7121         return E->VectorizedValue;
7122       }
7123 
7124       Value *V = Builder.CreateBinOp(
7125           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7126           RHS);
7127       propagateIRFlags(V, E->Scalars, VL0);
7128       if (auto *I = dyn_cast<Instruction>(V))
7129         V = propagateMetadata(I, E->Scalars);
7130 
7131       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7132       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7133       V = ShuffleBuilder.finalize(V);
7134 
7135       E->VectorizedValue = V;
7136       ++NumVectorInstructions;
7137 
7138       return V;
7139     }
7140     case Instruction::Load: {
7141       // Loads are inserted at the head of the tree because we don't want to
7142       // sink them all the way down past store instructions.
7143       setInsertPointAfterBundle(E);
7144 
7145       LoadInst *LI = cast<LoadInst>(VL0);
7146       Instruction *NewLI;
7147       unsigned AS = LI->getPointerAddressSpace();
7148       Value *PO = LI->getPointerOperand();
7149       if (E->State == TreeEntry::Vectorize) {
7150         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7151         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7152 
7153         // The pointer operand uses an in-tree scalar so we add the new BitCast
7154         // or LoadInst to ExternalUses list to make sure that an extract will
7155         // be generated in the future.
7156         if (TreeEntry *Entry = getTreeEntry(PO)) {
7157           // Find which lane we need to extract.
7158           unsigned FoundLane = Entry->findLaneForValue(PO);
7159           ExternalUses.emplace_back(
7160               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7161         }
7162       } else {
7163         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7164         Value *VecPtr = vectorizeTree(E->getOperand(0));
7165         // Use the minimum alignment of the gathered loads.
7166         Align CommonAlignment = LI->getAlign();
7167         for (Value *V : E->Scalars)
7168           CommonAlignment =
7169               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7170         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7171       }
7172       Value *V = propagateMetadata(NewLI, E->Scalars);
7173 
7174       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7175       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7176       V = ShuffleBuilder.finalize(V);
7177       E->VectorizedValue = V;
7178       ++NumVectorInstructions;
7179       return V;
7180     }
7181     case Instruction::Store: {
7182       auto *SI = cast<StoreInst>(VL0);
7183       unsigned AS = SI->getPointerAddressSpace();
7184 
7185       setInsertPointAfterBundle(E);
7186 
7187       Value *VecValue = vectorizeTree(E->getOperand(0));
7188       ShuffleBuilder.addMask(E->ReorderIndices);
7189       VecValue = ShuffleBuilder.finalize(VecValue);
7190 
7191       Value *ScalarPtr = SI->getPointerOperand();
7192       Value *VecPtr = Builder.CreateBitCast(
7193           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7194       StoreInst *ST =
7195           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7196 
7197       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7198       // StoreInst to ExternalUses to make sure that an extract will be
7199       // generated in the future.
7200       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7201         // Find which lane we need to extract.
7202         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7203         ExternalUses.push_back(ExternalUser(
7204             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7205             FoundLane));
7206       }
7207 
7208       Value *V = propagateMetadata(ST, E->Scalars);
7209 
7210       E->VectorizedValue = V;
7211       ++NumVectorInstructions;
7212       return V;
7213     }
7214     case Instruction::GetElementPtr: {
7215       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7216       setInsertPointAfterBundle(E);
7217 
7218       Value *Op0 = vectorizeTree(E->getOperand(0));
7219 
7220       SmallVector<Value *> OpVecs;
7221       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7222         Value *OpVec = vectorizeTree(E->getOperand(J));
7223         OpVecs.push_back(OpVec);
7224       }
7225 
7226       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7227       if (Instruction *I = dyn_cast<Instruction>(V))
7228         V = propagateMetadata(I, E->Scalars);
7229 
7230       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7231       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7232       V = ShuffleBuilder.finalize(V);
7233 
7234       E->VectorizedValue = V;
7235       ++NumVectorInstructions;
7236 
7237       return V;
7238     }
7239     case Instruction::Call: {
7240       CallInst *CI = cast<CallInst>(VL0);
7241       setInsertPointAfterBundle(E);
7242 
7243       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7244       if (Function *FI = CI->getCalledFunction())
7245         IID = FI->getIntrinsicID();
7246 
7247       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7248 
7249       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7250       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7251                           VecCallCosts.first <= VecCallCosts.second;
7252 
7253       Value *ScalarArg = nullptr;
7254       std::vector<Value *> OpVecs;
7255       SmallVector<Type *, 2> TysForDecl =
7256           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7257       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7258         ValueList OpVL;
7259         // Some intrinsics have scalar arguments. This argument should not be
7260         // vectorized.
7261         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7262           CallInst *CEI = cast<CallInst>(VL0);
7263           ScalarArg = CEI->getArgOperand(j);
7264           OpVecs.push_back(CEI->getArgOperand(j));
7265           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7266             TysForDecl.push_back(ScalarArg->getType());
7267           continue;
7268         }
7269 
7270         Value *OpVec = vectorizeTree(E->getOperand(j));
7271         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7272         OpVecs.push_back(OpVec);
7273       }
7274 
7275       Function *CF;
7276       if (!UseIntrinsic) {
7277         VFShape Shape =
7278             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7279                                   VecTy->getNumElements())),
7280                          false /*HasGlobalPred*/);
7281         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7282       } else {
7283         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7284       }
7285 
7286       SmallVector<OperandBundleDef, 1> OpBundles;
7287       CI->getOperandBundlesAsDefs(OpBundles);
7288       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7289 
7290       // The scalar argument uses an in-tree scalar so we add the new vectorized
7291       // call to ExternalUses list to make sure that an extract will be
7292       // generated in the future.
7293       if (ScalarArg) {
7294         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7295           // Find which lane we need to extract.
7296           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7297           ExternalUses.push_back(
7298               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7299         }
7300       }
7301 
7302       propagateIRFlags(V, E->Scalars, VL0);
7303       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7304       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7305       V = ShuffleBuilder.finalize(V);
7306 
7307       E->VectorizedValue = V;
7308       ++NumVectorInstructions;
7309       return V;
7310     }
7311     case Instruction::ShuffleVector: {
7312       assert(E->isAltShuffle() &&
7313              ((Instruction::isBinaryOp(E->getOpcode()) &&
7314                Instruction::isBinaryOp(E->getAltOpcode())) ||
7315               (Instruction::isCast(E->getOpcode()) &&
7316                Instruction::isCast(E->getAltOpcode())) ||
7317               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7318              "Invalid Shuffle Vector Operand");
7319 
7320       Value *LHS = nullptr, *RHS = nullptr;
7321       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7322         setInsertPointAfterBundle(E);
7323         LHS = vectorizeTree(E->getOperand(0));
7324         RHS = vectorizeTree(E->getOperand(1));
7325       } else {
7326         setInsertPointAfterBundle(E);
7327         LHS = vectorizeTree(E->getOperand(0));
7328       }
7329 
7330       if (E->VectorizedValue) {
7331         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7332         return E->VectorizedValue;
7333       }
7334 
7335       Value *V0, *V1;
7336       if (Instruction::isBinaryOp(E->getOpcode())) {
7337         V0 = Builder.CreateBinOp(
7338             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7339         V1 = Builder.CreateBinOp(
7340             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7341       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7342         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7343         auto *AltCI = cast<CmpInst>(E->getAltOp());
7344         CmpInst::Predicate AltPred = AltCI->getPredicate();
7345         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7346       } else {
7347         V0 = Builder.CreateCast(
7348             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7349         V1 = Builder.CreateCast(
7350             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7351       }
7352       // Add V0 and V1 to later analysis to try to find and remove matching
7353       // instruction, if any.
7354       for (Value *V : {V0, V1}) {
7355         if (auto *I = dyn_cast<Instruction>(V)) {
7356           GatherShuffleSeq.insert(I);
7357           CSEBlocks.insert(I->getParent());
7358         }
7359       }
7360 
7361       // Create shuffle to take alternate operations from the vector.
7362       // Also, gather up main and alt scalar ops to propagate IR flags to
7363       // each vector operation.
7364       ValueList OpScalars, AltScalars;
7365       SmallVector<int> Mask;
7366       buildShuffleEntryMask(
7367           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7368           [E](Instruction *I) {
7369             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7370             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7371           },
7372           Mask, &OpScalars, &AltScalars);
7373 
7374       propagateIRFlags(V0, OpScalars);
7375       propagateIRFlags(V1, AltScalars);
7376 
7377       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7378       if (auto *I = dyn_cast<Instruction>(V)) {
7379         V = propagateMetadata(I, E->Scalars);
7380         GatherShuffleSeq.insert(I);
7381         CSEBlocks.insert(I->getParent());
7382       }
7383       V = ShuffleBuilder.finalize(V);
7384 
7385       E->VectorizedValue = V;
7386       ++NumVectorInstructions;
7387 
7388       return V;
7389     }
7390     default:
7391     llvm_unreachable("unknown inst");
7392   }
7393   return nullptr;
7394 }
7395 
7396 Value *BoUpSLP::vectorizeTree() {
7397   ExtraValueToDebugLocsMap ExternallyUsedValues;
7398   return vectorizeTree(ExternallyUsedValues);
7399 }
7400 
7401 Value *
7402 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7403   // All blocks must be scheduled before any instructions are inserted.
7404   for (auto &BSIter : BlocksSchedules) {
7405     scheduleBlock(BSIter.second.get());
7406   }
7407 
7408   Builder.SetInsertPoint(&F->getEntryBlock().front());
7409   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7410 
7411   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7412   // vectorized root. InstCombine will then rewrite the entire expression. We
7413   // sign extend the extracted values below.
7414   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7415   if (MinBWs.count(ScalarRoot)) {
7416     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7417       // If current instr is a phi and not the last phi, insert it after the
7418       // last phi node.
7419       if (isa<PHINode>(I))
7420         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7421       else
7422         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7423     }
7424     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7425     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7426     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7427     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7428     VectorizableTree[0]->VectorizedValue = Trunc;
7429   }
7430 
7431   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7432                     << " values .\n");
7433 
7434   // Extract all of the elements with the external uses.
7435   for (const auto &ExternalUse : ExternalUses) {
7436     Value *Scalar = ExternalUse.Scalar;
7437     llvm::User *User = ExternalUse.User;
7438 
7439     // Skip users that we already RAUW. This happens when one instruction
7440     // has multiple uses of the same value.
7441     if (User && !is_contained(Scalar->users(), User))
7442       continue;
7443     TreeEntry *E = getTreeEntry(Scalar);
7444     assert(E && "Invalid scalar");
7445     assert(E->State != TreeEntry::NeedToGather &&
7446            "Extracting from a gather list");
7447 
7448     Value *Vec = E->VectorizedValue;
7449     assert(Vec && "Can't find vectorizable value");
7450 
7451     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7452     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7453       if (Scalar->getType() != Vec->getType()) {
7454         Value *Ex;
7455         // "Reuse" the existing extract to improve final codegen.
7456         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7457           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7458                                             ES->getOperand(1));
7459         } else {
7460           Ex = Builder.CreateExtractElement(Vec, Lane);
7461         }
7462         // If necessary, sign-extend or zero-extend ScalarRoot
7463         // to the larger type.
7464         if (!MinBWs.count(ScalarRoot))
7465           return Ex;
7466         if (MinBWs[ScalarRoot].second)
7467           return Builder.CreateSExt(Ex, Scalar->getType());
7468         return Builder.CreateZExt(Ex, Scalar->getType());
7469       }
7470       assert(isa<FixedVectorType>(Scalar->getType()) &&
7471              isa<InsertElementInst>(Scalar) &&
7472              "In-tree scalar of vector type is not insertelement?");
7473       return Vec;
7474     };
7475     // If User == nullptr, the Scalar is used as extra arg. Generate
7476     // ExtractElement instruction and update the record for this scalar in
7477     // ExternallyUsedValues.
7478     if (!User) {
7479       assert(ExternallyUsedValues.count(Scalar) &&
7480              "Scalar with nullptr as an external user must be registered in "
7481              "ExternallyUsedValues map");
7482       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7483         Builder.SetInsertPoint(VecI->getParent(),
7484                                std::next(VecI->getIterator()));
7485       } else {
7486         Builder.SetInsertPoint(&F->getEntryBlock().front());
7487       }
7488       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7489       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7490       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7491       auto It = ExternallyUsedValues.find(Scalar);
7492       assert(It != ExternallyUsedValues.end() &&
7493              "Externally used scalar is not found in ExternallyUsedValues");
7494       NewInstLocs.append(It->second);
7495       ExternallyUsedValues.erase(Scalar);
7496       // Required to update internally referenced instructions.
7497       Scalar->replaceAllUsesWith(NewInst);
7498       continue;
7499     }
7500 
7501     // Generate extracts for out-of-tree users.
7502     // Find the insertion point for the extractelement lane.
7503     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7504       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7505         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7506           if (PH->getIncomingValue(i) == Scalar) {
7507             Instruction *IncomingTerminator =
7508                 PH->getIncomingBlock(i)->getTerminator();
7509             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7510               Builder.SetInsertPoint(VecI->getParent(),
7511                                      std::next(VecI->getIterator()));
7512             } else {
7513               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7514             }
7515             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7516             CSEBlocks.insert(PH->getIncomingBlock(i));
7517             PH->setOperand(i, NewInst);
7518           }
7519         }
7520       } else {
7521         Builder.SetInsertPoint(cast<Instruction>(User));
7522         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7523         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7524         User->replaceUsesOfWith(Scalar, NewInst);
7525       }
7526     } else {
7527       Builder.SetInsertPoint(&F->getEntryBlock().front());
7528       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7529       CSEBlocks.insert(&F->getEntryBlock());
7530       User->replaceUsesOfWith(Scalar, NewInst);
7531     }
7532 
7533     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7534   }
7535 
7536   // For each vectorized value:
7537   for (auto &TEPtr : VectorizableTree) {
7538     TreeEntry *Entry = TEPtr.get();
7539 
7540     // No need to handle users of gathered values.
7541     if (Entry->State == TreeEntry::NeedToGather)
7542       continue;
7543 
7544     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7545 
7546     // For each lane:
7547     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7548       Value *Scalar = Entry->Scalars[Lane];
7549 
7550 #ifndef NDEBUG
7551       Type *Ty = Scalar->getType();
7552       if (!Ty->isVoidTy()) {
7553         for (User *U : Scalar->users()) {
7554           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7555 
7556           // It is legal to delete users in the ignorelist.
7557           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7558                   (isa_and_nonnull<Instruction>(U) &&
7559                    isDeleted(cast<Instruction>(U)))) &&
7560                  "Deleting out-of-tree value");
7561         }
7562       }
7563 #endif
7564       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7565       eraseInstruction(cast<Instruction>(Scalar));
7566     }
7567   }
7568 
7569   Builder.ClearInsertionPoint();
7570   InstrElementSize.clear();
7571 
7572   return VectorizableTree[0]->VectorizedValue;
7573 }
7574 
7575 void BoUpSLP::optimizeGatherSequence() {
7576   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7577                     << " gather sequences instructions.\n");
7578   // LICM InsertElementInst sequences.
7579   for (Instruction *I : GatherShuffleSeq) {
7580     if (isDeleted(I))
7581       continue;
7582 
7583     // Check if this block is inside a loop.
7584     Loop *L = LI->getLoopFor(I->getParent());
7585     if (!L)
7586       continue;
7587 
7588     // Check if it has a preheader.
7589     BasicBlock *PreHeader = L->getLoopPreheader();
7590     if (!PreHeader)
7591       continue;
7592 
7593     // If the vector or the element that we insert into it are
7594     // instructions that are defined in this basic block then we can't
7595     // hoist this instruction.
7596     if (any_of(I->operands(), [L](Value *V) {
7597           auto *OpI = dyn_cast<Instruction>(V);
7598           return OpI && L->contains(OpI);
7599         }))
7600       continue;
7601 
7602     // We can hoist this instruction. Move it to the pre-header.
7603     I->moveBefore(PreHeader->getTerminator());
7604   }
7605 
7606   // Make a list of all reachable blocks in our CSE queue.
7607   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7608   CSEWorkList.reserve(CSEBlocks.size());
7609   for (BasicBlock *BB : CSEBlocks)
7610     if (DomTreeNode *N = DT->getNode(BB)) {
7611       assert(DT->isReachableFromEntry(N));
7612       CSEWorkList.push_back(N);
7613     }
7614 
7615   // Sort blocks by domination. This ensures we visit a block after all blocks
7616   // dominating it are visited.
7617   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7618     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7619            "Different nodes should have different DFS numbers");
7620     return A->getDFSNumIn() < B->getDFSNumIn();
7621   });
7622 
7623   // Less defined shuffles can be replaced by the more defined copies.
7624   // Between two shuffles one is less defined if it has the same vector operands
7625   // and its mask indeces are the same as in the first one or undefs. E.g.
7626   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7627   // poison, <0, 0, 0, 0>.
7628   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7629                                            SmallVectorImpl<int> &NewMask) {
7630     if (I1->getType() != I2->getType())
7631       return false;
7632     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7633     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7634     if (!SI1 || !SI2)
7635       return I1->isIdenticalTo(I2);
7636     if (SI1->isIdenticalTo(SI2))
7637       return true;
7638     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7639       if (SI1->getOperand(I) != SI2->getOperand(I))
7640         return false;
7641     // Check if the second instruction is more defined than the first one.
7642     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7643     ArrayRef<int> SM1 = SI1->getShuffleMask();
7644     // Count trailing undefs in the mask to check the final number of used
7645     // registers.
7646     unsigned LastUndefsCnt = 0;
7647     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7648       if (SM1[I] == UndefMaskElem)
7649         ++LastUndefsCnt;
7650       else
7651         LastUndefsCnt = 0;
7652       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7653           NewMask[I] != SM1[I])
7654         return false;
7655       if (NewMask[I] == UndefMaskElem)
7656         NewMask[I] = SM1[I];
7657     }
7658     // Check if the last undefs actually change the final number of used vector
7659     // registers.
7660     return SM1.size() - LastUndefsCnt > 1 &&
7661            TTI->getNumberOfParts(SI1->getType()) ==
7662                TTI->getNumberOfParts(
7663                    FixedVectorType::get(SI1->getType()->getElementType(),
7664                                         SM1.size() - LastUndefsCnt));
7665   };
7666   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7667   // instructions. TODO: We can further optimize this scan if we split the
7668   // instructions into different buckets based on the insert lane.
7669   SmallVector<Instruction *, 16> Visited;
7670   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7671     assert(*I &&
7672            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7673            "Worklist not sorted properly!");
7674     BasicBlock *BB = (*I)->getBlock();
7675     // For all instructions in blocks containing gather sequences:
7676     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7677       if (isDeleted(&In))
7678         continue;
7679       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7680           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7681         continue;
7682 
7683       // Check if we can replace this instruction with any of the
7684       // visited instructions.
7685       bool Replaced = false;
7686       for (Instruction *&V : Visited) {
7687         SmallVector<int> NewMask;
7688         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7689             DT->dominates(V->getParent(), In.getParent())) {
7690           In.replaceAllUsesWith(V);
7691           eraseInstruction(&In);
7692           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7693             if (!NewMask.empty())
7694               SI->setShuffleMask(NewMask);
7695           Replaced = true;
7696           break;
7697         }
7698         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7699             GatherShuffleSeq.contains(V) &&
7700             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7701             DT->dominates(In.getParent(), V->getParent())) {
7702           In.moveAfter(V);
7703           V->replaceAllUsesWith(&In);
7704           eraseInstruction(V);
7705           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7706             if (!NewMask.empty())
7707               SI->setShuffleMask(NewMask);
7708           V = &In;
7709           Replaced = true;
7710           break;
7711         }
7712       }
7713       if (!Replaced) {
7714         assert(!is_contained(Visited, &In));
7715         Visited.push_back(&In);
7716       }
7717     }
7718   }
7719   CSEBlocks.clear();
7720   GatherShuffleSeq.clear();
7721 }
7722 
7723 BoUpSLP::ScheduleData *
7724 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7725   ScheduleData *Bundle = nullptr;
7726   ScheduleData *PrevInBundle = nullptr;
7727   for (Value *V : VL) {
7728     if (doesNotNeedToBeScheduled(V))
7729       continue;
7730     ScheduleData *BundleMember = getScheduleData(V);
7731     assert(BundleMember &&
7732            "no ScheduleData for bundle member "
7733            "(maybe not in same basic block)");
7734     assert(BundleMember->isSchedulingEntity() &&
7735            "bundle member already part of other bundle");
7736     if (PrevInBundle) {
7737       PrevInBundle->NextInBundle = BundleMember;
7738     } else {
7739       Bundle = BundleMember;
7740     }
7741 
7742     // Group the instructions to a bundle.
7743     BundleMember->FirstInBundle = Bundle;
7744     PrevInBundle = BundleMember;
7745   }
7746   assert(Bundle && "Failed to find schedule bundle");
7747   return Bundle;
7748 }
7749 
7750 // Groups the instructions to a bundle (which is then a single scheduling entity)
7751 // and schedules instructions until the bundle gets ready.
7752 Optional<BoUpSLP::ScheduleData *>
7753 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7754                                             const InstructionsState &S) {
7755   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7756   // instructions.
7757   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7758       doesNotNeedToSchedule(VL))
7759     return nullptr;
7760 
7761   // Initialize the instruction bundle.
7762   Instruction *OldScheduleEnd = ScheduleEnd;
7763   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7764 
7765   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7766                                                          ScheduleData *Bundle) {
7767     // The scheduling region got new instructions at the lower end (or it is a
7768     // new region for the first bundle). This makes it necessary to
7769     // recalculate all dependencies.
7770     // It is seldom that this needs to be done a second time after adding the
7771     // initial bundle to the region.
7772     if (ScheduleEnd != OldScheduleEnd) {
7773       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7774         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7775       ReSchedule = true;
7776     }
7777     if (Bundle) {
7778       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7779                         << " in block " << BB->getName() << "\n");
7780       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7781     }
7782 
7783     if (ReSchedule) {
7784       resetSchedule();
7785       initialFillReadyList(ReadyInsts);
7786     }
7787 
7788     // Now try to schedule the new bundle or (if no bundle) just calculate
7789     // dependencies. As soon as the bundle is "ready" it means that there are no
7790     // cyclic dependencies and we can schedule it. Note that's important that we
7791     // don't "schedule" the bundle yet (see cancelScheduling).
7792     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7793            !ReadyInsts.empty()) {
7794       ScheduleData *Picked = ReadyInsts.pop_back_val();
7795       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7796              "must be ready to schedule");
7797       schedule(Picked, ReadyInsts);
7798     }
7799   };
7800 
7801   // Make sure that the scheduling region contains all
7802   // instructions of the bundle.
7803   for (Value *V : VL) {
7804     if (doesNotNeedToBeScheduled(V))
7805       continue;
7806     if (!extendSchedulingRegion(V, S)) {
7807       // If the scheduling region got new instructions at the lower end (or it
7808       // is a new region for the first bundle). This makes it necessary to
7809       // recalculate all dependencies.
7810       // Otherwise the compiler may crash trying to incorrectly calculate
7811       // dependencies and emit instruction in the wrong order at the actual
7812       // scheduling.
7813       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7814       return None;
7815     }
7816   }
7817 
7818   bool ReSchedule = false;
7819   for (Value *V : VL) {
7820     if (doesNotNeedToBeScheduled(V))
7821       continue;
7822     ScheduleData *BundleMember = getScheduleData(V);
7823     assert(BundleMember &&
7824            "no ScheduleData for bundle member (maybe not in same basic block)");
7825 
7826     // Make sure we don't leave the pieces of the bundle in the ready list when
7827     // whole bundle might not be ready.
7828     ReadyInsts.remove(BundleMember);
7829 
7830     if (!BundleMember->IsScheduled)
7831       continue;
7832     // A bundle member was scheduled as single instruction before and now
7833     // needs to be scheduled as part of the bundle. We just get rid of the
7834     // existing schedule.
7835     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7836                       << " was already scheduled\n");
7837     ReSchedule = true;
7838   }
7839 
7840   auto *Bundle = buildBundle(VL);
7841   TryScheduleBundleImpl(ReSchedule, Bundle);
7842   if (!Bundle->isReady()) {
7843     cancelScheduling(VL, S.OpValue);
7844     return None;
7845   }
7846   return Bundle;
7847 }
7848 
7849 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7850                                                 Value *OpValue) {
7851   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7852       doesNotNeedToSchedule(VL))
7853     return;
7854 
7855   if (doesNotNeedToBeScheduled(OpValue))
7856     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7857   ScheduleData *Bundle = getScheduleData(OpValue);
7858   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7859   assert(!Bundle->IsScheduled &&
7860          "Can't cancel bundle which is already scheduled");
7861   assert(Bundle->isSchedulingEntity() &&
7862          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7863          "tried to unbundle something which is not a bundle");
7864 
7865   // Remove the bundle from the ready list.
7866   if (Bundle->isReady())
7867     ReadyInsts.remove(Bundle);
7868 
7869   // Un-bundle: make single instructions out of the bundle.
7870   ScheduleData *BundleMember = Bundle;
7871   while (BundleMember) {
7872     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7873     BundleMember->FirstInBundle = BundleMember;
7874     ScheduleData *Next = BundleMember->NextInBundle;
7875     BundleMember->NextInBundle = nullptr;
7876     BundleMember->TE = nullptr;
7877     if (BundleMember->unscheduledDepsInBundle() == 0) {
7878       ReadyInsts.insert(BundleMember);
7879     }
7880     BundleMember = Next;
7881   }
7882 }
7883 
7884 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7885   // Allocate a new ScheduleData for the instruction.
7886   if (ChunkPos >= ChunkSize) {
7887     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7888     ChunkPos = 0;
7889   }
7890   return &(ScheduleDataChunks.back()[ChunkPos++]);
7891 }
7892 
7893 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7894                                                       const InstructionsState &S) {
7895   if (getScheduleData(V, isOneOf(S, V)))
7896     return true;
7897   Instruction *I = dyn_cast<Instruction>(V);
7898   assert(I && "bundle member must be an instruction");
7899   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7900          !doesNotNeedToBeScheduled(I) &&
7901          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7902          "be scheduled");
7903   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7904     ScheduleData *ISD = getScheduleData(I);
7905     if (!ISD)
7906       return false;
7907     assert(isInSchedulingRegion(ISD) &&
7908            "ScheduleData not in scheduling region");
7909     ScheduleData *SD = allocateScheduleDataChunks();
7910     SD->Inst = I;
7911     SD->init(SchedulingRegionID, S.OpValue);
7912     ExtraScheduleDataMap[I][S.OpValue] = SD;
7913     return true;
7914   };
7915   if (CheckScheduleForI(I))
7916     return true;
7917   if (!ScheduleStart) {
7918     // It's the first instruction in the new region.
7919     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7920     ScheduleStart = I;
7921     ScheduleEnd = I->getNextNode();
7922     if (isOneOf(S, I) != I)
7923       CheckScheduleForI(I);
7924     assert(ScheduleEnd && "tried to vectorize a terminator?");
7925     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7926     return true;
7927   }
7928   // Search up and down at the same time, because we don't know if the new
7929   // instruction is above or below the existing scheduling region.
7930   BasicBlock::reverse_iterator UpIter =
7931       ++ScheduleStart->getIterator().getReverse();
7932   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7933   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7934   BasicBlock::iterator LowerEnd = BB->end();
7935   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7936          &*DownIter != I) {
7937     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7938       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7939       return false;
7940     }
7941 
7942     ++UpIter;
7943     ++DownIter;
7944   }
7945   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7946     assert(I->getParent() == ScheduleStart->getParent() &&
7947            "Instruction is in wrong basic block.");
7948     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7949     ScheduleStart = I;
7950     if (isOneOf(S, I) != I)
7951       CheckScheduleForI(I);
7952     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7953                       << "\n");
7954     return true;
7955   }
7956   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7957          "Expected to reach top of the basic block or instruction down the "
7958          "lower end.");
7959   assert(I->getParent() == ScheduleEnd->getParent() &&
7960          "Instruction is in wrong basic block.");
7961   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7962                    nullptr);
7963   ScheduleEnd = I->getNextNode();
7964   if (isOneOf(S, I) != I)
7965     CheckScheduleForI(I);
7966   assert(ScheduleEnd && "tried to vectorize a terminator?");
7967   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7968   return true;
7969 }
7970 
7971 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7972                                                 Instruction *ToI,
7973                                                 ScheduleData *PrevLoadStore,
7974                                                 ScheduleData *NextLoadStore) {
7975   ScheduleData *CurrentLoadStore = PrevLoadStore;
7976   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7977     // No need to allocate data for non-schedulable instructions.
7978     if (doesNotNeedToBeScheduled(I))
7979       continue;
7980     ScheduleData *SD = ScheduleDataMap.lookup(I);
7981     if (!SD) {
7982       SD = allocateScheduleDataChunks();
7983       ScheduleDataMap[I] = SD;
7984       SD->Inst = I;
7985     }
7986     assert(!isInSchedulingRegion(SD) &&
7987            "new ScheduleData already in scheduling region");
7988     SD->init(SchedulingRegionID, I);
7989 
7990     if (I->mayReadOrWriteMemory() &&
7991         (!isa<IntrinsicInst>(I) ||
7992          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7993           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7994               Intrinsic::pseudoprobe))) {
7995       // Update the linked list of memory accessing instructions.
7996       if (CurrentLoadStore) {
7997         CurrentLoadStore->NextLoadStore = SD;
7998       } else {
7999         FirstLoadStoreInRegion = SD;
8000       }
8001       CurrentLoadStore = SD;
8002     }
8003   }
8004   if (NextLoadStore) {
8005     if (CurrentLoadStore)
8006       CurrentLoadStore->NextLoadStore = NextLoadStore;
8007   } else {
8008     LastLoadStoreInRegion = CurrentLoadStore;
8009   }
8010 }
8011 
8012 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8013                                                      bool InsertInReadyList,
8014                                                      BoUpSLP *SLP) {
8015   assert(SD->isSchedulingEntity());
8016 
8017   SmallVector<ScheduleData *, 10> WorkList;
8018   WorkList.push_back(SD);
8019 
8020   while (!WorkList.empty()) {
8021     ScheduleData *SD = WorkList.pop_back_val();
8022     for (ScheduleData *BundleMember = SD; BundleMember;
8023          BundleMember = BundleMember->NextInBundle) {
8024       assert(isInSchedulingRegion(BundleMember));
8025       if (BundleMember->hasValidDependencies())
8026         continue;
8027 
8028       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8029                  << "\n");
8030       BundleMember->Dependencies = 0;
8031       BundleMember->resetUnscheduledDeps();
8032 
8033       // Handle def-use chain dependencies.
8034       if (BundleMember->OpValue != BundleMember->Inst) {
8035         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8036           BundleMember->Dependencies++;
8037           ScheduleData *DestBundle = UseSD->FirstInBundle;
8038           if (!DestBundle->IsScheduled)
8039             BundleMember->incrementUnscheduledDeps(1);
8040           if (!DestBundle->hasValidDependencies())
8041             WorkList.push_back(DestBundle);
8042         }
8043       } else {
8044         for (User *U : BundleMember->Inst->users()) {
8045           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8046             BundleMember->Dependencies++;
8047             ScheduleData *DestBundle = UseSD->FirstInBundle;
8048             if (!DestBundle->IsScheduled)
8049               BundleMember->incrementUnscheduledDeps(1);
8050             if (!DestBundle->hasValidDependencies())
8051               WorkList.push_back(DestBundle);
8052           }
8053         }
8054       }
8055 
8056       // Any instruction which isn't safe to speculate at the begining of the
8057       // block is control dependend on any early exit or non-willreturn call
8058       // which proceeds it.
8059       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8060         for (Instruction *I = BundleMember->Inst->getNextNode();
8061              I != ScheduleEnd; I = I->getNextNode()) {
8062           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8063             continue;
8064 
8065           // Add the dependency
8066           auto *DepDest = getScheduleData(I);
8067           assert(DepDest && "must be in schedule window");
8068           DepDest->ControlDependencies.push_back(BundleMember);
8069           BundleMember->Dependencies++;
8070           ScheduleData *DestBundle = DepDest->FirstInBundle;
8071           if (!DestBundle->IsScheduled)
8072             BundleMember->incrementUnscheduledDeps(1);
8073           if (!DestBundle->hasValidDependencies())
8074             WorkList.push_back(DestBundle);
8075 
8076           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8077             // Everything past here must be control dependent on I.
8078             break;
8079         }
8080       }
8081 
8082       // If we have an inalloc alloca instruction, it needs to be scheduled
8083       // after any preceeding stacksave.
8084       if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>())) {
8085         for (Instruction *I = BundleMember->Inst->getNextNode();
8086              I != ScheduleEnd; I = I->getNextNode()) {
8087           if (match(I, m_Intrinsic<Intrinsic::stacksave>()))
8088             // Any allocas past here must be control dependent on I, and I
8089             // must be memory dependend on BundleMember->Inst.
8090             break;
8091 
8092           if (!isa<AllocaInst>(I))
8093             continue;
8094 
8095           // Add the dependency
8096           auto *DepDest = getScheduleData(I);
8097           assert(DepDest && "must be in schedule window");
8098           DepDest->ControlDependencies.push_back(BundleMember);
8099           BundleMember->Dependencies++;
8100           ScheduleData *DestBundle = DepDest->FirstInBundle;
8101           if (!DestBundle->IsScheduled)
8102             BundleMember->incrementUnscheduledDeps(1);
8103           if (!DestBundle->hasValidDependencies())
8104             WorkList.push_back(DestBundle);
8105         }
8106       }
8107 
8108 
8109       // Handle the memory dependencies (if any).
8110       ScheduleData *DepDest = BundleMember->NextLoadStore;
8111       if (!DepDest)
8112         continue;
8113       Instruction *SrcInst = BundleMember->Inst;
8114       assert(SrcInst->mayReadOrWriteMemory() &&
8115              "NextLoadStore list for non memory effecting bundle?");
8116       MemoryLocation SrcLoc = getLocation(SrcInst);
8117       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8118       unsigned numAliased = 0;
8119       unsigned DistToSrc = 1;
8120 
8121       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8122         assert(isInSchedulingRegion(DepDest));
8123 
8124         // We have two limits to reduce the complexity:
8125         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8126         //    SLP->isAliased (which is the expensive part in this loop).
8127         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8128         //    the whole loop (even if the loop is fast, it's quadratic).
8129         //    It's important for the loop break condition (see below) to
8130         //    check this limit even between two read-only instructions.
8131         if (DistToSrc >= MaxMemDepDistance ||
8132             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8133              (numAliased >= AliasedCheckLimit ||
8134               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8135 
8136           // We increment the counter only if the locations are aliased
8137           // (instead of counting all alias checks). This gives a better
8138           // balance between reduced runtime and accurate dependencies.
8139           numAliased++;
8140 
8141           DepDest->MemoryDependencies.push_back(BundleMember);
8142           BundleMember->Dependencies++;
8143           ScheduleData *DestBundle = DepDest->FirstInBundle;
8144           if (!DestBundle->IsScheduled) {
8145             BundleMember->incrementUnscheduledDeps(1);
8146           }
8147           if (!DestBundle->hasValidDependencies()) {
8148             WorkList.push_back(DestBundle);
8149           }
8150         }
8151 
8152         // Example, explaining the loop break condition: Let's assume our
8153         // starting instruction is i0 and MaxMemDepDistance = 3.
8154         //
8155         //                      +--------v--v--v
8156         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8157         //             +--------^--^--^
8158         //
8159         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8160         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8161         // Previously we already added dependencies from i3 to i6,i7,i8
8162         // (because of MaxMemDepDistance). As we added a dependency from
8163         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8164         // and we can abort this loop at i6.
8165         if (DistToSrc >= 2 * MaxMemDepDistance)
8166           break;
8167         DistToSrc++;
8168       }
8169     }
8170     if (InsertInReadyList && SD->isReady()) {
8171       ReadyInsts.insert(SD);
8172       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8173                         << "\n");
8174     }
8175   }
8176 }
8177 
8178 void BoUpSLP::BlockScheduling::resetSchedule() {
8179   assert(ScheduleStart &&
8180          "tried to reset schedule on block which has not been scheduled");
8181   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8182     doForAllOpcodes(I, [&](ScheduleData *SD) {
8183       assert(isInSchedulingRegion(SD) &&
8184              "ScheduleData not in scheduling region");
8185       SD->IsScheduled = false;
8186       SD->resetUnscheduledDeps();
8187     });
8188   }
8189   ReadyInsts.clear();
8190 }
8191 
8192 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8193   if (!BS->ScheduleStart)
8194     return;
8195 
8196   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8197 
8198   BS->resetSchedule();
8199 
8200   // For the real scheduling we use a more sophisticated ready-list: it is
8201   // sorted by the original instruction location. This lets the final schedule
8202   // be as  close as possible to the original instruction order.
8203   // WARNING: If changing this order causes a correctness issue, that means
8204   // there is some missing dependence edge in the schedule data graph.
8205   struct ScheduleDataCompare {
8206     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8207       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8208     }
8209   };
8210   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8211 
8212   // Ensure that all dependency data is updated and fill the ready-list with
8213   // initial instructions.
8214   int Idx = 0;
8215   int NumToSchedule = 0;
8216   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8217        I = I->getNextNode()) {
8218     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
8219       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8220       (void)SDTE;
8221       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8222               SD->isPartOfBundle() ==
8223                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8224              "scheduler and vectorizer bundle mismatch");
8225       SD->FirstInBundle->SchedulingPriority = Idx++;
8226       if (SD->isSchedulingEntity()) {
8227         BS->calculateDependencies(SD, false, this);
8228         NumToSchedule++;
8229       }
8230     });
8231   }
8232   BS->initialFillReadyList(ReadyInsts);
8233 
8234   Instruction *LastScheduledInst = BS->ScheduleEnd;
8235 
8236   // Do the "real" scheduling.
8237   while (!ReadyInsts.empty()) {
8238     ScheduleData *picked = *ReadyInsts.begin();
8239     ReadyInsts.erase(ReadyInsts.begin());
8240 
8241     // Move the scheduled instruction(s) to their dedicated places, if not
8242     // there yet.
8243     for (ScheduleData *BundleMember = picked; BundleMember;
8244          BundleMember = BundleMember->NextInBundle) {
8245       Instruction *pickedInst = BundleMember->Inst;
8246       if (pickedInst->getNextNode() != LastScheduledInst)
8247         pickedInst->moveBefore(LastScheduledInst);
8248       LastScheduledInst = pickedInst;
8249     }
8250 
8251     BS->schedule(picked, ReadyInsts);
8252     NumToSchedule--;
8253   }
8254   assert(NumToSchedule == 0 && "could not schedule all instructions");
8255 
8256   // Check that we didn't break any of our invariants.
8257 #ifdef EXPENSIVE_CHECKS
8258   BS->verify();
8259 #endif
8260 
8261 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8262   // Check that all schedulable entities got scheduled
8263   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8264     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8265       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8266         assert(SD->IsScheduled && "must be scheduled at this point");
8267       }
8268     });
8269   }
8270 #endif
8271 
8272   // Avoid duplicate scheduling of the block.
8273   BS->ScheduleStart = nullptr;
8274 }
8275 
8276 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8277   // If V is a store, just return the width of the stored value (or value
8278   // truncated just before storing) without traversing the expression tree.
8279   // This is the common case.
8280   if (auto *Store = dyn_cast<StoreInst>(V)) {
8281     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8282       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8283     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8284   }
8285 
8286   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8287     return getVectorElementSize(IEI->getOperand(1));
8288 
8289   auto E = InstrElementSize.find(V);
8290   if (E != InstrElementSize.end())
8291     return E->second;
8292 
8293   // If V is not a store, we can traverse the expression tree to find loads
8294   // that feed it. The type of the loaded value may indicate a more suitable
8295   // width than V's type. We want to base the vector element size on the width
8296   // of memory operations where possible.
8297   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8298   SmallPtrSet<Instruction *, 16> Visited;
8299   if (auto *I = dyn_cast<Instruction>(V)) {
8300     Worklist.emplace_back(I, I->getParent());
8301     Visited.insert(I);
8302   }
8303 
8304   // Traverse the expression tree in bottom-up order looking for loads. If we
8305   // encounter an instruction we don't yet handle, we give up.
8306   auto Width = 0u;
8307   while (!Worklist.empty()) {
8308     Instruction *I;
8309     BasicBlock *Parent;
8310     std::tie(I, Parent) = Worklist.pop_back_val();
8311 
8312     // We should only be looking at scalar instructions here. If the current
8313     // instruction has a vector type, skip.
8314     auto *Ty = I->getType();
8315     if (isa<VectorType>(Ty))
8316       continue;
8317 
8318     // If the current instruction is a load, update MaxWidth to reflect the
8319     // width of the loaded value.
8320     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8321         isa<ExtractValueInst>(I))
8322       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8323 
8324     // Otherwise, we need to visit the operands of the instruction. We only
8325     // handle the interesting cases from buildTree here. If an operand is an
8326     // instruction we haven't yet visited and from the same basic block as the
8327     // user or the use is a PHI node, we add it to the worklist.
8328     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8329              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8330              isa<UnaryOperator>(I)) {
8331       for (Use &U : I->operands())
8332         if (auto *J = dyn_cast<Instruction>(U.get()))
8333           if (Visited.insert(J).second &&
8334               (isa<PHINode>(I) || J->getParent() == Parent))
8335             Worklist.emplace_back(J, J->getParent());
8336     } else {
8337       break;
8338     }
8339   }
8340 
8341   // If we didn't encounter a memory access in the expression tree, or if we
8342   // gave up for some reason, just return the width of V. Otherwise, return the
8343   // maximum width we found.
8344   if (!Width) {
8345     if (auto *CI = dyn_cast<CmpInst>(V))
8346       V = CI->getOperand(0);
8347     Width = DL->getTypeSizeInBits(V->getType());
8348   }
8349 
8350   for (Instruction *I : Visited)
8351     InstrElementSize[I] = Width;
8352 
8353   return Width;
8354 }
8355 
8356 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8357 // smaller type with a truncation. We collect the values that will be demoted
8358 // in ToDemote and additional roots that require investigating in Roots.
8359 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8360                                   SmallVectorImpl<Value *> &ToDemote,
8361                                   SmallVectorImpl<Value *> &Roots) {
8362   // We can always demote constants.
8363   if (isa<Constant>(V)) {
8364     ToDemote.push_back(V);
8365     return true;
8366   }
8367 
8368   // If the value is not an instruction in the expression with only one use, it
8369   // cannot be demoted.
8370   auto *I = dyn_cast<Instruction>(V);
8371   if (!I || !I->hasOneUse() || !Expr.count(I))
8372     return false;
8373 
8374   switch (I->getOpcode()) {
8375 
8376   // We can always demote truncations and extensions. Since truncations can
8377   // seed additional demotion, we save the truncated value.
8378   case Instruction::Trunc:
8379     Roots.push_back(I->getOperand(0));
8380     break;
8381   case Instruction::ZExt:
8382   case Instruction::SExt:
8383     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8384         isa<InsertElementInst>(I->getOperand(0)))
8385       return false;
8386     break;
8387 
8388   // We can demote certain binary operations if we can demote both of their
8389   // operands.
8390   case Instruction::Add:
8391   case Instruction::Sub:
8392   case Instruction::Mul:
8393   case Instruction::And:
8394   case Instruction::Or:
8395   case Instruction::Xor:
8396     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8397         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8398       return false;
8399     break;
8400 
8401   // We can demote selects if we can demote their true and false values.
8402   case Instruction::Select: {
8403     SelectInst *SI = cast<SelectInst>(I);
8404     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8405         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8406       return false;
8407     break;
8408   }
8409 
8410   // We can demote phis if we can demote all their incoming operands. Note that
8411   // we don't need to worry about cycles since we ensure single use above.
8412   case Instruction::PHI: {
8413     PHINode *PN = cast<PHINode>(I);
8414     for (Value *IncValue : PN->incoming_values())
8415       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8416         return false;
8417     break;
8418   }
8419 
8420   // Otherwise, conservatively give up.
8421   default:
8422     return false;
8423   }
8424 
8425   // Record the value that we can demote.
8426   ToDemote.push_back(V);
8427   return true;
8428 }
8429 
8430 void BoUpSLP::computeMinimumValueSizes() {
8431   // If there are no external uses, the expression tree must be rooted by a
8432   // store. We can't demote in-memory values, so there is nothing to do here.
8433   if (ExternalUses.empty())
8434     return;
8435 
8436   // We only attempt to truncate integer expressions.
8437   auto &TreeRoot = VectorizableTree[0]->Scalars;
8438   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8439   if (!TreeRootIT)
8440     return;
8441 
8442   // If the expression is not rooted by a store, these roots should have
8443   // external uses. We will rely on InstCombine to rewrite the expression in
8444   // the narrower type. However, InstCombine only rewrites single-use values.
8445   // This means that if a tree entry other than a root is used externally, it
8446   // must have multiple uses and InstCombine will not rewrite it. The code
8447   // below ensures that only the roots are used externally.
8448   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8449   for (auto &EU : ExternalUses)
8450     if (!Expr.erase(EU.Scalar))
8451       return;
8452   if (!Expr.empty())
8453     return;
8454 
8455   // Collect the scalar values of the vectorizable expression. We will use this
8456   // context to determine which values can be demoted. If we see a truncation,
8457   // we mark it as seeding another demotion.
8458   for (auto &EntryPtr : VectorizableTree)
8459     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8460 
8461   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8462   // have a single external user that is not in the vectorizable tree.
8463   for (auto *Root : TreeRoot)
8464     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8465       return;
8466 
8467   // Conservatively determine if we can actually truncate the roots of the
8468   // expression. Collect the values that can be demoted in ToDemote and
8469   // additional roots that require investigating in Roots.
8470   SmallVector<Value *, 32> ToDemote;
8471   SmallVector<Value *, 4> Roots;
8472   for (auto *Root : TreeRoot)
8473     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8474       return;
8475 
8476   // The maximum bit width required to represent all the values that can be
8477   // demoted without loss of precision. It would be safe to truncate the roots
8478   // of the expression to this width.
8479   auto MaxBitWidth = 8u;
8480 
8481   // We first check if all the bits of the roots are demanded. If they're not,
8482   // we can truncate the roots to this narrower type.
8483   for (auto *Root : TreeRoot) {
8484     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8485     MaxBitWidth = std::max<unsigned>(
8486         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8487   }
8488 
8489   // True if the roots can be zero-extended back to their original type, rather
8490   // than sign-extended. We know that if the leading bits are not demanded, we
8491   // can safely zero-extend. So we initialize IsKnownPositive to True.
8492   bool IsKnownPositive = true;
8493 
8494   // If all the bits of the roots are demanded, we can try a little harder to
8495   // compute a narrower type. This can happen, for example, if the roots are
8496   // getelementptr indices. InstCombine promotes these indices to the pointer
8497   // width. Thus, all their bits are technically demanded even though the
8498   // address computation might be vectorized in a smaller type.
8499   //
8500   // We start by looking at each entry that can be demoted. We compute the
8501   // maximum bit width required to store the scalar by using ValueTracking to
8502   // compute the number of high-order bits we can truncate.
8503   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8504       llvm::all_of(TreeRoot, [](Value *R) {
8505         assert(R->hasOneUse() && "Root should have only one use!");
8506         return isa<GetElementPtrInst>(R->user_back());
8507       })) {
8508     MaxBitWidth = 8u;
8509 
8510     // Determine if the sign bit of all the roots is known to be zero. If not,
8511     // IsKnownPositive is set to False.
8512     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8513       KnownBits Known = computeKnownBits(R, *DL);
8514       return Known.isNonNegative();
8515     });
8516 
8517     // Determine the maximum number of bits required to store the scalar
8518     // values.
8519     for (auto *Scalar : ToDemote) {
8520       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8521       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8522       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8523     }
8524 
8525     // If we can't prove that the sign bit is zero, we must add one to the
8526     // maximum bit width to account for the unknown sign bit. This preserves
8527     // the existing sign bit so we can safely sign-extend the root back to the
8528     // original type. Otherwise, if we know the sign bit is zero, we will
8529     // zero-extend the root instead.
8530     //
8531     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8532     //        one to the maximum bit width will yield a larger-than-necessary
8533     //        type. In general, we need to add an extra bit only if we can't
8534     //        prove that the upper bit of the original type is equal to the
8535     //        upper bit of the proposed smaller type. If these two bits are the
8536     //        same (either zero or one) we know that sign-extending from the
8537     //        smaller type will result in the same value. Here, since we can't
8538     //        yet prove this, we are just making the proposed smaller type
8539     //        larger to ensure correctness.
8540     if (!IsKnownPositive)
8541       ++MaxBitWidth;
8542   }
8543 
8544   // Round MaxBitWidth up to the next power-of-two.
8545   if (!isPowerOf2_64(MaxBitWidth))
8546     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8547 
8548   // If the maximum bit width we compute is less than the with of the roots'
8549   // type, we can proceed with the narrowing. Otherwise, do nothing.
8550   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8551     return;
8552 
8553   // If we can truncate the root, we must collect additional values that might
8554   // be demoted as a result. That is, those seeded by truncations we will
8555   // modify.
8556   while (!Roots.empty())
8557     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8558 
8559   // Finally, map the values we can demote to the maximum bit with we computed.
8560   for (auto *Scalar : ToDemote)
8561     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8562 }
8563 
8564 namespace {
8565 
8566 /// The SLPVectorizer Pass.
8567 struct SLPVectorizer : public FunctionPass {
8568   SLPVectorizerPass Impl;
8569 
8570   /// Pass identification, replacement for typeid
8571   static char ID;
8572 
8573   explicit SLPVectorizer() : FunctionPass(ID) {
8574     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8575   }
8576 
8577   bool doInitialization(Module &M) override { return false; }
8578 
8579   bool runOnFunction(Function &F) override {
8580     if (skipFunction(F))
8581       return false;
8582 
8583     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8584     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8585     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8586     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8587     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8588     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8589     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8590     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8591     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8592     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8593 
8594     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8595   }
8596 
8597   void getAnalysisUsage(AnalysisUsage &AU) const override {
8598     FunctionPass::getAnalysisUsage(AU);
8599     AU.addRequired<AssumptionCacheTracker>();
8600     AU.addRequired<ScalarEvolutionWrapperPass>();
8601     AU.addRequired<AAResultsWrapperPass>();
8602     AU.addRequired<TargetTransformInfoWrapperPass>();
8603     AU.addRequired<LoopInfoWrapperPass>();
8604     AU.addRequired<DominatorTreeWrapperPass>();
8605     AU.addRequired<DemandedBitsWrapperPass>();
8606     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8607     AU.addRequired<InjectTLIMappingsLegacy>();
8608     AU.addPreserved<LoopInfoWrapperPass>();
8609     AU.addPreserved<DominatorTreeWrapperPass>();
8610     AU.addPreserved<AAResultsWrapperPass>();
8611     AU.addPreserved<GlobalsAAWrapperPass>();
8612     AU.setPreservesCFG();
8613   }
8614 };
8615 
8616 } // end anonymous namespace
8617 
8618 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8619   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8620   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8621   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8622   auto *AA = &AM.getResult<AAManager>(F);
8623   auto *LI = &AM.getResult<LoopAnalysis>(F);
8624   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8625   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8626   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8627   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8628 
8629   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8630   if (!Changed)
8631     return PreservedAnalyses::all();
8632 
8633   PreservedAnalyses PA;
8634   PA.preserveSet<CFGAnalyses>();
8635   return PA;
8636 }
8637 
8638 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8639                                 TargetTransformInfo *TTI_,
8640                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8641                                 LoopInfo *LI_, DominatorTree *DT_,
8642                                 AssumptionCache *AC_, DemandedBits *DB_,
8643                                 OptimizationRemarkEmitter *ORE_) {
8644   if (!RunSLPVectorization)
8645     return false;
8646   SE = SE_;
8647   TTI = TTI_;
8648   TLI = TLI_;
8649   AA = AA_;
8650   LI = LI_;
8651   DT = DT_;
8652   AC = AC_;
8653   DB = DB_;
8654   DL = &F.getParent()->getDataLayout();
8655 
8656   Stores.clear();
8657   GEPs.clear();
8658   bool Changed = false;
8659 
8660   // If the target claims to have no vector registers don't attempt
8661   // vectorization.
8662   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8663     LLVM_DEBUG(
8664         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8665     return false;
8666   }
8667 
8668   // Don't vectorize when the attribute NoImplicitFloat is used.
8669   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8670     return false;
8671 
8672   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8673 
8674   // Use the bottom up slp vectorizer to construct chains that start with
8675   // store instructions.
8676   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8677 
8678   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8679   // delete instructions.
8680 
8681   // Update DFS numbers now so that we can use them for ordering.
8682   DT->updateDFSNumbers();
8683 
8684   // Scan the blocks in the function in post order.
8685   for (auto BB : post_order(&F.getEntryBlock())) {
8686     collectSeedInstructions(BB);
8687 
8688     // Vectorize trees that end at stores.
8689     if (!Stores.empty()) {
8690       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8691                         << " underlying objects.\n");
8692       Changed |= vectorizeStoreChains(R);
8693     }
8694 
8695     // Vectorize trees that end at reductions.
8696     Changed |= vectorizeChainsInBlock(BB, R);
8697 
8698     // Vectorize the index computations of getelementptr instructions. This
8699     // is primarily intended to catch gather-like idioms ending at
8700     // non-consecutive loads.
8701     if (!GEPs.empty()) {
8702       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8703                         << " underlying objects.\n");
8704       Changed |= vectorizeGEPIndices(BB, R);
8705     }
8706   }
8707 
8708   if (Changed) {
8709     R.optimizeGatherSequence();
8710     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8711   }
8712   return Changed;
8713 }
8714 
8715 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8716                                             unsigned Idx) {
8717   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8718                     << "\n");
8719   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8720   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8721   unsigned VF = Chain.size();
8722 
8723   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8724     return false;
8725 
8726   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8727                     << "\n");
8728 
8729   R.buildTree(Chain);
8730   if (R.isTreeTinyAndNotFullyVectorizable())
8731     return false;
8732   if (R.isLoadCombineCandidate())
8733     return false;
8734   R.reorderTopToBottom();
8735   R.reorderBottomToTop();
8736   R.buildExternalUses();
8737 
8738   R.computeMinimumValueSizes();
8739 
8740   InstructionCost Cost = R.getTreeCost();
8741 
8742   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8743   if (Cost < -SLPCostThreshold) {
8744     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8745 
8746     using namespace ore;
8747 
8748     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8749                                         cast<StoreInst>(Chain[0]))
8750                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8751                      << " and with tree size "
8752                      << NV("TreeSize", R.getTreeSize()));
8753 
8754     R.vectorizeTree();
8755     return true;
8756   }
8757 
8758   return false;
8759 }
8760 
8761 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8762                                         BoUpSLP &R) {
8763   // We may run into multiple chains that merge into a single chain. We mark the
8764   // stores that we vectorized so that we don't visit the same store twice.
8765   BoUpSLP::ValueSet VectorizedStores;
8766   bool Changed = false;
8767 
8768   int E = Stores.size();
8769   SmallBitVector Tails(E, false);
8770   int MaxIter = MaxStoreLookup.getValue();
8771   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8772       E, std::make_pair(E, INT_MAX));
8773   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8774   int IterCnt;
8775   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8776                                   &CheckedPairs,
8777                                   &ConsecutiveChain](int K, int Idx) {
8778     if (IterCnt >= MaxIter)
8779       return true;
8780     if (CheckedPairs[Idx].test(K))
8781       return ConsecutiveChain[K].second == 1 &&
8782              ConsecutiveChain[K].first == Idx;
8783     ++IterCnt;
8784     CheckedPairs[Idx].set(K);
8785     CheckedPairs[K].set(Idx);
8786     Optional<int> Diff = getPointersDiff(
8787         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8788         Stores[Idx]->getValueOperand()->getType(),
8789         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8790     if (!Diff || *Diff == 0)
8791       return false;
8792     int Val = *Diff;
8793     if (Val < 0) {
8794       if (ConsecutiveChain[Idx].second > -Val) {
8795         Tails.set(K);
8796         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8797       }
8798       return false;
8799     }
8800     if (ConsecutiveChain[K].second <= Val)
8801       return false;
8802 
8803     Tails.set(Idx);
8804     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8805     return Val == 1;
8806   };
8807   // Do a quadratic search on all of the given stores in reverse order and find
8808   // all of the pairs of stores that follow each other.
8809   for (int Idx = E - 1; Idx >= 0; --Idx) {
8810     // If a store has multiple consecutive store candidates, search according
8811     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8812     // This is because usually pairing with immediate succeeding or preceding
8813     // candidate create the best chance to find slp vectorization opportunity.
8814     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8815     IterCnt = 0;
8816     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8817       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8818           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8819         break;
8820   }
8821 
8822   // Tracks if we tried to vectorize stores starting from the given tail
8823   // already.
8824   SmallBitVector TriedTails(E, false);
8825   // For stores that start but don't end a link in the chain:
8826   for (int Cnt = E; Cnt > 0; --Cnt) {
8827     int I = Cnt - 1;
8828     if (ConsecutiveChain[I].first == E || Tails.test(I))
8829       continue;
8830     // We found a store instr that starts a chain. Now follow the chain and try
8831     // to vectorize it.
8832     BoUpSLP::ValueList Operands;
8833     // Collect the chain into a list.
8834     while (I != E && !VectorizedStores.count(Stores[I])) {
8835       Operands.push_back(Stores[I]);
8836       Tails.set(I);
8837       if (ConsecutiveChain[I].second != 1) {
8838         // Mark the new end in the chain and go back, if required. It might be
8839         // required if the original stores come in reversed order, for example.
8840         if (ConsecutiveChain[I].first != E &&
8841             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8842             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8843           TriedTails.set(I);
8844           Tails.reset(ConsecutiveChain[I].first);
8845           if (Cnt < ConsecutiveChain[I].first + 2)
8846             Cnt = ConsecutiveChain[I].first + 2;
8847         }
8848         break;
8849       }
8850       // Move to the next value in the chain.
8851       I = ConsecutiveChain[I].first;
8852     }
8853     assert(!Operands.empty() && "Expected non-empty list of stores.");
8854 
8855     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8856     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8857     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8858 
8859     unsigned MinVF = R.getMinVF(EltSize);
8860     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8861                               MaxElts);
8862 
8863     // FIXME: Is division-by-2 the correct step? Should we assert that the
8864     // register size is a power-of-2?
8865     unsigned StartIdx = 0;
8866     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8867       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8868         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8869         if (!VectorizedStores.count(Slice.front()) &&
8870             !VectorizedStores.count(Slice.back()) &&
8871             vectorizeStoreChain(Slice, R, Cnt)) {
8872           // Mark the vectorized stores so that we don't vectorize them again.
8873           VectorizedStores.insert(Slice.begin(), Slice.end());
8874           Changed = true;
8875           // If we vectorized initial block, no need to try to vectorize it
8876           // again.
8877           if (Cnt == StartIdx)
8878             StartIdx += Size;
8879           Cnt += Size;
8880           continue;
8881         }
8882         ++Cnt;
8883       }
8884       // Check if the whole array was vectorized already - exit.
8885       if (StartIdx >= Operands.size())
8886         break;
8887     }
8888   }
8889 
8890   return Changed;
8891 }
8892 
8893 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8894   // Initialize the collections. We will make a single pass over the block.
8895   Stores.clear();
8896   GEPs.clear();
8897 
8898   // Visit the store and getelementptr instructions in BB and organize them in
8899   // Stores and GEPs according to the underlying objects of their pointer
8900   // operands.
8901   for (Instruction &I : *BB) {
8902     // Ignore store instructions that are volatile or have a pointer operand
8903     // that doesn't point to a scalar type.
8904     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8905       if (!SI->isSimple())
8906         continue;
8907       if (!isValidElementType(SI->getValueOperand()->getType()))
8908         continue;
8909       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8910     }
8911 
8912     // Ignore getelementptr instructions that have more than one index, a
8913     // constant index, or a pointer operand that doesn't point to a scalar
8914     // type.
8915     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8916       auto Idx = GEP->idx_begin()->get();
8917       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8918         continue;
8919       if (!isValidElementType(Idx->getType()))
8920         continue;
8921       if (GEP->getType()->isVectorTy())
8922         continue;
8923       GEPs[GEP->getPointerOperand()].push_back(GEP);
8924     }
8925   }
8926 }
8927 
8928 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8929   if (!A || !B)
8930     return false;
8931   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8932     return false;
8933   Value *VL[] = {A, B};
8934   return tryToVectorizeList(VL, R);
8935 }
8936 
8937 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8938                                            bool LimitForRegisterSize) {
8939   if (VL.size() < 2)
8940     return false;
8941 
8942   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8943                     << VL.size() << ".\n");
8944 
8945   // Check that all of the parts are instructions of the same type,
8946   // we permit an alternate opcode via InstructionsState.
8947   InstructionsState S = getSameOpcode(VL);
8948   if (!S.getOpcode())
8949     return false;
8950 
8951   Instruction *I0 = cast<Instruction>(S.OpValue);
8952   // Make sure invalid types (including vector type) are rejected before
8953   // determining vectorization factor for scalar instructions.
8954   for (Value *V : VL) {
8955     Type *Ty = V->getType();
8956     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8957       // NOTE: the following will give user internal llvm type name, which may
8958       // not be useful.
8959       R.getORE()->emit([&]() {
8960         std::string type_str;
8961         llvm::raw_string_ostream rso(type_str);
8962         Ty->print(rso);
8963         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8964                << "Cannot SLP vectorize list: type "
8965                << rso.str() + " is unsupported by vectorizer";
8966       });
8967       return false;
8968     }
8969   }
8970 
8971   unsigned Sz = R.getVectorElementSize(I0);
8972   unsigned MinVF = R.getMinVF(Sz);
8973   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8974   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8975   if (MaxVF < 2) {
8976     R.getORE()->emit([&]() {
8977       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8978              << "Cannot SLP vectorize list: vectorization factor "
8979              << "less than 2 is not supported";
8980     });
8981     return false;
8982   }
8983 
8984   bool Changed = false;
8985   bool CandidateFound = false;
8986   InstructionCost MinCost = SLPCostThreshold.getValue();
8987   Type *ScalarTy = VL[0]->getType();
8988   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8989     ScalarTy = IE->getOperand(1)->getType();
8990 
8991   unsigned NextInst = 0, MaxInst = VL.size();
8992   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8993     // No actual vectorization should happen, if number of parts is the same as
8994     // provided vectorization factor (i.e. the scalar type is used for vector
8995     // code during codegen).
8996     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8997     if (TTI->getNumberOfParts(VecTy) == VF)
8998       continue;
8999     for (unsigned I = NextInst; I < MaxInst; ++I) {
9000       unsigned OpsWidth = 0;
9001 
9002       if (I + VF > MaxInst)
9003         OpsWidth = MaxInst - I;
9004       else
9005         OpsWidth = VF;
9006 
9007       if (!isPowerOf2_32(OpsWidth))
9008         continue;
9009 
9010       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9011           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9012         break;
9013 
9014       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9015       // Check that a previous iteration of this loop did not delete the Value.
9016       if (llvm::any_of(Ops, [&R](Value *V) {
9017             auto *I = dyn_cast<Instruction>(V);
9018             return I && R.isDeleted(I);
9019           }))
9020         continue;
9021 
9022       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9023                         << "\n");
9024 
9025       R.buildTree(Ops);
9026       if (R.isTreeTinyAndNotFullyVectorizable())
9027         continue;
9028       R.reorderTopToBottom();
9029       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9030       R.buildExternalUses();
9031 
9032       R.computeMinimumValueSizes();
9033       InstructionCost Cost = R.getTreeCost();
9034       CandidateFound = true;
9035       MinCost = std::min(MinCost, Cost);
9036 
9037       if (Cost < -SLPCostThreshold) {
9038         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9039         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9040                                                     cast<Instruction>(Ops[0]))
9041                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9042                                  << " and with tree size "
9043                                  << ore::NV("TreeSize", R.getTreeSize()));
9044 
9045         R.vectorizeTree();
9046         // Move to the next bundle.
9047         I += VF - 1;
9048         NextInst = I + 1;
9049         Changed = true;
9050       }
9051     }
9052   }
9053 
9054   if (!Changed && CandidateFound) {
9055     R.getORE()->emit([&]() {
9056       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9057              << "List vectorization was possible but not beneficial with cost "
9058              << ore::NV("Cost", MinCost) << " >= "
9059              << ore::NV("Treshold", -SLPCostThreshold);
9060     });
9061   } else if (!Changed) {
9062     R.getORE()->emit([&]() {
9063       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9064              << "Cannot SLP vectorize list: vectorization was impossible"
9065              << " with available vectorization factors";
9066     });
9067   }
9068   return Changed;
9069 }
9070 
9071 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9072   if (!I)
9073     return false;
9074 
9075   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9076     return false;
9077 
9078   Value *P = I->getParent();
9079 
9080   // Vectorize in current basic block only.
9081   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9082   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9083   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9084     return false;
9085 
9086   // Try to vectorize V.
9087   if (tryToVectorizePair(Op0, Op1, R))
9088     return true;
9089 
9090   auto *A = dyn_cast<BinaryOperator>(Op0);
9091   auto *B = dyn_cast<BinaryOperator>(Op1);
9092   // Try to skip B.
9093   if (B && B->hasOneUse()) {
9094     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9095     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9096     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9097       return true;
9098     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9099       return true;
9100   }
9101 
9102   // Try to skip A.
9103   if (A && A->hasOneUse()) {
9104     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9105     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9106     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9107       return true;
9108     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9109       return true;
9110   }
9111   return false;
9112 }
9113 
9114 namespace {
9115 
9116 /// Model horizontal reductions.
9117 ///
9118 /// A horizontal reduction is a tree of reduction instructions that has values
9119 /// that can be put into a vector as its leaves. For example:
9120 ///
9121 /// mul mul mul mul
9122 ///  \  /    \  /
9123 ///   +       +
9124 ///    \     /
9125 ///       +
9126 /// This tree has "mul" as its leaf values and "+" as its reduction
9127 /// instructions. A reduction can feed into a store or a binary operation
9128 /// feeding a phi.
9129 ///    ...
9130 ///    \  /
9131 ///     +
9132 ///     |
9133 ///  phi +=
9134 ///
9135 ///  Or:
9136 ///    ...
9137 ///    \  /
9138 ///     +
9139 ///     |
9140 ///   *p =
9141 ///
9142 class HorizontalReduction {
9143   using ReductionOpsType = SmallVector<Value *, 16>;
9144   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9145   ReductionOpsListType ReductionOps;
9146   SmallVector<Value *, 32> ReducedVals;
9147   // Use map vector to make stable output.
9148   MapVector<Instruction *, Value *> ExtraArgs;
9149   WeakTrackingVH ReductionRoot;
9150   /// The type of reduction operation.
9151   RecurKind RdxKind;
9152 
9153   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9154 
9155   static bool isCmpSelMinMax(Instruction *I) {
9156     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9157            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9158   }
9159 
9160   // And/or are potentially poison-safe logical patterns like:
9161   // select x, y, false
9162   // select x, true, y
9163   static bool isBoolLogicOp(Instruction *I) {
9164     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9165            match(I, m_LogicalOr(m_Value(), m_Value()));
9166   }
9167 
9168   /// Checks if instruction is associative and can be vectorized.
9169   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9170     if (Kind == RecurKind::None)
9171       return false;
9172 
9173     // Integer ops that map to select instructions or intrinsics are fine.
9174     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9175         isBoolLogicOp(I))
9176       return true;
9177 
9178     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9179       // FP min/max are associative except for NaN and -0.0. We do not
9180       // have to rule out -0.0 here because the intrinsic semantics do not
9181       // specify a fixed result for it.
9182       return I->getFastMathFlags().noNaNs();
9183     }
9184 
9185     return I->isAssociative();
9186   }
9187 
9188   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9189     // Poison-safe 'or' takes the form: select X, true, Y
9190     // To make that work with the normal operand processing, we skip the
9191     // true value operand.
9192     // TODO: Change the code and data structures to handle this without a hack.
9193     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9194       return I->getOperand(2);
9195     return I->getOperand(Index);
9196   }
9197 
9198   /// Checks if the ParentStackElem.first should be marked as a reduction
9199   /// operation with an extra argument or as extra argument itself.
9200   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9201                     Value *ExtraArg) {
9202     if (ExtraArgs.count(ParentStackElem.first)) {
9203       ExtraArgs[ParentStackElem.first] = nullptr;
9204       // We ran into something like:
9205       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9206       // The whole ParentStackElem.first should be considered as an extra value
9207       // in this case.
9208       // Do not perform analysis of remaining operands of ParentStackElem.first
9209       // instruction, this whole instruction is an extra argument.
9210       ParentStackElem.second = INVALID_OPERAND_INDEX;
9211     } else {
9212       // We ran into something like:
9213       // ParentStackElem.first += ... + ExtraArg + ...
9214       ExtraArgs[ParentStackElem.first] = ExtraArg;
9215     }
9216   }
9217 
9218   /// Creates reduction operation with the current opcode.
9219   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9220                          Value *RHS, const Twine &Name, bool UseSelect) {
9221     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9222     switch (Kind) {
9223     case RecurKind::Or:
9224       if (UseSelect &&
9225           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9226         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9227       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9228                                  Name);
9229     case RecurKind::And:
9230       if (UseSelect &&
9231           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9232         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9233       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9234                                  Name);
9235     case RecurKind::Add:
9236     case RecurKind::Mul:
9237     case RecurKind::Xor:
9238     case RecurKind::FAdd:
9239     case RecurKind::FMul:
9240       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9241                                  Name);
9242     case RecurKind::FMax:
9243       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9244     case RecurKind::FMin:
9245       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9246     case RecurKind::SMax:
9247       if (UseSelect) {
9248         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9249         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9250       }
9251       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9252     case RecurKind::SMin:
9253       if (UseSelect) {
9254         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9255         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9256       }
9257       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9258     case RecurKind::UMax:
9259       if (UseSelect) {
9260         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9261         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9262       }
9263       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9264     case RecurKind::UMin:
9265       if (UseSelect) {
9266         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9267         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9268       }
9269       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9270     default:
9271       llvm_unreachable("Unknown reduction operation.");
9272     }
9273   }
9274 
9275   /// Creates reduction operation with the current opcode with the IR flags
9276   /// from \p ReductionOps.
9277   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9278                          Value *RHS, const Twine &Name,
9279                          const ReductionOpsListType &ReductionOps) {
9280     bool UseSelect = ReductionOps.size() == 2 ||
9281                      // Logical or/and.
9282                      (ReductionOps.size() == 1 &&
9283                       isa<SelectInst>(ReductionOps.front().front()));
9284     assert((!UseSelect || ReductionOps.size() != 2 ||
9285             isa<SelectInst>(ReductionOps[1][0])) &&
9286            "Expected cmp + select pairs for reduction");
9287     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9288     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9289       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9290         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9291         propagateIRFlags(Op, ReductionOps[1]);
9292         return Op;
9293       }
9294     }
9295     propagateIRFlags(Op, ReductionOps[0]);
9296     return Op;
9297   }
9298 
9299   /// Creates reduction operation with the current opcode with the IR flags
9300   /// from \p I.
9301   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9302                          Value *RHS, const Twine &Name, Instruction *I) {
9303     auto *SelI = dyn_cast<SelectInst>(I);
9304     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9305     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9306       if (auto *Sel = dyn_cast<SelectInst>(Op))
9307         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9308     }
9309     propagateIRFlags(Op, I);
9310     return Op;
9311   }
9312 
9313   static RecurKind getRdxKind(Instruction *I) {
9314     assert(I && "Expected instruction for reduction matching");
9315     if (match(I, m_Add(m_Value(), m_Value())))
9316       return RecurKind::Add;
9317     if (match(I, m_Mul(m_Value(), m_Value())))
9318       return RecurKind::Mul;
9319     if (match(I, m_And(m_Value(), m_Value())) ||
9320         match(I, m_LogicalAnd(m_Value(), m_Value())))
9321       return RecurKind::And;
9322     if (match(I, m_Or(m_Value(), m_Value())) ||
9323         match(I, m_LogicalOr(m_Value(), m_Value())))
9324       return RecurKind::Or;
9325     if (match(I, m_Xor(m_Value(), m_Value())))
9326       return RecurKind::Xor;
9327     if (match(I, m_FAdd(m_Value(), m_Value())))
9328       return RecurKind::FAdd;
9329     if (match(I, m_FMul(m_Value(), m_Value())))
9330       return RecurKind::FMul;
9331 
9332     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9333       return RecurKind::FMax;
9334     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9335       return RecurKind::FMin;
9336 
9337     // This matches either cmp+select or intrinsics. SLP is expected to handle
9338     // either form.
9339     // TODO: If we are canonicalizing to intrinsics, we can remove several
9340     //       special-case paths that deal with selects.
9341     if (match(I, m_SMax(m_Value(), m_Value())))
9342       return RecurKind::SMax;
9343     if (match(I, m_SMin(m_Value(), m_Value())))
9344       return RecurKind::SMin;
9345     if (match(I, m_UMax(m_Value(), m_Value())))
9346       return RecurKind::UMax;
9347     if (match(I, m_UMin(m_Value(), m_Value())))
9348       return RecurKind::UMin;
9349 
9350     if (auto *Select = dyn_cast<SelectInst>(I)) {
9351       // Try harder: look for min/max pattern based on instructions producing
9352       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9353       // During the intermediate stages of SLP, it's very common to have
9354       // pattern like this (since optimizeGatherSequence is run only once
9355       // at the end):
9356       // %1 = extractelement <2 x i32> %a, i32 0
9357       // %2 = extractelement <2 x i32> %a, i32 1
9358       // %cond = icmp sgt i32 %1, %2
9359       // %3 = extractelement <2 x i32> %a, i32 0
9360       // %4 = extractelement <2 x i32> %a, i32 1
9361       // %select = select i1 %cond, i32 %3, i32 %4
9362       CmpInst::Predicate Pred;
9363       Instruction *L1;
9364       Instruction *L2;
9365 
9366       Value *LHS = Select->getTrueValue();
9367       Value *RHS = Select->getFalseValue();
9368       Value *Cond = Select->getCondition();
9369 
9370       // TODO: Support inverse predicates.
9371       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9372         if (!isa<ExtractElementInst>(RHS) ||
9373             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9374           return RecurKind::None;
9375       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9376         if (!isa<ExtractElementInst>(LHS) ||
9377             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9378           return RecurKind::None;
9379       } else {
9380         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9381           return RecurKind::None;
9382         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9383             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9384             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9385           return RecurKind::None;
9386       }
9387 
9388       switch (Pred) {
9389       default:
9390         return RecurKind::None;
9391       case CmpInst::ICMP_SGT:
9392       case CmpInst::ICMP_SGE:
9393         return RecurKind::SMax;
9394       case CmpInst::ICMP_SLT:
9395       case CmpInst::ICMP_SLE:
9396         return RecurKind::SMin;
9397       case CmpInst::ICMP_UGT:
9398       case CmpInst::ICMP_UGE:
9399         return RecurKind::UMax;
9400       case CmpInst::ICMP_ULT:
9401       case CmpInst::ICMP_ULE:
9402         return RecurKind::UMin;
9403       }
9404     }
9405     return RecurKind::None;
9406   }
9407 
9408   /// Get the index of the first operand.
9409   static unsigned getFirstOperandIndex(Instruction *I) {
9410     return isCmpSelMinMax(I) ? 1 : 0;
9411   }
9412 
9413   /// Total number of operands in the reduction operation.
9414   static unsigned getNumberOfOperands(Instruction *I) {
9415     return isCmpSelMinMax(I) ? 3 : 2;
9416   }
9417 
9418   /// Checks if the instruction is in basic block \p BB.
9419   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9420   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9421     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9422       auto *Sel = cast<SelectInst>(I);
9423       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9424       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9425     }
9426     return I->getParent() == BB;
9427   }
9428 
9429   /// Expected number of uses for reduction operations/reduced values.
9430   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9431     if (IsCmpSelMinMax) {
9432       // SelectInst must be used twice while the condition op must have single
9433       // use only.
9434       if (auto *Sel = dyn_cast<SelectInst>(I))
9435         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9436       return I->hasNUses(2);
9437     }
9438 
9439     // Arithmetic reduction operation must be used once only.
9440     return I->hasOneUse();
9441   }
9442 
9443   /// Initializes the list of reduction operations.
9444   void initReductionOps(Instruction *I) {
9445     if (isCmpSelMinMax(I))
9446       ReductionOps.assign(2, ReductionOpsType());
9447     else
9448       ReductionOps.assign(1, ReductionOpsType());
9449   }
9450 
9451   /// Add all reduction operations for the reduction instruction \p I.
9452   void addReductionOps(Instruction *I) {
9453     if (isCmpSelMinMax(I)) {
9454       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9455       ReductionOps[1].emplace_back(I);
9456     } else {
9457       ReductionOps[0].emplace_back(I);
9458     }
9459   }
9460 
9461   static Value *getLHS(RecurKind Kind, Instruction *I) {
9462     if (Kind == RecurKind::None)
9463       return nullptr;
9464     return I->getOperand(getFirstOperandIndex(I));
9465   }
9466   static Value *getRHS(RecurKind Kind, Instruction *I) {
9467     if (Kind == RecurKind::None)
9468       return nullptr;
9469     return I->getOperand(getFirstOperandIndex(I) + 1);
9470   }
9471 
9472 public:
9473   HorizontalReduction() = default;
9474 
9475   /// Try to find a reduction tree.
9476   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9477     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9478            "Phi needs to use the binary operator");
9479     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9480             isa<IntrinsicInst>(Inst)) &&
9481            "Expected binop, select, or intrinsic for reduction matching");
9482     RdxKind = getRdxKind(Inst);
9483 
9484     // We could have a initial reductions that is not an add.
9485     //  r *= v1 + v2 + v3 + v4
9486     // In such a case start looking for a tree rooted in the first '+'.
9487     if (Phi) {
9488       if (getLHS(RdxKind, Inst) == Phi) {
9489         Phi = nullptr;
9490         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9491         if (!Inst)
9492           return false;
9493         RdxKind = getRdxKind(Inst);
9494       } else if (getRHS(RdxKind, Inst) == Phi) {
9495         Phi = nullptr;
9496         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9497         if (!Inst)
9498           return false;
9499         RdxKind = getRdxKind(Inst);
9500       }
9501     }
9502 
9503     if (!isVectorizable(RdxKind, Inst))
9504       return false;
9505 
9506     // Analyze "regular" integer/FP types for reductions - no target-specific
9507     // types or pointers.
9508     Type *Ty = Inst->getType();
9509     if (!isValidElementType(Ty) || Ty->isPointerTy())
9510       return false;
9511 
9512     // Though the ultimate reduction may have multiple uses, its condition must
9513     // have only single use.
9514     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9515       if (!Sel->getCondition()->hasOneUse())
9516         return false;
9517 
9518     ReductionRoot = Inst;
9519 
9520     // The opcode for leaf values that we perform a reduction on.
9521     // For example: load(x) + load(y) + load(z) + fptoui(w)
9522     // The leaf opcode for 'w' does not match, so we don't include it as a
9523     // potential candidate for the reduction.
9524     unsigned LeafOpcode = 0;
9525 
9526     // Post-order traverse the reduction tree starting at Inst. We only handle
9527     // true trees containing binary operators or selects.
9528     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9529     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9530     initReductionOps(Inst);
9531     while (!Stack.empty()) {
9532       Instruction *TreeN = Stack.back().first;
9533       unsigned EdgeToVisit = Stack.back().second++;
9534       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9535       bool IsReducedValue = TreeRdxKind != RdxKind;
9536 
9537       // Postorder visit.
9538       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9539         if (IsReducedValue)
9540           ReducedVals.push_back(TreeN);
9541         else {
9542           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9543           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9544             // Check if TreeN is an extra argument of its parent operation.
9545             if (Stack.size() <= 1) {
9546               // TreeN can't be an extra argument as it is a root reduction
9547               // operation.
9548               return false;
9549             }
9550             // Yes, TreeN is an extra argument, do not add it to a list of
9551             // reduction operations.
9552             // Stack[Stack.size() - 2] always points to the parent operation.
9553             markExtraArg(Stack[Stack.size() - 2], TreeN);
9554             ExtraArgs.erase(TreeN);
9555           } else
9556             addReductionOps(TreeN);
9557         }
9558         // Retract.
9559         Stack.pop_back();
9560         continue;
9561       }
9562 
9563       // Visit operands.
9564       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9565       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9566       if (!EdgeInst) {
9567         // Edge value is not a reduction instruction or a leaf instruction.
9568         // (It may be a constant, function argument, or something else.)
9569         markExtraArg(Stack.back(), EdgeVal);
9570         continue;
9571       }
9572       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9573       // Continue analysis if the next operand is a reduction operation or
9574       // (possibly) a leaf value. If the leaf value opcode is not set,
9575       // the first met operation != reduction operation is considered as the
9576       // leaf opcode.
9577       // Only handle trees in the current basic block.
9578       // Each tree node needs to have minimal number of users except for the
9579       // ultimate reduction.
9580       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9581       if (EdgeInst != Phi && EdgeInst != Inst &&
9582           hasSameParent(EdgeInst, Inst->getParent()) &&
9583           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9584           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9585         if (IsRdxInst) {
9586           // We need to be able to reassociate the reduction operations.
9587           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9588             // I is an extra argument for TreeN (its parent operation).
9589             markExtraArg(Stack.back(), EdgeInst);
9590             continue;
9591           }
9592         } else if (!LeafOpcode) {
9593           LeafOpcode = EdgeInst->getOpcode();
9594         }
9595         Stack.push_back(
9596             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9597         continue;
9598       }
9599       // I is an extra argument for TreeN (its parent operation).
9600       markExtraArg(Stack.back(), EdgeInst);
9601     }
9602     return true;
9603   }
9604 
9605   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9606   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9607     // If there are a sufficient number of reduction values, reduce
9608     // to a nearby power-of-2. We can safely generate oversized
9609     // vectors and rely on the backend to split them to legal sizes.
9610     unsigned NumReducedVals = ReducedVals.size();
9611     if (NumReducedVals < 4)
9612       return nullptr;
9613 
9614     // Intersect the fast-math-flags from all reduction operations.
9615     FastMathFlags RdxFMF;
9616     RdxFMF.set();
9617     for (ReductionOpsType &RdxOp : ReductionOps) {
9618       for (Value *RdxVal : RdxOp) {
9619         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9620           RdxFMF &= FPMO->getFastMathFlags();
9621       }
9622     }
9623 
9624     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9625     Builder.setFastMathFlags(RdxFMF);
9626 
9627     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9628     // The same extra argument may be used several times, so log each attempt
9629     // to use it.
9630     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9631       assert(Pair.first && "DebugLoc must be set.");
9632       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9633     }
9634 
9635     // The compare instruction of a min/max is the insertion point for new
9636     // instructions and may be replaced with a new compare instruction.
9637     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9638       assert(isa<SelectInst>(RdxRootInst) &&
9639              "Expected min/max reduction to have select root instruction");
9640       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9641       assert(isa<Instruction>(ScalarCond) &&
9642              "Expected min/max reduction to have compare condition");
9643       return cast<Instruction>(ScalarCond);
9644     };
9645 
9646     // The reduction root is used as the insertion point for new instructions,
9647     // so set it as externally used to prevent it from being deleted.
9648     ExternallyUsedValues[ReductionRoot];
9649     SmallVector<Value *, 16> IgnoreList;
9650     for (ReductionOpsType &RdxOp : ReductionOps)
9651       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9652 
9653     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9654     if (NumReducedVals > ReduxWidth) {
9655       // In the loop below, we are building a tree based on a window of
9656       // 'ReduxWidth' values.
9657       // If the operands of those values have common traits (compare predicate,
9658       // constant operand, etc), then we want to group those together to
9659       // minimize the cost of the reduction.
9660 
9661       // TODO: This should be extended to count common operands for
9662       //       compares and binops.
9663 
9664       // Step 1: Count the number of times each compare predicate occurs.
9665       SmallDenseMap<unsigned, unsigned> PredCountMap;
9666       for (Value *RdxVal : ReducedVals) {
9667         CmpInst::Predicate Pred;
9668         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9669           ++PredCountMap[Pred];
9670       }
9671       // Step 2: Sort the values so the most common predicates come first.
9672       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9673         CmpInst::Predicate PredA, PredB;
9674         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9675             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9676           return PredCountMap[PredA] > PredCountMap[PredB];
9677         }
9678         return false;
9679       });
9680     }
9681 
9682     Value *VectorizedTree = nullptr;
9683     unsigned i = 0;
9684     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9685       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9686       V.buildTree(VL, IgnoreList);
9687       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9688         break;
9689       if (V.isLoadCombineReductionCandidate(RdxKind))
9690         break;
9691       V.reorderTopToBottom();
9692       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9693       V.buildExternalUses(ExternallyUsedValues);
9694 
9695       // For a poison-safe boolean logic reduction, do not replace select
9696       // instructions with logic ops. All reduced values will be frozen (see
9697       // below) to prevent leaking poison.
9698       if (isa<SelectInst>(ReductionRoot) &&
9699           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9700           NumReducedVals != ReduxWidth)
9701         break;
9702 
9703       V.computeMinimumValueSizes();
9704 
9705       // Estimate cost.
9706       InstructionCost TreeCost =
9707           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9708       InstructionCost ReductionCost =
9709           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9710       InstructionCost Cost = TreeCost + ReductionCost;
9711       if (!Cost.isValid()) {
9712         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9713         return nullptr;
9714       }
9715       if (Cost >= -SLPCostThreshold) {
9716         V.getORE()->emit([&]() {
9717           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9718                                           cast<Instruction>(VL[0]))
9719                  << "Vectorizing horizontal reduction is possible"
9720                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9721                  << " and threshold "
9722                  << ore::NV("Threshold", -SLPCostThreshold);
9723         });
9724         break;
9725       }
9726 
9727       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9728                         << Cost << ". (HorRdx)\n");
9729       V.getORE()->emit([&]() {
9730         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9731                                   cast<Instruction>(VL[0]))
9732                << "Vectorized horizontal reduction with cost "
9733                << ore::NV("Cost", Cost) << " and with tree size "
9734                << ore::NV("TreeSize", V.getTreeSize());
9735       });
9736 
9737       // Vectorize a tree.
9738       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9739       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9740 
9741       // Emit a reduction. If the root is a select (min/max idiom), the insert
9742       // point is the compare condition of that select.
9743       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9744       if (isCmpSelMinMax(RdxRootInst))
9745         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9746       else
9747         Builder.SetInsertPoint(RdxRootInst);
9748 
9749       // To prevent poison from leaking across what used to be sequential, safe,
9750       // scalar boolean logic operations, the reduction operand must be frozen.
9751       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9752         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9753 
9754       Value *ReducedSubTree =
9755           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9756 
9757       if (!VectorizedTree) {
9758         // Initialize the final value in the reduction.
9759         VectorizedTree = ReducedSubTree;
9760       } else {
9761         // Update the final value in the reduction.
9762         Builder.SetCurrentDebugLocation(Loc);
9763         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9764                                   ReducedSubTree, "op.rdx", ReductionOps);
9765       }
9766       i += ReduxWidth;
9767       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9768     }
9769 
9770     if (VectorizedTree) {
9771       // Finish the reduction.
9772       for (; i < NumReducedVals; ++i) {
9773         auto *I = cast<Instruction>(ReducedVals[i]);
9774         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9775         VectorizedTree =
9776             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9777       }
9778       for (auto &Pair : ExternallyUsedValues) {
9779         // Add each externally used value to the final reduction.
9780         for (auto *I : Pair.second) {
9781           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9782           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9783                                     Pair.first, "op.extra", I);
9784         }
9785       }
9786 
9787       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9788 
9789       // Mark all scalar reduction ops for deletion, they are replaced by the
9790       // vector reductions.
9791       V.eraseInstructions(IgnoreList);
9792     }
9793     return VectorizedTree;
9794   }
9795 
9796   unsigned numReductionValues() const { return ReducedVals.size(); }
9797 
9798 private:
9799   /// Calculate the cost of a reduction.
9800   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9801                                    Value *FirstReducedVal, unsigned ReduxWidth,
9802                                    FastMathFlags FMF) {
9803     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9804     Type *ScalarTy = FirstReducedVal->getType();
9805     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9806     InstructionCost VectorCost, ScalarCost;
9807     switch (RdxKind) {
9808     case RecurKind::Add:
9809     case RecurKind::Mul:
9810     case RecurKind::Or:
9811     case RecurKind::And:
9812     case RecurKind::Xor:
9813     case RecurKind::FAdd:
9814     case RecurKind::FMul: {
9815       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9816       VectorCost =
9817           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9818       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9819       break;
9820     }
9821     case RecurKind::FMax:
9822     case RecurKind::FMin: {
9823       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9824       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9825       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9826                                                /*IsUnsigned=*/false, CostKind);
9827       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9828       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9829                                            SclCondTy, RdxPred, CostKind) +
9830                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9831                                            SclCondTy, RdxPred, CostKind);
9832       break;
9833     }
9834     case RecurKind::SMax:
9835     case RecurKind::SMin:
9836     case RecurKind::UMax:
9837     case RecurKind::UMin: {
9838       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9839       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9840       bool IsUnsigned =
9841           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9842       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9843                                                CostKind);
9844       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9845       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9846                                            SclCondTy, RdxPred, CostKind) +
9847                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9848                                            SclCondTy, RdxPred, CostKind);
9849       break;
9850     }
9851     default:
9852       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9853     }
9854 
9855     // Scalar cost is repeated for N-1 elements.
9856     ScalarCost *= (ReduxWidth - 1);
9857     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9858                       << " for reduction that starts with " << *FirstReducedVal
9859                       << " (It is a splitting reduction)\n");
9860     return VectorCost - ScalarCost;
9861   }
9862 
9863   /// Emit a horizontal reduction of the vectorized value.
9864   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9865                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9866     assert(VectorizedValue && "Need to have a vectorized tree node");
9867     assert(isPowerOf2_32(ReduxWidth) &&
9868            "We only handle power-of-two reductions for now");
9869     assert(RdxKind != RecurKind::FMulAdd &&
9870            "A call to the llvm.fmuladd intrinsic is not handled yet");
9871 
9872     ++NumVectorInstructions;
9873     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9874   }
9875 };
9876 
9877 } // end anonymous namespace
9878 
9879 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9880   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9881     return cast<FixedVectorType>(IE->getType())->getNumElements();
9882 
9883   unsigned AggregateSize = 1;
9884   auto *IV = cast<InsertValueInst>(InsertInst);
9885   Type *CurrentType = IV->getType();
9886   do {
9887     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9888       for (auto *Elt : ST->elements())
9889         if (Elt != ST->getElementType(0)) // check homogeneity
9890           return None;
9891       AggregateSize *= ST->getNumElements();
9892       CurrentType = ST->getElementType(0);
9893     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9894       AggregateSize *= AT->getNumElements();
9895       CurrentType = AT->getElementType();
9896     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9897       AggregateSize *= VT->getNumElements();
9898       return AggregateSize;
9899     } else if (CurrentType->isSingleValueType()) {
9900       return AggregateSize;
9901     } else {
9902       return None;
9903     }
9904   } while (true);
9905 }
9906 
9907 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9908                                    TargetTransformInfo *TTI,
9909                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9910                                    SmallVectorImpl<Value *> &InsertElts,
9911                                    unsigned OperandOffset) {
9912   do {
9913     Value *InsertedOperand = LastInsertInst->getOperand(1);
9914     Optional<unsigned> OperandIndex =
9915         getInsertIndex(LastInsertInst, OperandOffset);
9916     if (!OperandIndex)
9917       return;
9918     if (isa<InsertElementInst>(InsertedOperand) ||
9919         isa<InsertValueInst>(InsertedOperand)) {
9920       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9921                              BuildVectorOpds, InsertElts, *OperandIndex);
9922 
9923     } else {
9924       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9925       InsertElts[*OperandIndex] = LastInsertInst;
9926     }
9927     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9928   } while (LastInsertInst != nullptr &&
9929            (isa<InsertValueInst>(LastInsertInst) ||
9930             isa<InsertElementInst>(LastInsertInst)) &&
9931            LastInsertInst->hasOneUse());
9932 }
9933 
9934 /// Recognize construction of vectors like
9935 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9936 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9937 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9938 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9939 ///  starting from the last insertelement or insertvalue instruction.
9940 ///
9941 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9942 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9943 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9944 ///
9945 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9946 ///
9947 /// \return true if it matches.
9948 static bool findBuildAggregate(Instruction *LastInsertInst,
9949                                TargetTransformInfo *TTI,
9950                                SmallVectorImpl<Value *> &BuildVectorOpds,
9951                                SmallVectorImpl<Value *> &InsertElts) {
9952 
9953   assert((isa<InsertElementInst>(LastInsertInst) ||
9954           isa<InsertValueInst>(LastInsertInst)) &&
9955          "Expected insertelement or insertvalue instruction!");
9956 
9957   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9958          "Expected empty result vectors!");
9959 
9960   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9961   if (!AggregateSize)
9962     return false;
9963   BuildVectorOpds.resize(*AggregateSize);
9964   InsertElts.resize(*AggregateSize);
9965 
9966   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
9967   llvm::erase_value(BuildVectorOpds, nullptr);
9968   llvm::erase_value(InsertElts, nullptr);
9969   if (BuildVectorOpds.size() >= 2)
9970     return true;
9971 
9972   return false;
9973 }
9974 
9975 /// Try and get a reduction value from a phi node.
9976 ///
9977 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9978 /// if they come from either \p ParentBB or a containing loop latch.
9979 ///
9980 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9981 /// if not possible.
9982 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9983                                 BasicBlock *ParentBB, LoopInfo *LI) {
9984   // There are situations where the reduction value is not dominated by the
9985   // reduction phi. Vectorizing such cases has been reported to cause
9986   // miscompiles. See PR25787.
9987   auto DominatedReduxValue = [&](Value *R) {
9988     return isa<Instruction>(R) &&
9989            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9990   };
9991 
9992   Value *Rdx = nullptr;
9993 
9994   // Return the incoming value if it comes from the same BB as the phi node.
9995   if (P->getIncomingBlock(0) == ParentBB) {
9996     Rdx = P->getIncomingValue(0);
9997   } else if (P->getIncomingBlock(1) == ParentBB) {
9998     Rdx = P->getIncomingValue(1);
9999   }
10000 
10001   if (Rdx && DominatedReduxValue(Rdx))
10002     return Rdx;
10003 
10004   // Otherwise, check whether we have a loop latch to look at.
10005   Loop *BBL = LI->getLoopFor(ParentBB);
10006   if (!BBL)
10007     return nullptr;
10008   BasicBlock *BBLatch = BBL->getLoopLatch();
10009   if (!BBLatch)
10010     return nullptr;
10011 
10012   // There is a loop latch, return the incoming value if it comes from
10013   // that. This reduction pattern occasionally turns up.
10014   if (P->getIncomingBlock(0) == BBLatch) {
10015     Rdx = P->getIncomingValue(0);
10016   } else if (P->getIncomingBlock(1) == BBLatch) {
10017     Rdx = P->getIncomingValue(1);
10018   }
10019 
10020   if (Rdx && DominatedReduxValue(Rdx))
10021     return Rdx;
10022 
10023   return nullptr;
10024 }
10025 
10026 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10027   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10028     return true;
10029   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10030     return true;
10031   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10032     return true;
10033   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10034     return true;
10035   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10036     return true;
10037   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10038     return true;
10039   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10040     return true;
10041   return false;
10042 }
10043 
10044 /// Attempt to reduce a horizontal reduction.
10045 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10046 /// with reduction operators \a Root (or one of its operands) in a basic block
10047 /// \a BB, then check if it can be done. If horizontal reduction is not found
10048 /// and root instruction is a binary operation, vectorization of the operands is
10049 /// attempted.
10050 /// \returns true if a horizontal reduction was matched and reduced or operands
10051 /// of one of the binary instruction were vectorized.
10052 /// \returns false if a horizontal reduction was not matched (or not possible)
10053 /// or no vectorization of any binary operation feeding \a Root instruction was
10054 /// performed.
10055 static bool tryToVectorizeHorReductionOrInstOperands(
10056     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10057     TargetTransformInfo *TTI,
10058     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10059   if (!ShouldVectorizeHor)
10060     return false;
10061 
10062   if (!Root)
10063     return false;
10064 
10065   if (Root->getParent() != BB || isa<PHINode>(Root))
10066     return false;
10067   // Start analysis starting from Root instruction. If horizontal reduction is
10068   // found, try to vectorize it. If it is not a horizontal reduction or
10069   // vectorization is not possible or not effective, and currently analyzed
10070   // instruction is a binary operation, try to vectorize the operands, using
10071   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10072   // the same procedure considering each operand as a possible root of the
10073   // horizontal reduction.
10074   // Interrupt the process if the Root instruction itself was vectorized or all
10075   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10076   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10077   // CmpInsts so we can skip extra attempts in
10078   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10079   std::queue<std::pair<Instruction *, unsigned>> Stack;
10080   Stack.emplace(Root, 0);
10081   SmallPtrSet<Value *, 8> VisitedInstrs;
10082   SmallVector<WeakTrackingVH> PostponedInsts;
10083   bool Res = false;
10084   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
10085                                      Value *&B1) -> Value * {
10086     bool IsBinop = matchRdxBop(Inst, B0, B1);
10087     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10088     if (IsBinop || IsSelect) {
10089       HorizontalReduction HorRdx;
10090       if (HorRdx.matchAssociativeReduction(P, Inst))
10091         return HorRdx.tryToReduce(R, TTI);
10092     }
10093     return nullptr;
10094   };
10095   while (!Stack.empty()) {
10096     Instruction *Inst;
10097     unsigned Level;
10098     std::tie(Inst, Level) = Stack.front();
10099     Stack.pop();
10100     // Do not try to analyze instruction that has already been vectorized.
10101     // This may happen when we vectorize instruction operands on a previous
10102     // iteration while stack was populated before that happened.
10103     if (R.isDeleted(Inst))
10104       continue;
10105     Value *B0 = nullptr, *B1 = nullptr;
10106     if (Value *V = TryToReduce(Inst, B0, B1)) {
10107       Res = true;
10108       // Set P to nullptr to avoid re-analysis of phi node in
10109       // matchAssociativeReduction function unless this is the root node.
10110       P = nullptr;
10111       if (auto *I = dyn_cast<Instruction>(V)) {
10112         // Try to find another reduction.
10113         Stack.emplace(I, Level);
10114         continue;
10115       }
10116     } else {
10117       bool IsBinop = B0 && B1;
10118       if (P && IsBinop) {
10119         Inst = dyn_cast<Instruction>(B0);
10120         if (Inst == P)
10121           Inst = dyn_cast<Instruction>(B1);
10122         if (!Inst) {
10123           // Set P to nullptr to avoid re-analysis of phi node in
10124           // matchAssociativeReduction function unless this is the root node.
10125           P = nullptr;
10126           continue;
10127         }
10128       }
10129       // Set P to nullptr to avoid re-analysis of phi node in
10130       // matchAssociativeReduction function unless this is the root node.
10131       P = nullptr;
10132       // Do not try to vectorize CmpInst operands, this is done separately.
10133       // Final attempt for binop args vectorization should happen after the loop
10134       // to try to find reductions.
10135       if (!isa<CmpInst>(Inst))
10136         PostponedInsts.push_back(Inst);
10137     }
10138 
10139     // Try to vectorize operands.
10140     // Continue analysis for the instruction from the same basic block only to
10141     // save compile time.
10142     if (++Level < RecursionMaxDepth)
10143       for (auto *Op : Inst->operand_values())
10144         if (VisitedInstrs.insert(Op).second)
10145           if (auto *I = dyn_cast<Instruction>(Op))
10146             // Do not try to vectorize CmpInst operands,  this is done
10147             // separately.
10148             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10149                 I->getParent() == BB)
10150               Stack.emplace(I, Level);
10151   }
10152   // Try to vectorized binops where reductions were not found.
10153   for (Value *V : PostponedInsts)
10154     if (auto *Inst = dyn_cast<Instruction>(V))
10155       if (!R.isDeleted(Inst))
10156         Res |= Vectorize(Inst, R);
10157   return Res;
10158 }
10159 
10160 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10161                                                  BasicBlock *BB, BoUpSLP &R,
10162                                                  TargetTransformInfo *TTI) {
10163   auto *I = dyn_cast_or_null<Instruction>(V);
10164   if (!I)
10165     return false;
10166 
10167   if (!isa<BinaryOperator>(I))
10168     P = nullptr;
10169   // Try to match and vectorize a horizontal reduction.
10170   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10171     return tryToVectorize(I, R);
10172   };
10173   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10174                                                   ExtraVectorization);
10175 }
10176 
10177 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10178                                                  BasicBlock *BB, BoUpSLP &R) {
10179   const DataLayout &DL = BB->getModule()->getDataLayout();
10180   if (!R.canMapToVector(IVI->getType(), DL))
10181     return false;
10182 
10183   SmallVector<Value *, 16> BuildVectorOpds;
10184   SmallVector<Value *, 16> BuildVectorInsts;
10185   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10186     return false;
10187 
10188   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10189   // Aggregate value is unlikely to be processed in vector register.
10190   return tryToVectorizeList(BuildVectorOpds, R);
10191 }
10192 
10193 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10194                                                    BasicBlock *BB, BoUpSLP &R) {
10195   SmallVector<Value *, 16> BuildVectorInsts;
10196   SmallVector<Value *, 16> BuildVectorOpds;
10197   SmallVector<int> Mask;
10198   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10199       (llvm::all_of(
10200            BuildVectorOpds,
10201            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10202        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10203     return false;
10204 
10205   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10206   return tryToVectorizeList(BuildVectorInsts, R);
10207 }
10208 
10209 template <typename T>
10210 static bool
10211 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10212                        function_ref<unsigned(T *)> Limit,
10213                        function_ref<bool(T *, T *)> Comparator,
10214                        function_ref<bool(T *, T *)> AreCompatible,
10215                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10216                        bool LimitForRegisterSize) {
10217   bool Changed = false;
10218   // Sort by type, parent, operands.
10219   stable_sort(Incoming, Comparator);
10220 
10221   // Try to vectorize elements base on their type.
10222   SmallVector<T *> Candidates;
10223   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10224     // Look for the next elements with the same type, parent and operand
10225     // kinds.
10226     auto *SameTypeIt = IncIt;
10227     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10228       ++SameTypeIt;
10229 
10230     // Try to vectorize them.
10231     unsigned NumElts = (SameTypeIt - IncIt);
10232     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10233                       << NumElts << ")\n");
10234     // The vectorization is a 3-state attempt:
10235     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10236     // size of maximal register at first.
10237     // 2. Try to vectorize remaining instructions with the same type, if
10238     // possible. This may result in the better vectorization results rather than
10239     // if we try just to vectorize instructions with the same/alternate opcodes.
10240     // 3. Final attempt to try to vectorize all instructions with the
10241     // same/alternate ops only, this may result in some extra final
10242     // vectorization.
10243     if (NumElts > 1 &&
10244         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10245       // Success start over because instructions might have been changed.
10246       Changed = true;
10247     } else if (NumElts < Limit(*IncIt) &&
10248                (Candidates.empty() ||
10249                 Candidates.front()->getType() == (*IncIt)->getType())) {
10250       Candidates.append(IncIt, std::next(IncIt, NumElts));
10251     }
10252     // Final attempt to vectorize instructions with the same types.
10253     if (Candidates.size() > 1 &&
10254         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10255       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10256         // Success start over because instructions might have been changed.
10257         Changed = true;
10258       } else if (LimitForRegisterSize) {
10259         // Try to vectorize using small vectors.
10260         for (auto *It = Candidates.begin(), *End = Candidates.end();
10261              It != End;) {
10262           auto *SameTypeIt = It;
10263           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10264             ++SameTypeIt;
10265           unsigned NumElts = (SameTypeIt - It);
10266           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10267                                             /*LimitForRegisterSize=*/false))
10268             Changed = true;
10269           It = SameTypeIt;
10270         }
10271       }
10272       Candidates.clear();
10273     }
10274 
10275     // Start over at the next instruction of a different type (or the end).
10276     IncIt = SameTypeIt;
10277   }
10278   return Changed;
10279 }
10280 
10281 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10282 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10283 /// operands. If IsCompatibility is false, function implements strict weak
10284 /// ordering relation between two cmp instructions, returning true if the first
10285 /// instruction is "less" than the second, i.e. its predicate is less than the
10286 /// predicate of the second or the operands IDs are less than the operands IDs
10287 /// of the second cmp instruction.
10288 template <bool IsCompatibility>
10289 static bool compareCmp(Value *V, Value *V2,
10290                        function_ref<bool(Instruction *)> IsDeleted) {
10291   auto *CI1 = cast<CmpInst>(V);
10292   auto *CI2 = cast<CmpInst>(V2);
10293   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10294     return false;
10295   if (CI1->getOperand(0)->getType()->getTypeID() <
10296       CI2->getOperand(0)->getType()->getTypeID())
10297     return !IsCompatibility;
10298   if (CI1->getOperand(0)->getType()->getTypeID() >
10299       CI2->getOperand(0)->getType()->getTypeID())
10300     return false;
10301   CmpInst::Predicate Pred1 = CI1->getPredicate();
10302   CmpInst::Predicate Pred2 = CI2->getPredicate();
10303   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10304   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10305   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10306   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10307   if (BasePred1 < BasePred2)
10308     return !IsCompatibility;
10309   if (BasePred1 > BasePred2)
10310     return false;
10311   // Compare operands.
10312   bool LEPreds = Pred1 <= Pred2;
10313   bool GEPreds = Pred1 >= Pred2;
10314   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10315     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10316     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10317     if (Op1->getValueID() < Op2->getValueID())
10318       return !IsCompatibility;
10319     if (Op1->getValueID() > Op2->getValueID())
10320       return false;
10321     if (auto *I1 = dyn_cast<Instruction>(Op1))
10322       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10323         if (I1->getParent() != I2->getParent())
10324           return false;
10325         InstructionsState S = getSameOpcode({I1, I2});
10326         if (S.getOpcode())
10327           continue;
10328         return false;
10329       }
10330   }
10331   return IsCompatibility;
10332 }
10333 
10334 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10335     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10336     bool AtTerminator) {
10337   bool OpsChanged = false;
10338   SmallVector<Instruction *, 4> PostponedCmps;
10339   for (auto *I : reverse(Instructions)) {
10340     if (R.isDeleted(I))
10341       continue;
10342     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10343       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10344     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10345       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10346     else if (isa<CmpInst>(I))
10347       PostponedCmps.push_back(I);
10348   }
10349   if (AtTerminator) {
10350     // Try to find reductions first.
10351     for (Instruction *I : PostponedCmps) {
10352       if (R.isDeleted(I))
10353         continue;
10354       for (Value *Op : I->operands())
10355         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10356     }
10357     // Try to vectorize operands as vector bundles.
10358     for (Instruction *I : PostponedCmps) {
10359       if (R.isDeleted(I))
10360         continue;
10361       OpsChanged |= tryToVectorize(I, R);
10362     }
10363     // Try to vectorize list of compares.
10364     // Sort by type, compare predicate, etc.
10365     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10366       return compareCmp<false>(V, V2,
10367                                [&R](Instruction *I) { return R.isDeleted(I); });
10368     };
10369 
10370     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10371       if (V1 == V2)
10372         return true;
10373       return compareCmp<true>(V1, V2,
10374                               [&R](Instruction *I) { return R.isDeleted(I); });
10375     };
10376     auto Limit = [&R](Value *V) {
10377       unsigned EltSize = R.getVectorElementSize(V);
10378       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10379     };
10380 
10381     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10382     OpsChanged |= tryToVectorizeSequence<Value>(
10383         Vals, Limit, CompareSorter, AreCompatibleCompares,
10384         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10385           // Exclude possible reductions from other blocks.
10386           bool ArePossiblyReducedInOtherBlock =
10387               any_of(Candidates, [](Value *V) {
10388                 return any_of(V->users(), [V](User *U) {
10389                   return isa<SelectInst>(U) &&
10390                          cast<SelectInst>(U)->getParent() !=
10391                              cast<Instruction>(V)->getParent();
10392                 });
10393               });
10394           if (ArePossiblyReducedInOtherBlock)
10395             return false;
10396           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10397         },
10398         /*LimitForRegisterSize=*/true);
10399     Instructions.clear();
10400   } else {
10401     // Insert in reverse order since the PostponedCmps vector was filled in
10402     // reverse order.
10403     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10404   }
10405   return OpsChanged;
10406 }
10407 
10408 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10409   bool Changed = false;
10410   SmallVector<Value *, 4> Incoming;
10411   SmallPtrSet<Value *, 16> VisitedInstrs;
10412   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10413   // node. Allows better to identify the chains that can be vectorized in the
10414   // better way.
10415   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10416   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10417     assert(isValidElementType(V1->getType()) &&
10418            isValidElementType(V2->getType()) &&
10419            "Expected vectorizable types only.");
10420     // It is fine to compare type IDs here, since we expect only vectorizable
10421     // types, like ints, floats and pointers, we don't care about other type.
10422     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10423       return true;
10424     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10425       return false;
10426     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10427     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10428     if (Opcodes1.size() < Opcodes2.size())
10429       return true;
10430     if (Opcodes1.size() > Opcodes2.size())
10431       return false;
10432     Optional<bool> ConstOrder;
10433     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10434       // Undefs are compatible with any other value.
10435       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10436         if (!ConstOrder)
10437           ConstOrder =
10438               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10439         continue;
10440       }
10441       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10442         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10443           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10444           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10445           if (!NodeI1)
10446             return NodeI2 != nullptr;
10447           if (!NodeI2)
10448             return false;
10449           assert((NodeI1 == NodeI2) ==
10450                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10451                  "Different nodes should have different DFS numbers");
10452           if (NodeI1 != NodeI2)
10453             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10454           InstructionsState S = getSameOpcode({I1, I2});
10455           if (S.getOpcode())
10456             continue;
10457           return I1->getOpcode() < I2->getOpcode();
10458         }
10459       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10460         if (!ConstOrder)
10461           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10462         continue;
10463       }
10464       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10465         return true;
10466       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10467         return false;
10468     }
10469     return ConstOrder && *ConstOrder;
10470   };
10471   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10472     if (V1 == V2)
10473       return true;
10474     if (V1->getType() != V2->getType())
10475       return false;
10476     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10477     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10478     if (Opcodes1.size() != Opcodes2.size())
10479       return false;
10480     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10481       // Undefs are compatible with any other value.
10482       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10483         continue;
10484       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10485         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10486           if (I1->getParent() != I2->getParent())
10487             return false;
10488           InstructionsState S = getSameOpcode({I1, I2});
10489           if (S.getOpcode())
10490             continue;
10491           return false;
10492         }
10493       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10494         continue;
10495       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10496         return false;
10497     }
10498     return true;
10499   };
10500   auto Limit = [&R](Value *V) {
10501     unsigned EltSize = R.getVectorElementSize(V);
10502     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10503   };
10504 
10505   bool HaveVectorizedPhiNodes = false;
10506   do {
10507     // Collect the incoming values from the PHIs.
10508     Incoming.clear();
10509     for (Instruction &I : *BB) {
10510       PHINode *P = dyn_cast<PHINode>(&I);
10511       if (!P)
10512         break;
10513 
10514       // No need to analyze deleted, vectorized and non-vectorizable
10515       // instructions.
10516       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10517           isValidElementType(P->getType()))
10518         Incoming.push_back(P);
10519     }
10520 
10521     // Find the corresponding non-phi nodes for better matching when trying to
10522     // build the tree.
10523     for (Value *V : Incoming) {
10524       SmallVectorImpl<Value *> &Opcodes =
10525           PHIToOpcodes.try_emplace(V).first->getSecond();
10526       if (!Opcodes.empty())
10527         continue;
10528       SmallVector<Value *, 4> Nodes(1, V);
10529       SmallPtrSet<Value *, 4> Visited;
10530       while (!Nodes.empty()) {
10531         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10532         if (!Visited.insert(PHI).second)
10533           continue;
10534         for (Value *V : PHI->incoming_values()) {
10535           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10536             Nodes.push_back(PHI1);
10537             continue;
10538           }
10539           Opcodes.emplace_back(V);
10540         }
10541       }
10542     }
10543 
10544     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10545         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10546         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10547           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10548         },
10549         /*LimitForRegisterSize=*/true);
10550     Changed |= HaveVectorizedPhiNodes;
10551     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10552   } while (HaveVectorizedPhiNodes);
10553 
10554   VisitedInstrs.clear();
10555 
10556   SmallVector<Instruction *, 8> PostProcessInstructions;
10557   SmallDenseSet<Instruction *, 4> KeyNodes;
10558   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10559     // Skip instructions with scalable type. The num of elements is unknown at
10560     // compile-time for scalable type.
10561     if (isa<ScalableVectorType>(it->getType()))
10562       continue;
10563 
10564     // Skip instructions marked for the deletion.
10565     if (R.isDeleted(&*it))
10566       continue;
10567     // We may go through BB multiple times so skip the one we have checked.
10568     if (!VisitedInstrs.insert(&*it).second) {
10569       if (it->use_empty() && KeyNodes.contains(&*it) &&
10570           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10571                                       it->isTerminator())) {
10572         // We would like to start over since some instructions are deleted
10573         // and the iterator may become invalid value.
10574         Changed = true;
10575         it = BB->begin();
10576         e = BB->end();
10577       }
10578       continue;
10579     }
10580 
10581     if (isa<DbgInfoIntrinsic>(it))
10582       continue;
10583 
10584     // Try to vectorize reductions that use PHINodes.
10585     if (PHINode *P = dyn_cast<PHINode>(it)) {
10586       // Check that the PHI is a reduction PHI.
10587       if (P->getNumIncomingValues() == 2) {
10588         // Try to match and vectorize a horizontal reduction.
10589         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10590                                      TTI)) {
10591           Changed = true;
10592           it = BB->begin();
10593           e = BB->end();
10594           continue;
10595         }
10596       }
10597       // Try to vectorize the incoming values of the PHI, to catch reductions
10598       // that feed into PHIs.
10599       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10600         // Skip if the incoming block is the current BB for now. Also, bypass
10601         // unreachable IR for efficiency and to avoid crashing.
10602         // TODO: Collect the skipped incoming values and try to vectorize them
10603         // after processing BB.
10604         if (BB == P->getIncomingBlock(I) ||
10605             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10606           continue;
10607 
10608         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10609                                             P->getIncomingBlock(I), R, TTI);
10610       }
10611       continue;
10612     }
10613 
10614     // Ran into an instruction without users, like terminator, or function call
10615     // with ignored return value, store. Ignore unused instructions (basing on
10616     // instruction type, except for CallInst and InvokeInst).
10617     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10618                             isa<InvokeInst>(it))) {
10619       KeyNodes.insert(&*it);
10620       bool OpsChanged = false;
10621       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10622         for (auto *V : it->operand_values()) {
10623           // Try to match and vectorize a horizontal reduction.
10624           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10625         }
10626       }
10627       // Start vectorization of post-process list of instructions from the
10628       // top-tree instructions to try to vectorize as many instructions as
10629       // possible.
10630       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10631                                                 it->isTerminator());
10632       if (OpsChanged) {
10633         // We would like to start over since some instructions are deleted
10634         // and the iterator may become invalid value.
10635         Changed = true;
10636         it = BB->begin();
10637         e = BB->end();
10638         continue;
10639       }
10640     }
10641 
10642     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10643         isa<InsertValueInst>(it))
10644       PostProcessInstructions.push_back(&*it);
10645   }
10646 
10647   return Changed;
10648 }
10649 
10650 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10651   auto Changed = false;
10652   for (auto &Entry : GEPs) {
10653     // If the getelementptr list has fewer than two elements, there's nothing
10654     // to do.
10655     if (Entry.second.size() < 2)
10656       continue;
10657 
10658     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10659                       << Entry.second.size() << ".\n");
10660 
10661     // Process the GEP list in chunks suitable for the target's supported
10662     // vector size. If a vector register can't hold 1 element, we are done. We
10663     // are trying to vectorize the index computations, so the maximum number of
10664     // elements is based on the size of the index expression, rather than the
10665     // size of the GEP itself (the target's pointer size).
10666     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10667     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10668     if (MaxVecRegSize < EltSize)
10669       continue;
10670 
10671     unsigned MaxElts = MaxVecRegSize / EltSize;
10672     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10673       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10674       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10675 
10676       // Initialize a set a candidate getelementptrs. Note that we use a
10677       // SetVector here to preserve program order. If the index computations
10678       // are vectorizable and begin with loads, we want to minimize the chance
10679       // of having to reorder them later.
10680       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10681 
10682       // Some of the candidates may have already been vectorized after we
10683       // initially collected them. If so, they are marked as deleted, so remove
10684       // them from the set of candidates.
10685       Candidates.remove_if(
10686           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10687 
10688       // Remove from the set of candidates all pairs of getelementptrs with
10689       // constant differences. Such getelementptrs are likely not good
10690       // candidates for vectorization in a bottom-up phase since one can be
10691       // computed from the other. We also ensure all candidate getelementptr
10692       // indices are unique.
10693       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10694         auto *GEPI = GEPList[I];
10695         if (!Candidates.count(GEPI))
10696           continue;
10697         auto *SCEVI = SE->getSCEV(GEPList[I]);
10698         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10699           auto *GEPJ = GEPList[J];
10700           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10701           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10702             Candidates.remove(GEPI);
10703             Candidates.remove(GEPJ);
10704           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10705             Candidates.remove(GEPJ);
10706           }
10707         }
10708       }
10709 
10710       // We break out of the above computation as soon as we know there are
10711       // fewer than two candidates remaining.
10712       if (Candidates.size() < 2)
10713         continue;
10714 
10715       // Add the single, non-constant index of each candidate to the bundle. We
10716       // ensured the indices met these constraints when we originally collected
10717       // the getelementptrs.
10718       SmallVector<Value *, 16> Bundle(Candidates.size());
10719       auto BundleIndex = 0u;
10720       for (auto *V : Candidates) {
10721         auto *GEP = cast<GetElementPtrInst>(V);
10722         auto *GEPIdx = GEP->idx_begin()->get();
10723         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10724         Bundle[BundleIndex++] = GEPIdx;
10725       }
10726 
10727       // Try and vectorize the indices. We are currently only interested in
10728       // gather-like cases of the form:
10729       //
10730       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10731       //
10732       // where the loads of "a", the loads of "b", and the subtractions can be
10733       // performed in parallel. It's likely that detecting this pattern in a
10734       // bottom-up phase will be simpler and less costly than building a
10735       // full-blown top-down phase beginning at the consecutive loads.
10736       Changed |= tryToVectorizeList(Bundle, R);
10737     }
10738   }
10739   return Changed;
10740 }
10741 
10742 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10743   bool Changed = false;
10744   // Sort by type, base pointers and values operand. Value operands must be
10745   // compatible (have the same opcode, same parent), otherwise it is
10746   // definitely not profitable to try to vectorize them.
10747   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10748     if (V->getPointerOperandType()->getTypeID() <
10749         V2->getPointerOperandType()->getTypeID())
10750       return true;
10751     if (V->getPointerOperandType()->getTypeID() >
10752         V2->getPointerOperandType()->getTypeID())
10753       return false;
10754     // UndefValues are compatible with all other values.
10755     if (isa<UndefValue>(V->getValueOperand()) ||
10756         isa<UndefValue>(V2->getValueOperand()))
10757       return false;
10758     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10759       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10760         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10761             DT->getNode(I1->getParent());
10762         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10763             DT->getNode(I2->getParent());
10764         assert(NodeI1 && "Should only process reachable instructions");
10765         assert(NodeI1 && "Should only process reachable instructions");
10766         assert((NodeI1 == NodeI2) ==
10767                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10768                "Different nodes should have different DFS numbers");
10769         if (NodeI1 != NodeI2)
10770           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10771         InstructionsState S = getSameOpcode({I1, I2});
10772         if (S.getOpcode())
10773           return false;
10774         return I1->getOpcode() < I2->getOpcode();
10775       }
10776     if (isa<Constant>(V->getValueOperand()) &&
10777         isa<Constant>(V2->getValueOperand()))
10778       return false;
10779     return V->getValueOperand()->getValueID() <
10780            V2->getValueOperand()->getValueID();
10781   };
10782 
10783   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10784     if (V1 == V2)
10785       return true;
10786     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10787       return false;
10788     // Undefs are compatible with any other value.
10789     if (isa<UndefValue>(V1->getValueOperand()) ||
10790         isa<UndefValue>(V2->getValueOperand()))
10791       return true;
10792     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10793       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10794         if (I1->getParent() != I2->getParent())
10795           return false;
10796         InstructionsState S = getSameOpcode({I1, I2});
10797         return S.getOpcode() > 0;
10798       }
10799     if (isa<Constant>(V1->getValueOperand()) &&
10800         isa<Constant>(V2->getValueOperand()))
10801       return true;
10802     return V1->getValueOperand()->getValueID() ==
10803            V2->getValueOperand()->getValueID();
10804   };
10805   auto Limit = [&R, this](StoreInst *SI) {
10806     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10807     return R.getMinVF(EltSize);
10808   };
10809 
10810   // Attempt to sort and vectorize each of the store-groups.
10811   for (auto &Pair : Stores) {
10812     if (Pair.second.size() < 2)
10813       continue;
10814 
10815     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10816                       << Pair.second.size() << ".\n");
10817 
10818     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10819       continue;
10820 
10821     Changed |= tryToVectorizeSequence<StoreInst>(
10822         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10823         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10824           return vectorizeStores(Candidates, R);
10825         },
10826         /*LimitForRegisterSize=*/false);
10827   }
10828   return Changed;
10829 }
10830 
10831 char SLPVectorizer::ID = 0;
10832 
10833 static const char lv_name[] = "SLP Vectorizer";
10834 
10835 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10836 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10837 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10838 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10839 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10840 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10841 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10842 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10843 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10844 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10845 
10846 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10847