1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The Look-ahead heuristic goes through the users of the bundle to calculate
168 // the users cost in getExternalUsesCost(). To avoid compilation time increase
169 // we limit the number of users visited to this value.
170 static cl::opt<unsigned> LookAheadUsersBudget(
171     "slp-look-ahead-users-budget", cl::init(2), cl::Hidden,
172     cl::desc("The maximum number of users to visit while visiting the "
173              "predecessors. This prevents compilation time increase."));
174 
175 static cl::opt<bool>
176     ViewSLPTree("view-slp-tree", cl::Hidden,
177                 cl::desc("Display the SLP trees with Graphviz"));
178 
179 // Limit the number of alias checks. The limit is chosen so that
180 // it has no negative effect on the llvm benchmarks.
181 static const unsigned AliasedCheckLimit = 10;
182 
183 // Another limit for the alias checks: The maximum distance between load/store
184 // instructions where alias checks are done.
185 // This limit is useful for very large basic blocks.
186 static const unsigned MaxMemDepDistance = 160;
187 
188 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
189 /// regions to be handled.
190 static const int MinScheduleRegionSize = 16;
191 
192 /// Predicate for the element types that the SLP vectorizer supports.
193 ///
194 /// The most important thing to filter here are types which are invalid in LLVM
195 /// vectors. We also filter target specific types which have absolutely no
196 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
197 /// avoids spending time checking the cost model and realizing that they will
198 /// be inevitably scalarized.
199 static bool isValidElementType(Type *Ty) {
200   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
201          !Ty->isPPC_FP128Ty();
202 }
203 
204 /// \returns True if the value is a constant (but not globals/constant
205 /// expressions).
206 static bool isConstant(Value *V) {
207   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
208 }
209 
210 /// Checks if \p V is one of vector-like instructions, i.e. undef,
211 /// insertelement/extractelement with constant indices for fixed vector type or
212 /// extractvalue instruction.
213 static bool isVectorLikeInstWithConstOps(Value *V) {
214   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
215       !isa<ExtractValueInst, UndefValue>(V))
216     return false;
217   auto *I = dyn_cast<Instruction>(V);
218   if (!I || isa<ExtractValueInst>(I))
219     return true;
220   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
221     return false;
222   if (isa<ExtractElementInst>(I))
223     return isConstant(I->getOperand(1));
224   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
225   return isConstant(I->getOperand(2));
226 }
227 
228 /// \returns true if all of the instructions in \p VL are in the same block or
229 /// false otherwise.
230 static bool allSameBlock(ArrayRef<Value *> VL) {
231   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
232   if (!I0)
233     return false;
234   if (all_of(VL, isVectorLikeInstWithConstOps))
235     return true;
236 
237   BasicBlock *BB = I0->getParent();
238   for (int I = 1, E = VL.size(); I < E; I++) {
239     auto *II = dyn_cast<Instruction>(VL[I]);
240     if (!II)
241       return false;
242 
243     if (BB != II->getParent())
244       return false;
245   }
246   return true;
247 }
248 
249 /// \returns True if all of the values in \p VL are constants (but not
250 /// globals/constant expressions).
251 static bool allConstant(ArrayRef<Value *> VL) {
252   // Constant expressions and globals can't be vectorized like normal integer/FP
253   // constants.
254   return all_of(VL, isConstant);
255 }
256 
257 /// \returns True if all of the values in \p VL are identical or some of them
258 /// are UndefValue.
259 static bool isSplat(ArrayRef<Value *> VL) {
260   Value *FirstNonUndef = nullptr;
261   for (Value *V : VL) {
262     if (isa<UndefValue>(V))
263       continue;
264     if (!FirstNonUndef) {
265       FirstNonUndef = V;
266       continue;
267     }
268     if (V != FirstNonUndef)
269       return false;
270   }
271   return FirstNonUndef != nullptr;
272 }
273 
274 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
275 static bool isCommutative(Instruction *I) {
276   if (auto *Cmp = dyn_cast<CmpInst>(I))
277     return Cmp->isCommutative();
278   if (auto *BO = dyn_cast<BinaryOperator>(I))
279     return BO->isCommutative();
280   // TODO: This should check for generic Instruction::isCommutative(), but
281   //       we need to confirm that the caller code correctly handles Intrinsics
282   //       for example (does not have 2 operands).
283   return false;
284 }
285 
286 /// Checks if the given value is actually an undefined constant vector.
287 static bool isUndefVector(const Value *V) {
288   if (isa<UndefValue>(V))
289     return true;
290   auto *C = dyn_cast<Constant>(V);
291   if (!C)
292     return false;
293   if (!C->containsUndefOrPoisonElement())
294     return false;
295   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
296   if (!VecTy)
297     return false;
298   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
299     if (Constant *Elem = C->getAggregateElement(I))
300       if (!isa<UndefValue>(Elem))
301         return false;
302   }
303   return true;
304 }
305 
306 /// Checks if the vector of instructions can be represented as a shuffle, like:
307 /// %x0 = extractelement <4 x i8> %x, i32 0
308 /// %x3 = extractelement <4 x i8> %x, i32 3
309 /// %y1 = extractelement <4 x i8> %y, i32 1
310 /// %y2 = extractelement <4 x i8> %y, i32 2
311 /// %x0x0 = mul i8 %x0, %x0
312 /// %x3x3 = mul i8 %x3, %x3
313 /// %y1y1 = mul i8 %y1, %y1
314 /// %y2y2 = mul i8 %y2, %y2
315 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
316 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
317 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
318 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
319 /// ret <4 x i8> %ins4
320 /// can be transformed into:
321 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
322 ///                                                         i32 6>
323 /// %2 = mul <4 x i8> %1, %1
324 /// ret <4 x i8> %2
325 /// We convert this initially to something like:
326 /// %x0 = extractelement <4 x i8> %x, i32 0
327 /// %x3 = extractelement <4 x i8> %x, i32 3
328 /// %y1 = extractelement <4 x i8> %y, i32 1
329 /// %y2 = extractelement <4 x i8> %y, i32 2
330 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
331 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
332 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
333 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
334 /// %5 = mul <4 x i8> %4, %4
335 /// %6 = extractelement <4 x i8> %5, i32 0
336 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
337 /// %7 = extractelement <4 x i8> %5, i32 1
338 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
339 /// %8 = extractelement <4 x i8> %5, i32 2
340 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
341 /// %9 = extractelement <4 x i8> %5, i32 3
342 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
343 /// ret <4 x i8> %ins4
344 /// InstCombiner transforms this into a shuffle and vector mul
345 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
346 /// TODO: Can we split off and reuse the shuffle mask detection from
347 /// TargetTransformInfo::getInstructionThroughput?
348 static Optional<TargetTransformInfo::ShuffleKind>
349 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
350   const auto *It =
351       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
352   if (It == VL.end())
353     return None;
354   auto *EI0 = cast<ExtractElementInst>(*It);
355   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
356     return None;
357   unsigned Size =
358       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
359   Value *Vec1 = nullptr;
360   Value *Vec2 = nullptr;
361   enum ShuffleMode { Unknown, Select, Permute };
362   ShuffleMode CommonShuffleMode = Unknown;
363   Mask.assign(VL.size(), UndefMaskElem);
364   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
365     // Undef can be represented as an undef element in a vector.
366     if (isa<UndefValue>(VL[I]))
367       continue;
368     auto *EI = cast<ExtractElementInst>(VL[I]);
369     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
370       return None;
371     auto *Vec = EI->getVectorOperand();
372     // We can extractelement from undef or poison vector.
373     if (isUndefVector(Vec))
374       continue;
375     // All vector operands must have the same number of vector elements.
376     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
377       return None;
378     if (isa<UndefValue>(EI->getIndexOperand()))
379       continue;
380     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
381     if (!Idx)
382       return None;
383     // Undefined behavior if Idx is negative or >= Size.
384     if (Idx->getValue().uge(Size))
385       continue;
386     unsigned IntIdx = Idx->getValue().getZExtValue();
387     Mask[I] = IntIdx;
388     // For correct shuffling we have to have at most 2 different vector operands
389     // in all extractelement instructions.
390     if (!Vec1 || Vec1 == Vec) {
391       Vec1 = Vec;
392     } else if (!Vec2 || Vec2 == Vec) {
393       Vec2 = Vec;
394       Mask[I] += Size;
395     } else {
396       return None;
397     }
398     if (CommonShuffleMode == Permute)
399       continue;
400     // If the extract index is not the same as the operation number, it is a
401     // permutation.
402     if (IntIdx != I) {
403       CommonShuffleMode = Permute;
404       continue;
405     }
406     CommonShuffleMode = Select;
407   }
408   // If we're not crossing lanes in different vectors, consider it as blending.
409   if (CommonShuffleMode == Select && Vec2)
410     return TargetTransformInfo::SK_Select;
411   // If Vec2 was never used, we have a permutation of a single vector, otherwise
412   // we have permutation of 2 vectors.
413   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
414               : TargetTransformInfo::SK_PermuteSingleSrc;
415 }
416 
417 namespace {
418 
419 /// Main data required for vectorization of instructions.
420 struct InstructionsState {
421   /// The very first instruction in the list with the main opcode.
422   Value *OpValue = nullptr;
423 
424   /// The main/alternate instruction.
425   Instruction *MainOp = nullptr;
426   Instruction *AltOp = nullptr;
427 
428   /// The main/alternate opcodes for the list of instructions.
429   unsigned getOpcode() const {
430     return MainOp ? MainOp->getOpcode() : 0;
431   }
432 
433   unsigned getAltOpcode() const {
434     return AltOp ? AltOp->getOpcode() : 0;
435   }
436 
437   /// Some of the instructions in the list have alternate opcodes.
438   bool isAltShuffle() const { return AltOp != MainOp; }
439 
440   bool isOpcodeOrAlt(Instruction *I) const {
441     unsigned CheckedOpcode = I->getOpcode();
442     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
443   }
444 
445   InstructionsState() = delete;
446   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
447       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
448 };
449 
450 } // end anonymous namespace
451 
452 /// Chooses the correct key for scheduling data. If \p Op has the same (or
453 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
454 /// OpValue.
455 static Value *isOneOf(const InstructionsState &S, Value *Op) {
456   auto *I = dyn_cast<Instruction>(Op);
457   if (I && S.isOpcodeOrAlt(I))
458     return Op;
459   return S.OpValue;
460 }
461 
462 /// \returns true if \p Opcode is allowed as part of of the main/alternate
463 /// instruction for SLP vectorization.
464 ///
465 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
466 /// "shuffled out" lane would result in division by zero.
467 static bool isValidForAlternation(unsigned Opcode) {
468   if (Instruction::isIntDivRem(Opcode))
469     return false;
470 
471   return true;
472 }
473 
474 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
475                                        unsigned BaseIndex = 0);
476 
477 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
478 /// compatible instructions or constants, or just some other regular values.
479 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
480                                 Value *Op1) {
481   return (isConstant(BaseOp0) && isConstant(Op0)) ||
482          (isConstant(BaseOp1) && isConstant(Op1)) ||
483          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
484           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
485          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
486          getSameOpcode({BaseOp1, Op1}).getOpcode();
487 }
488 
489 /// \returns analysis of the Instructions in \p VL described in
490 /// InstructionsState, the Opcode that we suppose the whole list
491 /// could be vectorized even if its structure is diverse.
492 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
493                                        unsigned BaseIndex) {
494   // Make sure these are all Instructions.
495   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
496     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
497 
498   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
499   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
500   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
501   CmpInst::Predicate BasePred =
502       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
503               : CmpInst::BAD_ICMP_PREDICATE;
504   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
505   unsigned AltOpcode = Opcode;
506   unsigned AltIndex = BaseIndex;
507 
508   // Check for one alternate opcode from another BinaryOperator.
509   // TODO - generalize to support all operators (types, calls etc.).
510   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
511     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
512     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
513       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
514         continue;
515       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
516           isValidForAlternation(Opcode)) {
517         AltOpcode = InstOpcode;
518         AltIndex = Cnt;
519         continue;
520       }
521     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
522       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
523       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
524       if (Ty0 == Ty1) {
525         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
526           continue;
527         if (Opcode == AltOpcode) {
528           assert(isValidForAlternation(Opcode) &&
529                  isValidForAlternation(InstOpcode) &&
530                  "Cast isn't safe for alternation, logic needs to be updated!");
531           AltOpcode = InstOpcode;
532           AltIndex = Cnt;
533           continue;
534         }
535       }
536     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
537       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
538       auto *Inst = cast<Instruction>(VL[Cnt]);
539       Type *Ty0 = BaseInst->getOperand(0)->getType();
540       Type *Ty1 = Inst->getOperand(0)->getType();
541       if (Ty0 == Ty1) {
542         Value *BaseOp0 = BaseInst->getOperand(0);
543         Value *BaseOp1 = BaseInst->getOperand(1);
544         Value *Op0 = Inst->getOperand(0);
545         Value *Op1 = Inst->getOperand(1);
546         CmpInst::Predicate CurrentPred =
547             cast<CmpInst>(VL[Cnt])->getPredicate();
548         // Check for compatible operands. If the corresponding operands are not
549         // compatible - need to perform alternate vectorization.
550         if (InstOpcode == Opcode) {
551           if (BasePred == CurrentPred &&
552               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
553             continue;
554           if (BasePred == CmpInst::getSwappedPredicate(CurrentPred) &&
555               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
556             continue;
557           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
558           CmpInst::Predicate AltPred = AltInst->getPredicate();
559           Value *AltOp0 = AltInst->getOperand(0);
560           Value *AltOp1 = AltInst->getOperand(1);
561           // Check if operands are compatible with alternate operands.
562           if (AltPred == CurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
564             continue;
565           if (AltPred == CmpInst::getSwappedPredicate(CurrentPred) &&
566               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
567             continue;
568         }
569         if (BaseIndex == AltIndex) {
570           assert(isValidForAlternation(Opcode) &&
571                  isValidForAlternation(InstOpcode) &&
572                  "Cast isn't safe for alternation, logic needs to be updated!");
573           AltIndex = Cnt;
574           continue;
575         }
576       }
577     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
578       continue;
579     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
580   }
581 
582   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
583                            cast<Instruction>(VL[AltIndex]));
584 }
585 
586 /// \returns true if all of the values in \p VL have the same type or false
587 /// otherwise.
588 static bool allSameType(ArrayRef<Value *> VL) {
589   Type *Ty = VL[0]->getType();
590   for (int i = 1, e = VL.size(); i < e; i++)
591     if (VL[i]->getType() != Ty)
592       return false;
593 
594   return true;
595 }
596 
597 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
598 static Optional<unsigned> getExtractIndex(Instruction *E) {
599   unsigned Opcode = E->getOpcode();
600   assert((Opcode == Instruction::ExtractElement ||
601           Opcode == Instruction::ExtractValue) &&
602          "Expected extractelement or extractvalue instruction.");
603   if (Opcode == Instruction::ExtractElement) {
604     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
605     if (!CI)
606       return None;
607     return CI->getZExtValue();
608   }
609   ExtractValueInst *EI = cast<ExtractValueInst>(E);
610   if (EI->getNumIndices() != 1)
611     return None;
612   return *EI->idx_begin();
613 }
614 
615 /// \returns True if in-tree use also needs extract. This refers to
616 /// possible scalar operand in vectorized instruction.
617 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
618                                     TargetLibraryInfo *TLI) {
619   unsigned Opcode = UserInst->getOpcode();
620   switch (Opcode) {
621   case Instruction::Load: {
622     LoadInst *LI = cast<LoadInst>(UserInst);
623     return (LI->getPointerOperand() == Scalar);
624   }
625   case Instruction::Store: {
626     StoreInst *SI = cast<StoreInst>(UserInst);
627     return (SI->getPointerOperand() == Scalar);
628   }
629   case Instruction::Call: {
630     CallInst *CI = cast<CallInst>(UserInst);
631     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
632     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
633       if (hasVectorInstrinsicScalarOpd(ID, i))
634         return (CI->getArgOperand(i) == Scalar);
635     }
636     LLVM_FALLTHROUGH;
637   }
638   default:
639     return false;
640   }
641 }
642 
643 /// \returns the AA location that is being access by the instruction.
644 static MemoryLocation getLocation(Instruction *I) {
645   if (StoreInst *SI = dyn_cast<StoreInst>(I))
646     return MemoryLocation::get(SI);
647   if (LoadInst *LI = dyn_cast<LoadInst>(I))
648     return MemoryLocation::get(LI);
649   return MemoryLocation();
650 }
651 
652 /// \returns True if the instruction is not a volatile or atomic load/store.
653 static bool isSimple(Instruction *I) {
654   if (LoadInst *LI = dyn_cast<LoadInst>(I))
655     return LI->isSimple();
656   if (StoreInst *SI = dyn_cast<StoreInst>(I))
657     return SI->isSimple();
658   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
659     return !MI->isVolatile();
660   return true;
661 }
662 
663 /// Shuffles \p Mask in accordance with the given \p SubMask.
664 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
665   if (SubMask.empty())
666     return;
667   if (Mask.empty()) {
668     Mask.append(SubMask.begin(), SubMask.end());
669     return;
670   }
671   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
672   int TermValue = std::min(Mask.size(), SubMask.size());
673   for (int I = 0, E = SubMask.size(); I < E; ++I) {
674     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
675         Mask[SubMask[I]] >= TermValue)
676       continue;
677     NewMask[I] = Mask[SubMask[I]];
678   }
679   Mask.swap(NewMask);
680 }
681 
682 /// Order may have elements assigned special value (size) which is out of
683 /// bounds. Such indices only appear on places which correspond to undef values
684 /// (see canReuseExtract for details) and used in order to avoid undef values
685 /// have effect on operands ordering.
686 /// The first loop below simply finds all unused indices and then the next loop
687 /// nest assigns these indices for undef values positions.
688 /// As an example below Order has two undef positions and they have assigned
689 /// values 3 and 7 respectively:
690 /// before:  6 9 5 4 9 2 1 0
691 /// after:   6 3 5 4 7 2 1 0
692 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
693   const unsigned Sz = Order.size();
694   SmallBitVector UnusedIndices(Sz, /*t=*/true);
695   SmallBitVector MaskedIndices(Sz);
696   for (unsigned I = 0; I < Sz; ++I) {
697     if (Order[I] < Sz)
698       UnusedIndices.reset(Order[I]);
699     else
700       MaskedIndices.set(I);
701   }
702   if (MaskedIndices.none())
703     return;
704   assert(UnusedIndices.count() == MaskedIndices.count() &&
705          "Non-synced masked/available indices.");
706   int Idx = UnusedIndices.find_first();
707   int MIdx = MaskedIndices.find_first();
708   while (MIdx >= 0) {
709     assert(Idx >= 0 && "Indices must be synced.");
710     Order[MIdx] = Idx;
711     Idx = UnusedIndices.find_next(Idx);
712     MIdx = MaskedIndices.find_next(MIdx);
713   }
714 }
715 
716 namespace llvm {
717 
718 static void inversePermutation(ArrayRef<unsigned> Indices,
719                                SmallVectorImpl<int> &Mask) {
720   Mask.clear();
721   const unsigned E = Indices.size();
722   Mask.resize(E, UndefMaskElem);
723   for (unsigned I = 0; I < E; ++I)
724     Mask[Indices[I]] = I;
725 }
726 
727 /// \returns inserting index of InsertElement or InsertValue instruction,
728 /// using Offset as base offset for index.
729 static Optional<int> getInsertIndex(Value *InsertInst, unsigned Offset) {
730   int Index = Offset;
731   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
732     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
733       auto *VT = cast<FixedVectorType>(IE->getType());
734       if (CI->getValue().uge(VT->getNumElements()))
735         return UndefMaskElem;
736       Index *= VT->getNumElements();
737       Index += CI->getZExtValue();
738       return Index;
739     }
740     if (isa<UndefValue>(IE->getOperand(2)))
741       return UndefMaskElem;
742     return None;
743   }
744 
745   auto *IV = cast<InsertValueInst>(InsertInst);
746   Type *CurrentType = IV->getType();
747   for (unsigned I : IV->indices()) {
748     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
749       Index *= ST->getNumElements();
750       CurrentType = ST->getElementType(I);
751     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
752       Index *= AT->getNumElements();
753       CurrentType = AT->getElementType();
754     } else {
755       return None;
756     }
757     Index += I;
758   }
759   return Index;
760 }
761 
762 /// Reorders the list of scalars in accordance with the given \p Order and then
763 /// the \p Mask. \p Order - is the original order of the scalars, need to
764 /// reorder scalars into an unordered state at first according to the given
765 /// order. Then the ordered scalars are shuffled once again in accordance with
766 /// the provided mask.
767 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
768                            ArrayRef<int> Mask) {
769   assert(!Mask.empty() && "Expected non-empty mask.");
770   SmallVector<Value *> Prev(Scalars.size(),
771                             UndefValue::get(Scalars.front()->getType()));
772   Prev.swap(Scalars);
773   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
774     if (Mask[I] != UndefMaskElem)
775       Scalars[Mask[I]] = Prev[I];
776 }
777 
778 namespace slpvectorizer {
779 
780 /// Bottom Up SLP Vectorizer.
781 class BoUpSLP {
782   struct TreeEntry;
783   struct ScheduleData;
784 
785 public:
786   using ValueList = SmallVector<Value *, 8>;
787   using InstrList = SmallVector<Instruction *, 16>;
788   using ValueSet = SmallPtrSet<Value *, 16>;
789   using StoreList = SmallVector<StoreInst *, 8>;
790   using ExtraValueToDebugLocsMap =
791       MapVector<Value *, SmallVector<Instruction *, 2>>;
792   using OrdersType = SmallVector<unsigned, 4>;
793 
794   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
795           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
796           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
797           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
798       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
799         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
800     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
801     // Use the vector register size specified by the target unless overridden
802     // by a command-line option.
803     // TODO: It would be better to limit the vectorization factor based on
804     //       data type rather than just register size. For example, x86 AVX has
805     //       256-bit registers, but it does not support integer operations
806     //       at that width (that requires AVX2).
807     if (MaxVectorRegSizeOption.getNumOccurrences())
808       MaxVecRegSize = MaxVectorRegSizeOption;
809     else
810       MaxVecRegSize =
811           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
812               .getFixedSize();
813 
814     if (MinVectorRegSizeOption.getNumOccurrences())
815       MinVecRegSize = MinVectorRegSizeOption;
816     else
817       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
818   }
819 
820   /// Vectorize the tree that starts with the elements in \p VL.
821   /// Returns the vectorized root.
822   Value *vectorizeTree();
823 
824   /// Vectorize the tree but with the list of externally used values \p
825   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
826   /// generated extractvalue instructions.
827   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
828 
829   /// \returns the cost incurred by unwanted spills and fills, caused by
830   /// holding live values over call sites.
831   InstructionCost getSpillCost() const;
832 
833   /// \returns the vectorization cost of the subtree that starts at \p VL.
834   /// A negative number means that this is profitable.
835   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
836 
837   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
838   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
839   void buildTree(ArrayRef<Value *> Roots,
840                  ArrayRef<Value *> UserIgnoreLst = None);
841 
842   /// Builds external uses of the vectorized scalars, i.e. the list of
843   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
844   /// ExternallyUsedValues contains additional list of external uses to handle
845   /// vectorization of reductions.
846   void
847   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
848 
849   /// Clear the internal data structures that are created by 'buildTree'.
850   void deleteTree() {
851     VectorizableTree.clear();
852     ScalarToTreeEntry.clear();
853     MustGather.clear();
854     ExternalUses.clear();
855     for (auto &Iter : BlocksSchedules) {
856       BlockScheduling *BS = Iter.second.get();
857       BS->clear();
858     }
859     MinBWs.clear();
860     InstrElementSize.clear();
861   }
862 
863   unsigned getTreeSize() const { return VectorizableTree.size(); }
864 
865   /// Perform LICM and CSE on the newly generated gather sequences.
866   void optimizeGatherSequence();
867 
868   /// Checks if the specified gather tree entry \p TE can be represented as a
869   /// shuffled vector entry + (possibly) permutation with other gathers. It
870   /// implements the checks only for possibly ordered scalars (Loads,
871   /// ExtractElement, ExtractValue), which can be part of the graph.
872   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
873 
874   /// Gets reordering data for the given tree entry. If the entry is vectorized
875   /// - just return ReorderIndices, otherwise check if the scalars can be
876   /// reordered and return the most optimal order.
877   /// \param TopToBottom If true, include the order of vectorized stores and
878   /// insertelement nodes, otherwise skip them.
879   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
880 
881   /// Reorders the current graph to the most profitable order starting from the
882   /// root node to the leaf nodes. The best order is chosen only from the nodes
883   /// of the same size (vectorization factor). Smaller nodes are considered
884   /// parts of subgraph with smaller VF and they are reordered independently. We
885   /// can make it because we still need to extend smaller nodes to the wider VF
886   /// and we can merge reordering shuffles with the widening shuffles.
887   void reorderTopToBottom();
888 
889   /// Reorders the current graph to the most profitable order starting from
890   /// leaves to the root. It allows to rotate small subgraphs and reduce the
891   /// number of reshuffles if the leaf nodes use the same order. In this case we
892   /// can merge the orders and just shuffle user node instead of shuffling its
893   /// operands. Plus, even the leaf nodes have different orders, it allows to
894   /// sink reordering in the graph closer to the root node and merge it later
895   /// during analysis.
896   void reorderBottomToTop(bool IgnoreReorder = false);
897 
898   /// \return The vector element size in bits to use when vectorizing the
899   /// expression tree ending at \p V. If V is a store, the size is the width of
900   /// the stored value. Otherwise, the size is the width of the largest loaded
901   /// value reaching V. This method is used by the vectorizer to calculate
902   /// vectorization factors.
903   unsigned getVectorElementSize(Value *V);
904 
905   /// Compute the minimum type sizes required to represent the entries in a
906   /// vectorizable tree.
907   void computeMinimumValueSizes();
908 
909   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
910   unsigned getMaxVecRegSize() const {
911     return MaxVecRegSize;
912   }
913 
914   // \returns minimum vector register size as set by cl::opt.
915   unsigned getMinVecRegSize() const {
916     return MinVecRegSize;
917   }
918 
919   unsigned getMinVF(unsigned Sz) const {
920     return std::max(2U, getMinVecRegSize() / Sz);
921   }
922 
923   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
924     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
925       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
926     return MaxVF ? MaxVF : UINT_MAX;
927   }
928 
929   /// Check if homogeneous aggregate is isomorphic to some VectorType.
930   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
931   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
932   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
933   ///
934   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
935   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
936 
937   /// \returns True if the VectorizableTree is both tiny and not fully
938   /// vectorizable. We do not vectorize such trees.
939   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
940 
941   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
942   /// can be load combined in the backend. Load combining may not be allowed in
943   /// the IR optimizer, so we do not want to alter the pattern. For example,
944   /// partially transforming a scalar bswap() pattern into vector code is
945   /// effectively impossible for the backend to undo.
946   /// TODO: If load combining is allowed in the IR optimizer, this analysis
947   ///       may not be necessary.
948   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
949 
950   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
951   /// can be load combined in the backend. Load combining may not be allowed in
952   /// the IR optimizer, so we do not want to alter the pattern. For example,
953   /// partially transforming a scalar bswap() pattern into vector code is
954   /// effectively impossible for the backend to undo.
955   /// TODO: If load combining is allowed in the IR optimizer, this analysis
956   ///       may not be necessary.
957   bool isLoadCombineCandidate() const;
958 
959   OptimizationRemarkEmitter *getORE() { return ORE; }
960 
961   /// This structure holds any data we need about the edges being traversed
962   /// during buildTree_rec(). We keep track of:
963   /// (i) the user TreeEntry index, and
964   /// (ii) the index of the edge.
965   struct EdgeInfo {
966     EdgeInfo() = default;
967     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
968         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
969     /// The user TreeEntry.
970     TreeEntry *UserTE = nullptr;
971     /// The operand index of the use.
972     unsigned EdgeIdx = UINT_MAX;
973 #ifndef NDEBUG
974     friend inline raw_ostream &operator<<(raw_ostream &OS,
975                                           const BoUpSLP::EdgeInfo &EI) {
976       EI.dump(OS);
977       return OS;
978     }
979     /// Debug print.
980     void dump(raw_ostream &OS) const {
981       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
982          << " EdgeIdx:" << EdgeIdx << "}";
983     }
984     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
985 #endif
986   };
987 
988   /// A helper data structure to hold the operands of a vector of instructions.
989   /// This supports a fixed vector length for all operand vectors.
990   class VLOperands {
991     /// For each operand we need (i) the value, and (ii) the opcode that it
992     /// would be attached to if the expression was in a left-linearized form.
993     /// This is required to avoid illegal operand reordering.
994     /// For example:
995     /// \verbatim
996     ///                         0 Op1
997     ///                         |/
998     /// Op1 Op2   Linearized    + Op2
999     ///   \ /     ---------->   |/
1000     ///    -                    -
1001     ///
1002     /// Op1 - Op2            (0 + Op1) - Op2
1003     /// \endverbatim
1004     ///
1005     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1006     ///
1007     /// Another way to think of this is to track all the operations across the
1008     /// path from the operand all the way to the root of the tree and to
1009     /// calculate the operation that corresponds to this path. For example, the
1010     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1011     /// corresponding operation is a '-' (which matches the one in the
1012     /// linearized tree, as shown above).
1013     ///
1014     /// For lack of a better term, we refer to this operation as Accumulated
1015     /// Path Operation (APO).
1016     struct OperandData {
1017       OperandData() = default;
1018       OperandData(Value *V, bool APO, bool IsUsed)
1019           : V(V), APO(APO), IsUsed(IsUsed) {}
1020       /// The operand value.
1021       Value *V = nullptr;
1022       /// TreeEntries only allow a single opcode, or an alternate sequence of
1023       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1024       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1025       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1026       /// (e.g., Add/Mul)
1027       bool APO = false;
1028       /// Helper data for the reordering function.
1029       bool IsUsed = false;
1030     };
1031 
1032     /// During operand reordering, we are trying to select the operand at lane
1033     /// that matches best with the operand at the neighboring lane. Our
1034     /// selection is based on the type of value we are looking for. For example,
1035     /// if the neighboring lane has a load, we need to look for a load that is
1036     /// accessing a consecutive address. These strategies are summarized in the
1037     /// 'ReorderingMode' enumerator.
1038     enum class ReorderingMode {
1039       Load,     ///< Matching loads to consecutive memory addresses
1040       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1041       Constant, ///< Matching constants
1042       Splat,    ///< Matching the same instruction multiple times (broadcast)
1043       Failed,   ///< We failed to create a vectorizable group
1044     };
1045 
1046     using OperandDataVec = SmallVector<OperandData, 2>;
1047 
1048     /// A vector of operand vectors.
1049     SmallVector<OperandDataVec, 4> OpsVec;
1050 
1051     const DataLayout &DL;
1052     ScalarEvolution &SE;
1053     const BoUpSLP &R;
1054 
1055     /// \returns the operand data at \p OpIdx and \p Lane.
1056     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1057       return OpsVec[OpIdx][Lane];
1058     }
1059 
1060     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1061     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1062       return OpsVec[OpIdx][Lane];
1063     }
1064 
1065     /// Clears the used flag for all entries.
1066     void clearUsed() {
1067       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1068            OpIdx != NumOperands; ++OpIdx)
1069         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1070              ++Lane)
1071           OpsVec[OpIdx][Lane].IsUsed = false;
1072     }
1073 
1074     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1075     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1076       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1077     }
1078 
1079     // The hard-coded scores listed here are not very important, though it shall
1080     // be higher for better matches to improve the resulting cost. When
1081     // computing the scores of matching one sub-tree with another, we are
1082     // basically counting the number of values that are matching. So even if all
1083     // scores are set to 1, we would still get a decent matching result.
1084     // However, sometimes we have to break ties. For example we may have to
1085     // choose between matching loads vs matching opcodes. This is what these
1086     // scores are helping us with: they provide the order of preference. Also,
1087     // this is important if the scalar is externally used or used in another
1088     // tree entry node in the different lane.
1089 
1090     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1091     static const int ScoreConsecutiveLoads = 4;
1092     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1093     static const int ScoreReversedLoads = 3;
1094     /// ExtractElementInst from same vector and consecutive indexes.
1095     static const int ScoreConsecutiveExtracts = 4;
1096     /// ExtractElementInst from same vector and reversed indices.
1097     static const int ScoreReversedExtracts = 3;
1098     /// Constants.
1099     static const int ScoreConstants = 2;
1100     /// Instructions with the same opcode.
1101     static const int ScoreSameOpcode = 2;
1102     /// Instructions with alt opcodes (e.g, add + sub).
1103     static const int ScoreAltOpcodes = 1;
1104     /// Identical instructions (a.k.a. splat or broadcast).
1105     static const int ScoreSplat = 1;
1106     /// Matching with an undef is preferable to failing.
1107     static const int ScoreUndef = 1;
1108     /// Score for failing to find a decent match.
1109     static const int ScoreFail = 0;
1110     /// User exteranl to the vectorized code.
1111     static const int ExternalUseCost = 1;
1112     /// The user is internal but in a different lane.
1113     static const int UserInDiffLaneCost = ExternalUseCost;
1114 
1115     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1116     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1117                                ScalarEvolution &SE, int NumLanes) {
1118       if (V1 == V2)
1119         return VLOperands::ScoreSplat;
1120 
1121       auto *LI1 = dyn_cast<LoadInst>(V1);
1122       auto *LI2 = dyn_cast<LoadInst>(V2);
1123       if (LI1 && LI2) {
1124         if (LI1->getParent() != LI2->getParent())
1125           return VLOperands::ScoreFail;
1126 
1127         Optional<int> Dist = getPointersDiff(
1128             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1129             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1130         if (!Dist)
1131           return VLOperands::ScoreFail;
1132         // The distance is too large - still may be profitable to use masked
1133         // loads/gathers.
1134         if (std::abs(*Dist) > NumLanes / 2)
1135           return VLOperands::ScoreAltOpcodes;
1136         // This still will detect consecutive loads, but we might have "holes"
1137         // in some cases. It is ok for non-power-2 vectorization and may produce
1138         // better results. It should not affect current vectorization.
1139         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1140                            : VLOperands::ScoreReversedLoads;
1141       }
1142 
1143       auto *C1 = dyn_cast<Constant>(V1);
1144       auto *C2 = dyn_cast<Constant>(V2);
1145       if (C1 && C2)
1146         return VLOperands::ScoreConstants;
1147 
1148       // Extracts from consecutive indexes of the same vector better score as
1149       // the extracts could be optimized away.
1150       Value *EV1;
1151       ConstantInt *Ex1Idx;
1152       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1153         // Undefs are always profitable for extractelements.
1154         if (isa<UndefValue>(V2))
1155           return VLOperands::ScoreConsecutiveExtracts;
1156         Value *EV2 = nullptr;
1157         ConstantInt *Ex2Idx = nullptr;
1158         if (match(V2,
1159                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1160                                                          m_Undef())))) {
1161           // Undefs are always profitable for extractelements.
1162           if (!Ex2Idx)
1163             return VLOperands::ScoreConsecutiveExtracts;
1164           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1165             return VLOperands::ScoreConsecutiveExtracts;
1166           if (EV2 == EV1) {
1167             int Idx1 = Ex1Idx->getZExtValue();
1168             int Idx2 = Ex2Idx->getZExtValue();
1169             int Dist = Idx2 - Idx1;
1170             // The distance is too large - still may be profitable to use
1171             // shuffles.
1172             if (std::abs(Dist) > NumLanes / 2)
1173               return VLOperands::ScoreAltOpcodes;
1174             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1175                               : VLOperands::ScoreReversedExtracts;
1176           }
1177         }
1178       }
1179 
1180       auto *I1 = dyn_cast<Instruction>(V1);
1181       auto *I2 = dyn_cast<Instruction>(V2);
1182       if (I1 && I2) {
1183         if (I1->getParent() != I2->getParent())
1184           return VLOperands::ScoreFail;
1185         InstructionsState S = getSameOpcode({I1, I2});
1186         // Note: Only consider instructions with <= 2 operands to avoid
1187         // complexity explosion.
1188         if (S.getOpcode() && S.MainOp->getNumOperands() <= 2)
1189           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1190                                   : VLOperands::ScoreSameOpcode;
1191       }
1192 
1193       if (isa<UndefValue>(V2))
1194         return VLOperands::ScoreUndef;
1195 
1196       return VLOperands::ScoreFail;
1197     }
1198 
1199     /// Holds the values and their lanes that are taking part in the look-ahead
1200     /// score calculation. This is used in the external uses cost calculation.
1201     /// Need to hold all the lanes in case of splat/broadcast at least to
1202     /// correctly check for the use in the different lane.
1203     SmallDenseMap<Value *, SmallSet<int, 4>> InLookAheadValues;
1204 
1205     /// \returns the additional cost due to uses of \p LHS and \p RHS that are
1206     /// either external to the vectorized code, or require shuffling.
1207     int getExternalUsesCost(const std::pair<Value *, int> &LHS,
1208                             const std::pair<Value *, int> &RHS) {
1209       int Cost = 0;
1210       std::array<std::pair<Value *, int>, 2> Values = {{LHS, RHS}};
1211       for (int Idx = 0, IdxE = Values.size(); Idx != IdxE; ++Idx) {
1212         Value *V = Values[Idx].first;
1213         if (isa<Constant>(V)) {
1214           // Since this is a function pass, it doesn't make semantic sense to
1215           // walk the users of a subclass of Constant. The users could be in
1216           // another function, or even another module that happens to be in
1217           // the same LLVMContext.
1218           continue;
1219         }
1220 
1221         // Calculate the absolute lane, using the minimum relative lane of LHS
1222         // and RHS as base and Idx as the offset.
1223         int Ln = std::min(LHS.second, RHS.second) + Idx;
1224         assert(Ln >= 0 && "Bad lane calculation");
1225         unsigned UsersBudget = LookAheadUsersBudget;
1226         for (User *U : V->users()) {
1227           if (const TreeEntry *UserTE = R.getTreeEntry(U)) {
1228             // The user is in the VectorizableTree. Check if we need to insert.
1229             int UserLn = UserTE->findLaneForValue(U);
1230             assert(UserLn >= 0 && "Bad lane");
1231             // If the values are different, check just the line of the current
1232             // value. If the values are the same, need to add UserInDiffLaneCost
1233             // only if UserLn does not match both line numbers.
1234             if ((LHS.first != RHS.first && UserLn != Ln) ||
1235                 (LHS.first == RHS.first && UserLn != LHS.second &&
1236                  UserLn != RHS.second)) {
1237               Cost += UserInDiffLaneCost;
1238               break;
1239             }
1240           } else {
1241             // Check if the user is in the look-ahead code.
1242             auto It2 = InLookAheadValues.find(U);
1243             if (It2 != InLookAheadValues.end()) {
1244               // The user is in the look-ahead code. Check the lane.
1245               if (!It2->getSecond().contains(Ln)) {
1246                 Cost += UserInDiffLaneCost;
1247                 break;
1248               }
1249             } else {
1250               // The user is neither in SLP tree nor in the look-ahead code.
1251               Cost += ExternalUseCost;
1252               break;
1253             }
1254           }
1255           // Limit the number of visited uses to cap compilation time.
1256           if (--UsersBudget == 0)
1257             break;
1258         }
1259       }
1260       return Cost;
1261     }
1262 
1263     /// Go through the operands of \p LHS and \p RHS recursively until \p
1264     /// MaxLevel, and return the cummulative score. For example:
1265     /// \verbatim
1266     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1267     ///     \ /         \ /         \ /        \ /
1268     ///      +           +           +          +
1269     ///     G1          G2          G3         G4
1270     /// \endverbatim
1271     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1272     /// each level recursively, accumulating the score. It starts from matching
1273     /// the additions at level 0, then moves on to the loads (level 1). The
1274     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1275     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1276     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1277     /// Please note that the order of the operands does not matter, as we
1278     /// evaluate the score of all profitable combinations of operands. In
1279     /// other words the score of G1 and G4 is the same as G1 and G2. This
1280     /// heuristic is based on ideas described in:
1281     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1282     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1283     ///   Luís F. W. Góes
1284     int getScoreAtLevelRec(const std::pair<Value *, int> &LHS,
1285                            const std::pair<Value *, int> &RHS, int CurrLevel,
1286                            int MaxLevel) {
1287 
1288       Value *V1 = LHS.first;
1289       Value *V2 = RHS.first;
1290       // Get the shallow score of V1 and V2.
1291       int ShallowScoreAtThisLevel = std::max(
1292           (int)ScoreFail, getShallowScore(V1, V2, DL, SE, getNumLanes()) -
1293                               getExternalUsesCost(LHS, RHS));
1294       int Lane1 = LHS.second;
1295       int Lane2 = RHS.second;
1296 
1297       // If reached MaxLevel,
1298       //  or if V1 and V2 are not instructions,
1299       //  or if they are SPLAT,
1300       //  or if they are not consecutive,
1301       //  or if profitable to vectorize loads or extractelements, early return
1302       //  the current cost.
1303       auto *I1 = dyn_cast<Instruction>(V1);
1304       auto *I2 = dyn_cast<Instruction>(V2);
1305       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1306           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1307           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1308             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1309            ShallowScoreAtThisLevel))
1310         return ShallowScoreAtThisLevel;
1311       assert(I1 && I2 && "Should have early exited.");
1312 
1313       // Keep track of in-tree values for determining the external-use cost.
1314       InLookAheadValues[V1].insert(Lane1);
1315       InLookAheadValues[V2].insert(Lane2);
1316 
1317       // Contains the I2 operand indexes that got matched with I1 operands.
1318       SmallSet<unsigned, 4> Op2Used;
1319 
1320       // Recursion towards the operands of I1 and I2. We are trying all possible
1321       // operand pairs, and keeping track of the best score.
1322       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1323            OpIdx1 != NumOperands1; ++OpIdx1) {
1324         // Try to pair op1I with the best operand of I2.
1325         int MaxTmpScore = 0;
1326         unsigned MaxOpIdx2 = 0;
1327         bool FoundBest = false;
1328         // If I2 is commutative try all combinations.
1329         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1330         unsigned ToIdx = isCommutative(I2)
1331                              ? I2->getNumOperands()
1332                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1333         assert(FromIdx <= ToIdx && "Bad index");
1334         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1335           // Skip operands already paired with OpIdx1.
1336           if (Op2Used.count(OpIdx2))
1337             continue;
1338           // Recursively calculate the cost at each level
1339           int TmpScore = getScoreAtLevelRec({I1->getOperand(OpIdx1), Lane1},
1340                                             {I2->getOperand(OpIdx2), Lane2},
1341                                             CurrLevel + 1, MaxLevel);
1342           // Look for the best score.
1343           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1344             MaxTmpScore = TmpScore;
1345             MaxOpIdx2 = OpIdx2;
1346             FoundBest = true;
1347           }
1348         }
1349         if (FoundBest) {
1350           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1351           Op2Used.insert(MaxOpIdx2);
1352           ShallowScoreAtThisLevel += MaxTmpScore;
1353         }
1354       }
1355       return ShallowScoreAtThisLevel;
1356     }
1357 
1358     /// \Returns the look-ahead score, which tells us how much the sub-trees
1359     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1360     /// score. This helps break ties in an informed way when we cannot decide on
1361     /// the order of the operands by just considering the immediate
1362     /// predecessors.
1363     int getLookAheadScore(const std::pair<Value *, int> &LHS,
1364                           const std::pair<Value *, int> &RHS) {
1365       InLookAheadValues.clear();
1366       return getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth);
1367     }
1368 
1369     // Search all operands in Ops[*][Lane] for the one that matches best
1370     // Ops[OpIdx][LastLane] and return its opreand index.
1371     // If no good match can be found, return None.
1372     Optional<unsigned>
1373     getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1374                    ArrayRef<ReorderingMode> ReorderingModes) {
1375       unsigned NumOperands = getNumOperands();
1376 
1377       // The operand of the previous lane at OpIdx.
1378       Value *OpLastLane = getData(OpIdx, LastLane).V;
1379 
1380       // Our strategy mode for OpIdx.
1381       ReorderingMode RMode = ReorderingModes[OpIdx];
1382 
1383       // The linearized opcode of the operand at OpIdx, Lane.
1384       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1385 
1386       // The best operand index and its score.
1387       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1388       // are using the score to differentiate between the two.
1389       struct BestOpData {
1390         Optional<unsigned> Idx = None;
1391         unsigned Score = 0;
1392       } BestOp;
1393 
1394       // Iterate through all unused operands and look for the best.
1395       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1396         // Get the operand at Idx and Lane.
1397         OperandData &OpData = getData(Idx, Lane);
1398         Value *Op = OpData.V;
1399         bool OpAPO = OpData.APO;
1400 
1401         // Skip already selected operands.
1402         if (OpData.IsUsed)
1403           continue;
1404 
1405         // Skip if we are trying to move the operand to a position with a
1406         // different opcode in the linearized tree form. This would break the
1407         // semantics.
1408         if (OpAPO != OpIdxAPO)
1409           continue;
1410 
1411         // Look for an operand that matches the current mode.
1412         switch (RMode) {
1413         case ReorderingMode::Load:
1414         case ReorderingMode::Constant:
1415         case ReorderingMode::Opcode: {
1416           bool LeftToRight = Lane > LastLane;
1417           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1418           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1419           unsigned Score =
1420               getLookAheadScore({OpLeft, LastLane}, {OpRight, Lane});
1421           if (Score > BestOp.Score) {
1422             BestOp.Idx = Idx;
1423             BestOp.Score = Score;
1424           }
1425           break;
1426         }
1427         case ReorderingMode::Splat:
1428           if (Op == OpLastLane)
1429             BestOp.Idx = Idx;
1430           break;
1431         case ReorderingMode::Failed:
1432           return None;
1433         }
1434       }
1435 
1436       if (BestOp.Idx) {
1437         getData(BestOp.Idx.getValue(), Lane).IsUsed = true;
1438         return BestOp.Idx;
1439       }
1440       // If we could not find a good match return None.
1441       return None;
1442     }
1443 
1444     /// Helper for reorderOperandVecs.
1445     /// \returns the lane that we should start reordering from. This is the one
1446     /// which has the least number of operands that can freely move about or
1447     /// less profitable because it already has the most optimal set of operands.
1448     unsigned getBestLaneToStartReordering() const {
1449       unsigned Min = UINT_MAX;
1450       unsigned SameOpNumber = 0;
1451       // std::pair<unsigned, unsigned> is used to implement a simple voting
1452       // algorithm and choose the lane with the least number of operands that
1453       // can freely move about or less profitable because it already has the
1454       // most optimal set of operands. The first unsigned is a counter for
1455       // voting, the second unsigned is the counter of lanes with instructions
1456       // with same/alternate opcodes and same parent basic block.
1457       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1458       // Try to be closer to the original results, if we have multiple lanes
1459       // with same cost. If 2 lanes have the same cost, use the one with the
1460       // lowest index.
1461       for (int I = getNumLanes(); I > 0; --I) {
1462         unsigned Lane = I - 1;
1463         OperandsOrderData NumFreeOpsHash =
1464             getMaxNumOperandsThatCanBeReordered(Lane);
1465         // Compare the number of operands that can move and choose the one with
1466         // the least number.
1467         if (NumFreeOpsHash.NumOfAPOs < Min) {
1468           Min = NumFreeOpsHash.NumOfAPOs;
1469           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1470           HashMap.clear();
1471           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1472         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1473                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1474           // Select the most optimal lane in terms of number of operands that
1475           // should be moved around.
1476           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1477           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1478         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1479                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1480           auto It = HashMap.find(NumFreeOpsHash.Hash);
1481           if (It == HashMap.end())
1482             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1483           else
1484             ++It->second.first;
1485         }
1486       }
1487       // Select the lane with the minimum counter.
1488       unsigned BestLane = 0;
1489       unsigned CntMin = UINT_MAX;
1490       for (const auto &Data : reverse(HashMap)) {
1491         if (Data.second.first < CntMin) {
1492           CntMin = Data.second.first;
1493           BestLane = Data.second.second;
1494         }
1495       }
1496       return BestLane;
1497     }
1498 
1499     /// Data structure that helps to reorder operands.
1500     struct OperandsOrderData {
1501       /// The best number of operands with the same APOs, which can be
1502       /// reordered.
1503       unsigned NumOfAPOs = UINT_MAX;
1504       /// Number of operands with the same/alternate instruction opcode and
1505       /// parent.
1506       unsigned NumOpsWithSameOpcodeParent = 0;
1507       /// Hash for the actual operands ordering.
1508       /// Used to count operands, actually their position id and opcode
1509       /// value. It is used in the voting mechanism to find the lane with the
1510       /// least number of operands that can freely move about or less profitable
1511       /// because it already has the most optimal set of operands. Can be
1512       /// replaced with SmallVector<unsigned> instead but hash code is faster
1513       /// and requires less memory.
1514       unsigned Hash = 0;
1515     };
1516     /// \returns the maximum number of operands that are allowed to be reordered
1517     /// for \p Lane and the number of compatible instructions(with the same
1518     /// parent/opcode). This is used as a heuristic for selecting the first lane
1519     /// to start operand reordering.
1520     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1521       unsigned CntTrue = 0;
1522       unsigned NumOperands = getNumOperands();
1523       // Operands with the same APO can be reordered. We therefore need to count
1524       // how many of them we have for each APO, like this: Cnt[APO] = x.
1525       // Since we only have two APOs, namely true and false, we can avoid using
1526       // a map. Instead we can simply count the number of operands that
1527       // correspond to one of them (in this case the 'true' APO), and calculate
1528       // the other by subtracting it from the total number of operands.
1529       // Operands with the same instruction opcode and parent are more
1530       // profitable since we don't need to move them in many cases, with a high
1531       // probability such lane already can be vectorized effectively.
1532       bool AllUndefs = true;
1533       unsigned NumOpsWithSameOpcodeParent = 0;
1534       Instruction *OpcodeI = nullptr;
1535       BasicBlock *Parent = nullptr;
1536       unsigned Hash = 0;
1537       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1538         const OperandData &OpData = getData(OpIdx, Lane);
1539         if (OpData.APO)
1540           ++CntTrue;
1541         // Use Boyer-Moore majority voting for finding the majority opcode and
1542         // the number of times it occurs.
1543         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1544           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1545               I->getParent() != Parent) {
1546             if (NumOpsWithSameOpcodeParent == 0) {
1547               NumOpsWithSameOpcodeParent = 1;
1548               OpcodeI = I;
1549               Parent = I->getParent();
1550             } else {
1551               --NumOpsWithSameOpcodeParent;
1552             }
1553           } else {
1554             ++NumOpsWithSameOpcodeParent;
1555           }
1556         }
1557         Hash = hash_combine(
1558             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1559         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1560       }
1561       if (AllUndefs)
1562         return {};
1563       OperandsOrderData Data;
1564       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1565       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1566       Data.Hash = Hash;
1567       return Data;
1568     }
1569 
1570     /// Go through the instructions in VL and append their operands.
1571     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1572       assert(!VL.empty() && "Bad VL");
1573       assert((empty() || VL.size() == getNumLanes()) &&
1574              "Expected same number of lanes");
1575       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1576       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1577       OpsVec.resize(NumOperands);
1578       unsigned NumLanes = VL.size();
1579       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1580         OpsVec[OpIdx].resize(NumLanes);
1581         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1582           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1583           // Our tree has just 3 nodes: the root and two operands.
1584           // It is therefore trivial to get the APO. We only need to check the
1585           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1586           // RHS operand. The LHS operand of both add and sub is never attached
1587           // to an inversese operation in the linearized form, therefore its APO
1588           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1589 
1590           // Since operand reordering is performed on groups of commutative
1591           // operations or alternating sequences (e.g., +, -), we can safely
1592           // tell the inverse operations by checking commutativity.
1593           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1594           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1595           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1596                                  APO, false};
1597         }
1598       }
1599     }
1600 
1601     /// \returns the number of operands.
1602     unsigned getNumOperands() const { return OpsVec.size(); }
1603 
1604     /// \returns the number of lanes.
1605     unsigned getNumLanes() const { return OpsVec[0].size(); }
1606 
1607     /// \returns the operand value at \p OpIdx and \p Lane.
1608     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1609       return getData(OpIdx, Lane).V;
1610     }
1611 
1612     /// \returns true if the data structure is empty.
1613     bool empty() const { return OpsVec.empty(); }
1614 
1615     /// Clears the data.
1616     void clear() { OpsVec.clear(); }
1617 
1618     /// \Returns true if there are enough operands identical to \p Op to fill
1619     /// the whole vector.
1620     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1621     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1622       bool OpAPO = getData(OpIdx, Lane).APO;
1623       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1624         if (Ln == Lane)
1625           continue;
1626         // This is set to true if we found a candidate for broadcast at Lane.
1627         bool FoundCandidate = false;
1628         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1629           OperandData &Data = getData(OpI, Ln);
1630           if (Data.APO != OpAPO || Data.IsUsed)
1631             continue;
1632           if (Data.V == Op) {
1633             FoundCandidate = true;
1634             Data.IsUsed = true;
1635             break;
1636           }
1637         }
1638         if (!FoundCandidate)
1639           return false;
1640       }
1641       return true;
1642     }
1643 
1644   public:
1645     /// Initialize with all the operands of the instruction vector \p RootVL.
1646     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1647                ScalarEvolution &SE, const BoUpSLP &R)
1648         : DL(DL), SE(SE), R(R) {
1649       // Append all the operands of RootVL.
1650       appendOperandsOfVL(RootVL);
1651     }
1652 
1653     /// \Returns a value vector with the operands across all lanes for the
1654     /// opearnd at \p OpIdx.
1655     ValueList getVL(unsigned OpIdx) const {
1656       ValueList OpVL(OpsVec[OpIdx].size());
1657       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1658              "Expected same num of lanes across all operands");
1659       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1660         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1661       return OpVL;
1662     }
1663 
1664     // Performs operand reordering for 2 or more operands.
1665     // The original operands are in OrigOps[OpIdx][Lane].
1666     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1667     void reorder() {
1668       unsigned NumOperands = getNumOperands();
1669       unsigned NumLanes = getNumLanes();
1670       // Each operand has its own mode. We are using this mode to help us select
1671       // the instructions for each lane, so that they match best with the ones
1672       // we have selected so far.
1673       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1674 
1675       // This is a greedy single-pass algorithm. We are going over each lane
1676       // once and deciding on the best order right away with no back-tracking.
1677       // However, in order to increase its effectiveness, we start with the lane
1678       // that has operands that can move the least. For example, given the
1679       // following lanes:
1680       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1681       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1682       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1683       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1684       // we will start at Lane 1, since the operands of the subtraction cannot
1685       // be reordered. Then we will visit the rest of the lanes in a circular
1686       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1687 
1688       // Find the first lane that we will start our search from.
1689       unsigned FirstLane = getBestLaneToStartReordering();
1690 
1691       // Initialize the modes.
1692       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1693         Value *OpLane0 = getValue(OpIdx, FirstLane);
1694         // Keep track if we have instructions with all the same opcode on one
1695         // side.
1696         if (isa<LoadInst>(OpLane0))
1697           ReorderingModes[OpIdx] = ReorderingMode::Load;
1698         else if (isa<Instruction>(OpLane0)) {
1699           // Check if OpLane0 should be broadcast.
1700           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1701             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1702           else
1703             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1704         }
1705         else if (isa<Constant>(OpLane0))
1706           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1707         else if (isa<Argument>(OpLane0))
1708           // Our best hope is a Splat. It may save some cost in some cases.
1709           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1710         else
1711           // NOTE: This should be unreachable.
1712           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1713       }
1714 
1715       // Check that we don't have same operands. No need to reorder if operands
1716       // are just perfect diamond or shuffled diamond match. Do not do it only
1717       // for possible broadcasts or non-power of 2 number of scalars (just for
1718       // now).
1719       auto &&SkipReordering = [this]() {
1720         SmallPtrSet<Value *, 4> UniqueValues;
1721         ArrayRef<OperandData> Op0 = OpsVec.front();
1722         for (const OperandData &Data : Op0)
1723           UniqueValues.insert(Data.V);
1724         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1725           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1726                 return !UniqueValues.contains(Data.V);
1727               }))
1728             return false;
1729         }
1730         // TODO: Check if we can remove a check for non-power-2 number of
1731         // scalars after full support of non-power-2 vectorization.
1732         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1733       };
1734 
1735       // If the initial strategy fails for any of the operand indexes, then we
1736       // perform reordering again in a second pass. This helps avoid assigning
1737       // high priority to the failed strategy, and should improve reordering for
1738       // the non-failed operand indexes.
1739       for (int Pass = 0; Pass != 2; ++Pass) {
1740         // Check if no need to reorder operands since they're are perfect or
1741         // shuffled diamond match.
1742         // Need to to do it to avoid extra external use cost counting for
1743         // shuffled matches, which may cause regressions.
1744         if (SkipReordering())
1745           break;
1746         // Skip the second pass if the first pass did not fail.
1747         bool StrategyFailed = false;
1748         // Mark all operand data as free to use.
1749         clearUsed();
1750         // We keep the original operand order for the FirstLane, so reorder the
1751         // rest of the lanes. We are visiting the nodes in a circular fashion,
1752         // using FirstLane as the center point and increasing the radius
1753         // distance.
1754         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1755           // Visit the lane on the right and then the lane on the left.
1756           for (int Direction : {+1, -1}) {
1757             int Lane = FirstLane + Direction * Distance;
1758             if (Lane < 0 || Lane >= (int)NumLanes)
1759               continue;
1760             int LastLane = Lane - Direction;
1761             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1762                    "Out of bounds");
1763             // Look for a good match for each operand.
1764             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1765               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1766               Optional<unsigned> BestIdx =
1767                   getBestOperand(OpIdx, Lane, LastLane, ReorderingModes);
1768               // By not selecting a value, we allow the operands that follow to
1769               // select a better matching value. We will get a non-null value in
1770               // the next run of getBestOperand().
1771               if (BestIdx) {
1772                 // Swap the current operand with the one returned by
1773                 // getBestOperand().
1774                 swap(OpIdx, BestIdx.getValue(), Lane);
1775               } else {
1776                 // We failed to find a best operand, set mode to 'Failed'.
1777                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1778                 // Enable the second pass.
1779                 StrategyFailed = true;
1780               }
1781             }
1782           }
1783         }
1784         // Skip second pass if the strategy did not fail.
1785         if (!StrategyFailed)
1786           break;
1787       }
1788     }
1789 
1790 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1791     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1792       switch (RMode) {
1793       case ReorderingMode::Load:
1794         return "Load";
1795       case ReorderingMode::Opcode:
1796         return "Opcode";
1797       case ReorderingMode::Constant:
1798         return "Constant";
1799       case ReorderingMode::Splat:
1800         return "Splat";
1801       case ReorderingMode::Failed:
1802         return "Failed";
1803       }
1804       llvm_unreachable("Unimplemented Reordering Type");
1805     }
1806 
1807     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1808                                                    raw_ostream &OS) {
1809       return OS << getModeStr(RMode);
1810     }
1811 
1812     /// Debug print.
1813     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1814       printMode(RMode, dbgs());
1815     }
1816 
1817     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1818       return printMode(RMode, OS);
1819     }
1820 
1821     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1822       const unsigned Indent = 2;
1823       unsigned Cnt = 0;
1824       for (const OperandDataVec &OpDataVec : OpsVec) {
1825         OS << "Operand " << Cnt++ << "\n";
1826         for (const OperandData &OpData : OpDataVec) {
1827           OS.indent(Indent) << "{";
1828           if (Value *V = OpData.V)
1829             OS << *V;
1830           else
1831             OS << "null";
1832           OS << ", APO:" << OpData.APO << "}\n";
1833         }
1834         OS << "\n";
1835       }
1836       return OS;
1837     }
1838 
1839     /// Debug print.
1840     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1841 #endif
1842   };
1843 
1844   /// Checks if the instruction is marked for deletion.
1845   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1846 
1847   /// Marks values operands for later deletion by replacing them with Undefs.
1848   void eraseInstructions(ArrayRef<Value *> AV);
1849 
1850   ~BoUpSLP();
1851 
1852 private:
1853   /// Checks if all users of \p I are the part of the vectorization tree.
1854   bool areAllUsersVectorized(Instruction *I,
1855                              ArrayRef<Value *> VectorizedVals) const;
1856 
1857   /// \returns the cost of the vectorizable entry.
1858   InstructionCost getEntryCost(const TreeEntry *E,
1859                                ArrayRef<Value *> VectorizedVals);
1860 
1861   /// This is the recursive part of buildTree.
1862   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1863                      const EdgeInfo &EI);
1864 
1865   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1866   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1867   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1868   /// returns false, setting \p CurrentOrder to either an empty vector or a
1869   /// non-identity permutation that allows to reuse extract instructions.
1870   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1871                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1872 
1873   /// Vectorize a single entry in the tree.
1874   Value *vectorizeTree(TreeEntry *E);
1875 
1876   /// Vectorize a single entry in the tree, starting in \p VL.
1877   Value *vectorizeTree(ArrayRef<Value *> VL);
1878 
1879   /// \returns the scalarization cost for this type. Scalarization in this
1880   /// context means the creation of vectors from a group of scalars. If \p
1881   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1882   /// vector elements.
1883   InstructionCost getGatherCost(FixedVectorType *Ty,
1884                                 const DenseSet<unsigned> &ShuffledIndices,
1885                                 bool NeedToShuffle) const;
1886 
1887   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1888   /// tree entries.
1889   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1890   /// previous tree entries. \p Mask is filled with the shuffle mask.
1891   Optional<TargetTransformInfo::ShuffleKind>
1892   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1893                         SmallVectorImpl<const TreeEntry *> &Entries);
1894 
1895   /// \returns the scalarization cost for this list of values. Assuming that
1896   /// this subtree gets vectorized, we may need to extract the values from the
1897   /// roots. This method calculates the cost of extracting the values.
1898   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1899 
1900   /// Set the Builder insert point to one after the last instruction in
1901   /// the bundle
1902   void setInsertPointAfterBundle(const TreeEntry *E);
1903 
1904   /// \returns a vector from a collection of scalars in \p VL.
1905   Value *gather(ArrayRef<Value *> VL);
1906 
1907   /// \returns whether the VectorizableTree is fully vectorizable and will
1908   /// be beneficial even the tree height is tiny.
1909   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1910 
1911   /// Reorder commutative or alt operands to get better probability of
1912   /// generating vectorized code.
1913   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1914                                              SmallVectorImpl<Value *> &Left,
1915                                              SmallVectorImpl<Value *> &Right,
1916                                              const DataLayout &DL,
1917                                              ScalarEvolution &SE,
1918                                              const BoUpSLP &R);
1919   struct TreeEntry {
1920     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1921     TreeEntry(VecTreeTy &Container) : Container(Container) {}
1922 
1923     /// \returns true if the scalars in VL are equal to this entry.
1924     bool isSame(ArrayRef<Value *> VL) const {
1925       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
1926         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
1927           return std::equal(VL.begin(), VL.end(), Scalars.begin());
1928         return VL.size() == Mask.size() &&
1929                std::equal(VL.begin(), VL.end(), Mask.begin(),
1930                           [Scalars](Value *V, int Idx) {
1931                             return (isa<UndefValue>(V) &&
1932                                     Idx == UndefMaskElem) ||
1933                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
1934                           });
1935       };
1936       if (!ReorderIndices.empty()) {
1937         // TODO: implement matching if the nodes are just reordered, still can
1938         // treat the vector as the same if the list of scalars matches VL
1939         // directly, without reordering.
1940         SmallVector<int> Mask;
1941         inversePermutation(ReorderIndices, Mask);
1942         if (VL.size() == Scalars.size())
1943           return IsSame(Scalars, Mask);
1944         if (VL.size() == ReuseShuffleIndices.size()) {
1945           ::addMask(Mask, ReuseShuffleIndices);
1946           return IsSame(Scalars, Mask);
1947         }
1948         return false;
1949       }
1950       return IsSame(Scalars, ReuseShuffleIndices);
1951     }
1952 
1953     /// \returns true if current entry has same operands as \p TE.
1954     bool hasEqualOperands(const TreeEntry &TE) const {
1955       if (TE.getNumOperands() != getNumOperands())
1956         return false;
1957       SmallBitVector Used(getNumOperands());
1958       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
1959         unsigned PrevCount = Used.count();
1960         for (unsigned K = 0; K < E; ++K) {
1961           if (Used.test(K))
1962             continue;
1963           if (getOperand(K) == TE.getOperand(I)) {
1964             Used.set(K);
1965             break;
1966           }
1967         }
1968         // Check if we actually found the matching operand.
1969         if (PrevCount == Used.count())
1970           return false;
1971       }
1972       return true;
1973     }
1974 
1975     /// \return Final vectorization factor for the node. Defined by the total
1976     /// number of vectorized scalars, including those, used several times in the
1977     /// entry and counted in the \a ReuseShuffleIndices, if any.
1978     unsigned getVectorFactor() const {
1979       if (!ReuseShuffleIndices.empty())
1980         return ReuseShuffleIndices.size();
1981       return Scalars.size();
1982     };
1983 
1984     /// A vector of scalars.
1985     ValueList Scalars;
1986 
1987     /// The Scalars are vectorized into this value. It is initialized to Null.
1988     Value *VectorizedValue = nullptr;
1989 
1990     /// Do we need to gather this sequence or vectorize it
1991     /// (either with vector instruction or with scatter/gather
1992     /// intrinsics for store/load)?
1993     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
1994     EntryState State;
1995 
1996     /// Does this sequence require some shuffling?
1997     SmallVector<int, 4> ReuseShuffleIndices;
1998 
1999     /// Does this entry require reordering?
2000     SmallVector<unsigned, 4> ReorderIndices;
2001 
2002     /// Points back to the VectorizableTree.
2003     ///
2004     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2005     /// to be a pointer and needs to be able to initialize the child iterator.
2006     /// Thus we need a reference back to the container to translate the indices
2007     /// to entries.
2008     VecTreeTy &Container;
2009 
2010     /// The TreeEntry index containing the user of this entry.  We can actually
2011     /// have multiple users so the data structure is not truly a tree.
2012     SmallVector<EdgeInfo, 1> UserTreeIndices;
2013 
2014     /// The index of this treeEntry in VectorizableTree.
2015     int Idx = -1;
2016 
2017   private:
2018     /// The operands of each instruction in each lane Operands[op_index][lane].
2019     /// Note: This helps avoid the replication of the code that performs the
2020     /// reordering of operands during buildTree_rec() and vectorizeTree().
2021     SmallVector<ValueList, 2> Operands;
2022 
2023     /// The main/alternate instruction.
2024     Instruction *MainOp = nullptr;
2025     Instruction *AltOp = nullptr;
2026 
2027   public:
2028     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2029     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2030       if (Operands.size() < OpIdx + 1)
2031         Operands.resize(OpIdx + 1);
2032       assert(Operands[OpIdx].empty() && "Already resized?");
2033       assert(OpVL.size() <= Scalars.size() &&
2034              "Number of operands is greater than the number of scalars.");
2035       Operands[OpIdx].resize(OpVL.size());
2036       copy(OpVL, Operands[OpIdx].begin());
2037     }
2038 
2039     /// Set the operands of this bundle in their original order.
2040     void setOperandsInOrder() {
2041       assert(Operands.empty() && "Already initialized?");
2042       auto *I0 = cast<Instruction>(Scalars[0]);
2043       Operands.resize(I0->getNumOperands());
2044       unsigned NumLanes = Scalars.size();
2045       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2046            OpIdx != NumOperands; ++OpIdx) {
2047         Operands[OpIdx].resize(NumLanes);
2048         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2049           auto *I = cast<Instruction>(Scalars[Lane]);
2050           assert(I->getNumOperands() == NumOperands &&
2051                  "Expected same number of operands");
2052           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2053         }
2054       }
2055     }
2056 
2057     /// Reorders operands of the node to the given mask \p Mask.
2058     void reorderOperands(ArrayRef<int> Mask) {
2059       for (ValueList &Operand : Operands)
2060         reorderScalars(Operand, Mask);
2061     }
2062 
2063     /// \returns the \p OpIdx operand of this TreeEntry.
2064     ValueList &getOperand(unsigned OpIdx) {
2065       assert(OpIdx < Operands.size() && "Off bounds");
2066       return Operands[OpIdx];
2067     }
2068 
2069     /// \returns the \p OpIdx operand of this TreeEntry.
2070     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2071       assert(OpIdx < Operands.size() && "Off bounds");
2072       return Operands[OpIdx];
2073     }
2074 
2075     /// \returns the number of operands.
2076     unsigned getNumOperands() const { return Operands.size(); }
2077 
2078     /// \return the single \p OpIdx operand.
2079     Value *getSingleOperand(unsigned OpIdx) const {
2080       assert(OpIdx < Operands.size() && "Off bounds");
2081       assert(!Operands[OpIdx].empty() && "No operand available");
2082       return Operands[OpIdx][0];
2083     }
2084 
2085     /// Some of the instructions in the list have alternate opcodes.
2086     bool isAltShuffle() const { return MainOp != AltOp; }
2087 
2088     bool isOpcodeOrAlt(Instruction *I) const {
2089       unsigned CheckedOpcode = I->getOpcode();
2090       return (getOpcode() == CheckedOpcode ||
2091               getAltOpcode() == CheckedOpcode);
2092     }
2093 
2094     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2095     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2096     /// \p OpValue.
2097     Value *isOneOf(Value *Op) const {
2098       auto *I = dyn_cast<Instruction>(Op);
2099       if (I && isOpcodeOrAlt(I))
2100         return Op;
2101       return MainOp;
2102     }
2103 
2104     void setOperations(const InstructionsState &S) {
2105       MainOp = S.MainOp;
2106       AltOp = S.AltOp;
2107     }
2108 
2109     Instruction *getMainOp() const {
2110       return MainOp;
2111     }
2112 
2113     Instruction *getAltOp() const {
2114       return AltOp;
2115     }
2116 
2117     /// The main/alternate opcodes for the list of instructions.
2118     unsigned getOpcode() const {
2119       return MainOp ? MainOp->getOpcode() : 0;
2120     }
2121 
2122     unsigned getAltOpcode() const {
2123       return AltOp ? AltOp->getOpcode() : 0;
2124     }
2125 
2126     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2127     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2128     int findLaneForValue(Value *V) const {
2129       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2130       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2131       if (!ReorderIndices.empty())
2132         FoundLane = ReorderIndices[FoundLane];
2133       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2134       if (!ReuseShuffleIndices.empty()) {
2135         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2136                                   find(ReuseShuffleIndices, FoundLane));
2137       }
2138       return FoundLane;
2139     }
2140 
2141 #ifndef NDEBUG
2142     /// Debug printer.
2143     LLVM_DUMP_METHOD void dump() const {
2144       dbgs() << Idx << ".\n";
2145       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2146         dbgs() << "Operand " << OpI << ":\n";
2147         for (const Value *V : Operands[OpI])
2148           dbgs().indent(2) << *V << "\n";
2149       }
2150       dbgs() << "Scalars: \n";
2151       for (Value *V : Scalars)
2152         dbgs().indent(2) << *V << "\n";
2153       dbgs() << "State: ";
2154       switch (State) {
2155       case Vectorize:
2156         dbgs() << "Vectorize\n";
2157         break;
2158       case ScatterVectorize:
2159         dbgs() << "ScatterVectorize\n";
2160         break;
2161       case NeedToGather:
2162         dbgs() << "NeedToGather\n";
2163         break;
2164       }
2165       dbgs() << "MainOp: ";
2166       if (MainOp)
2167         dbgs() << *MainOp << "\n";
2168       else
2169         dbgs() << "NULL\n";
2170       dbgs() << "AltOp: ";
2171       if (AltOp)
2172         dbgs() << *AltOp << "\n";
2173       else
2174         dbgs() << "NULL\n";
2175       dbgs() << "VectorizedValue: ";
2176       if (VectorizedValue)
2177         dbgs() << *VectorizedValue << "\n";
2178       else
2179         dbgs() << "NULL\n";
2180       dbgs() << "ReuseShuffleIndices: ";
2181       if (ReuseShuffleIndices.empty())
2182         dbgs() << "Empty";
2183       else
2184         for (int ReuseIdx : ReuseShuffleIndices)
2185           dbgs() << ReuseIdx << ", ";
2186       dbgs() << "\n";
2187       dbgs() << "ReorderIndices: ";
2188       for (unsigned ReorderIdx : ReorderIndices)
2189         dbgs() << ReorderIdx << ", ";
2190       dbgs() << "\n";
2191       dbgs() << "UserTreeIndices: ";
2192       for (const auto &EInfo : UserTreeIndices)
2193         dbgs() << EInfo << ", ";
2194       dbgs() << "\n";
2195     }
2196 #endif
2197   };
2198 
2199 #ifndef NDEBUG
2200   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2201                      InstructionCost VecCost,
2202                      InstructionCost ScalarCost) const {
2203     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2204     dbgs() << "SLP: Costs:\n";
2205     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2206     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2207     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2208     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2209                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2210   }
2211 #endif
2212 
2213   /// Create a new VectorizableTree entry.
2214   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2215                           const InstructionsState &S,
2216                           const EdgeInfo &UserTreeIdx,
2217                           ArrayRef<int> ReuseShuffleIndices = None,
2218                           ArrayRef<unsigned> ReorderIndices = None) {
2219     TreeEntry::EntryState EntryState =
2220         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2221     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2222                         ReuseShuffleIndices, ReorderIndices);
2223   }
2224 
2225   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2226                           TreeEntry::EntryState EntryState,
2227                           Optional<ScheduleData *> Bundle,
2228                           const InstructionsState &S,
2229                           const EdgeInfo &UserTreeIdx,
2230                           ArrayRef<int> ReuseShuffleIndices = None,
2231                           ArrayRef<unsigned> ReorderIndices = None) {
2232     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2233             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2234            "Need to vectorize gather entry?");
2235     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2236     TreeEntry *Last = VectorizableTree.back().get();
2237     Last->Idx = VectorizableTree.size() - 1;
2238     Last->State = EntryState;
2239     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2240                                      ReuseShuffleIndices.end());
2241     if (ReorderIndices.empty()) {
2242       Last->Scalars.assign(VL.begin(), VL.end());
2243       Last->setOperations(S);
2244     } else {
2245       // Reorder scalars and build final mask.
2246       Last->Scalars.assign(VL.size(), nullptr);
2247       transform(ReorderIndices, Last->Scalars.begin(),
2248                 [VL](unsigned Idx) -> Value * {
2249                   if (Idx >= VL.size())
2250                     return UndefValue::get(VL.front()->getType());
2251                   return VL[Idx];
2252                 });
2253       InstructionsState S = getSameOpcode(Last->Scalars);
2254       Last->setOperations(S);
2255       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2256     }
2257     if (Last->State != TreeEntry::NeedToGather) {
2258       for (Value *V : VL) {
2259         assert(!getTreeEntry(V) && "Scalar already in tree!");
2260         ScalarToTreeEntry[V] = Last;
2261       }
2262       // Update the scheduler bundle to point to this TreeEntry.
2263       unsigned Lane = 0;
2264       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2265            BundleMember = BundleMember->NextInBundle) {
2266         BundleMember->TE = Last;
2267         BundleMember->Lane = Lane;
2268         ++Lane;
2269       }
2270       assert((!Bundle.getValue() || Lane == VL.size()) &&
2271              "Bundle and VL out of sync");
2272     } else {
2273       MustGather.insert(VL.begin(), VL.end());
2274     }
2275 
2276     if (UserTreeIdx.UserTE)
2277       Last->UserTreeIndices.push_back(UserTreeIdx);
2278 
2279     return Last;
2280   }
2281 
2282   /// -- Vectorization State --
2283   /// Holds all of the tree entries.
2284   TreeEntry::VecTreeTy VectorizableTree;
2285 
2286 #ifndef NDEBUG
2287   /// Debug printer.
2288   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2289     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2290       VectorizableTree[Id]->dump();
2291       dbgs() << "\n";
2292     }
2293   }
2294 #endif
2295 
2296   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2297 
2298   const TreeEntry *getTreeEntry(Value *V) const {
2299     return ScalarToTreeEntry.lookup(V);
2300   }
2301 
2302   /// Maps a specific scalar to its tree entry.
2303   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2304 
2305   /// Maps a value to the proposed vectorizable size.
2306   SmallDenseMap<Value *, unsigned> InstrElementSize;
2307 
2308   /// A list of scalars that we found that we need to keep as scalars.
2309   ValueSet MustGather;
2310 
2311   /// This POD struct describes one external user in the vectorized tree.
2312   struct ExternalUser {
2313     ExternalUser(Value *S, llvm::User *U, int L)
2314         : Scalar(S), User(U), Lane(L) {}
2315 
2316     // Which scalar in our function.
2317     Value *Scalar;
2318 
2319     // Which user that uses the scalar.
2320     llvm::User *User;
2321 
2322     // Which lane does the scalar belong to.
2323     int Lane;
2324   };
2325   using UserList = SmallVector<ExternalUser, 16>;
2326 
2327   /// Checks if two instructions may access the same memory.
2328   ///
2329   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2330   /// is invariant in the calling loop.
2331   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2332                  Instruction *Inst2) {
2333     // First check if the result is already in the cache.
2334     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2335     Optional<bool> &result = AliasCache[key];
2336     if (result.hasValue()) {
2337       return result.getValue();
2338     }
2339     bool aliased = true;
2340     if (Loc1.Ptr && isSimple(Inst1))
2341       aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
2342     // Store the result in the cache.
2343     result = aliased;
2344     return aliased;
2345   }
2346 
2347   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2348 
2349   /// Cache for alias results.
2350   /// TODO: consider moving this to the AliasAnalysis itself.
2351   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2352 
2353   /// Removes an instruction from its block and eventually deletes it.
2354   /// It's like Instruction::eraseFromParent() except that the actual deletion
2355   /// is delayed until BoUpSLP is destructed.
2356   /// This is required to ensure that there are no incorrect collisions in the
2357   /// AliasCache, which can happen if a new instruction is allocated at the
2358   /// same address as a previously deleted instruction.
2359   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2360     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2361     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2362   }
2363 
2364   /// Temporary store for deleted instructions. Instructions will be deleted
2365   /// eventually when the BoUpSLP is destructed.
2366   DenseMap<Instruction *, bool> DeletedInstructions;
2367 
2368   /// A list of values that need to extracted out of the tree.
2369   /// This list holds pairs of (Internal Scalar : External User). External User
2370   /// can be nullptr, it means that this Internal Scalar will be used later,
2371   /// after vectorization.
2372   UserList ExternalUses;
2373 
2374   /// Values used only by @llvm.assume calls.
2375   SmallPtrSet<const Value *, 32> EphValues;
2376 
2377   /// Holds all of the instructions that we gathered.
2378   SetVector<Instruction *> GatherShuffleSeq;
2379 
2380   /// A list of blocks that we are going to CSE.
2381   SetVector<BasicBlock *> CSEBlocks;
2382 
2383   /// Contains all scheduling relevant data for an instruction.
2384   /// A ScheduleData either represents a single instruction or a member of an
2385   /// instruction bundle (= a group of instructions which is combined into a
2386   /// vector instruction).
2387   struct ScheduleData {
2388     // The initial value for the dependency counters. It means that the
2389     // dependencies are not calculated yet.
2390     enum { InvalidDeps = -1 };
2391 
2392     ScheduleData() = default;
2393 
2394     void init(int BlockSchedulingRegionID, Value *OpVal) {
2395       FirstInBundle = this;
2396       NextInBundle = nullptr;
2397       NextLoadStore = nullptr;
2398       IsScheduled = false;
2399       SchedulingRegionID = BlockSchedulingRegionID;
2400       UnscheduledDepsInBundle = UnscheduledDeps;
2401       clearDependencies();
2402       OpValue = OpVal;
2403       TE = nullptr;
2404       Lane = -1;
2405     }
2406 
2407     /// Returns true if the dependency information has been calculated.
2408     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2409 
2410     /// Returns true for single instructions and for bundle representatives
2411     /// (= the head of a bundle).
2412     bool isSchedulingEntity() const { return FirstInBundle == this; }
2413 
2414     /// Returns true if it represents an instruction bundle and not only a
2415     /// single instruction.
2416     bool isPartOfBundle() const {
2417       return NextInBundle != nullptr || FirstInBundle != this;
2418     }
2419 
2420     /// Returns true if it is ready for scheduling, i.e. it has no more
2421     /// unscheduled depending instructions/bundles.
2422     bool isReady() const {
2423       assert(isSchedulingEntity() &&
2424              "can't consider non-scheduling entity for ready list");
2425       return UnscheduledDepsInBundle == 0 && !IsScheduled;
2426     }
2427 
2428     /// Modifies the number of unscheduled dependencies, also updating it for
2429     /// the whole bundle.
2430     int incrementUnscheduledDeps(int Incr) {
2431       UnscheduledDeps += Incr;
2432       return FirstInBundle->UnscheduledDepsInBundle += Incr;
2433     }
2434 
2435     /// Sets the number of unscheduled dependencies to the number of
2436     /// dependencies.
2437     void resetUnscheduledDeps() {
2438       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
2439     }
2440 
2441     /// Clears all dependency information.
2442     void clearDependencies() {
2443       Dependencies = InvalidDeps;
2444       resetUnscheduledDeps();
2445       MemoryDependencies.clear();
2446     }
2447 
2448     void dump(raw_ostream &os) const {
2449       if (!isSchedulingEntity()) {
2450         os << "/ " << *Inst;
2451       } else if (NextInBundle) {
2452         os << '[' << *Inst;
2453         ScheduleData *SD = NextInBundle;
2454         while (SD) {
2455           os << ';' << *SD->Inst;
2456           SD = SD->NextInBundle;
2457         }
2458         os << ']';
2459       } else {
2460         os << *Inst;
2461       }
2462     }
2463 
2464     Instruction *Inst = nullptr;
2465 
2466     /// Points to the head in an instruction bundle (and always to this for
2467     /// single instructions).
2468     ScheduleData *FirstInBundle = nullptr;
2469 
2470     /// Single linked list of all instructions in a bundle. Null if it is a
2471     /// single instruction.
2472     ScheduleData *NextInBundle = nullptr;
2473 
2474     /// Single linked list of all memory instructions (e.g. load, store, call)
2475     /// in the block - until the end of the scheduling region.
2476     ScheduleData *NextLoadStore = nullptr;
2477 
2478     /// The dependent memory instructions.
2479     /// This list is derived on demand in calculateDependencies().
2480     SmallVector<ScheduleData *, 4> MemoryDependencies;
2481 
2482     /// This ScheduleData is in the current scheduling region if this matches
2483     /// the current SchedulingRegionID of BlockScheduling.
2484     int SchedulingRegionID = 0;
2485 
2486     /// Used for getting a "good" final ordering of instructions.
2487     int SchedulingPriority = 0;
2488 
2489     /// The number of dependencies. Constitutes of the number of users of the
2490     /// instruction plus the number of dependent memory instructions (if any).
2491     /// This value is calculated on demand.
2492     /// If InvalidDeps, the number of dependencies is not calculated yet.
2493     int Dependencies = InvalidDeps;
2494 
2495     /// The number of dependencies minus the number of dependencies of scheduled
2496     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2497     /// for scheduling.
2498     /// Note that this is negative as long as Dependencies is not calculated.
2499     int UnscheduledDeps = InvalidDeps;
2500 
2501     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
2502     /// single instructions.
2503     int UnscheduledDepsInBundle = InvalidDeps;
2504 
2505     /// True if this instruction is scheduled (or considered as scheduled in the
2506     /// dry-run).
2507     bool IsScheduled = false;
2508 
2509     /// Opcode of the current instruction in the schedule data.
2510     Value *OpValue = nullptr;
2511 
2512     /// The TreeEntry that this instruction corresponds to.
2513     TreeEntry *TE = nullptr;
2514 
2515     /// The lane of this node in the TreeEntry.
2516     int Lane = -1;
2517   };
2518 
2519 #ifndef NDEBUG
2520   friend inline raw_ostream &operator<<(raw_ostream &os,
2521                                         const BoUpSLP::ScheduleData &SD) {
2522     SD.dump(os);
2523     return os;
2524   }
2525 #endif
2526 
2527   friend struct GraphTraits<BoUpSLP *>;
2528   friend struct DOTGraphTraits<BoUpSLP *>;
2529 
2530   /// Contains all scheduling data for a basic block.
2531   struct BlockScheduling {
2532     BlockScheduling(BasicBlock *BB)
2533         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2534 
2535     void clear() {
2536       ReadyInsts.clear();
2537       ScheduleStart = nullptr;
2538       ScheduleEnd = nullptr;
2539       FirstLoadStoreInRegion = nullptr;
2540       LastLoadStoreInRegion = nullptr;
2541 
2542       // Reduce the maximum schedule region size by the size of the
2543       // previous scheduling run.
2544       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2545       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2546         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2547       ScheduleRegionSize = 0;
2548 
2549       // Make a new scheduling region, i.e. all existing ScheduleData is not
2550       // in the new region yet.
2551       ++SchedulingRegionID;
2552     }
2553 
2554     ScheduleData *getScheduleData(Value *V) {
2555       ScheduleData *SD = ScheduleDataMap[V];
2556       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2557         return SD;
2558       return nullptr;
2559     }
2560 
2561     ScheduleData *getScheduleData(Value *V, Value *Key) {
2562       if (V == Key)
2563         return getScheduleData(V);
2564       auto I = ExtraScheduleDataMap.find(V);
2565       if (I != ExtraScheduleDataMap.end()) {
2566         ScheduleData *SD = I->second[Key];
2567         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2568           return SD;
2569       }
2570       return nullptr;
2571     }
2572 
2573     bool isInSchedulingRegion(ScheduleData *SD) const {
2574       return SD->SchedulingRegionID == SchedulingRegionID;
2575     }
2576 
2577     /// Marks an instruction as scheduled and puts all dependent ready
2578     /// instructions into the ready-list.
2579     template <typename ReadyListType>
2580     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2581       SD->IsScheduled = true;
2582       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2583 
2584       for (ScheduleData *BundleMember = SD; BundleMember;
2585            BundleMember = BundleMember->NextInBundle) {
2586         if (BundleMember->Inst != BundleMember->OpValue)
2587           continue;
2588 
2589         // Handle the def-use chain dependencies.
2590 
2591         // Decrement the unscheduled counter and insert to ready list if ready.
2592         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2593           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2594             if (OpDef && OpDef->hasValidDependencies() &&
2595                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2596               // There are no more unscheduled dependencies after
2597               // decrementing, so we can put the dependent instruction
2598               // into the ready list.
2599               ScheduleData *DepBundle = OpDef->FirstInBundle;
2600               assert(!DepBundle->IsScheduled &&
2601                      "already scheduled bundle gets ready");
2602               ReadyList.insert(DepBundle);
2603               LLVM_DEBUG(dbgs()
2604                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2605             }
2606           });
2607         };
2608 
2609         // If BundleMember is a vector bundle, its operands may have been
2610         // reordered duiring buildTree(). We therefore need to get its operands
2611         // through the TreeEntry.
2612         if (TreeEntry *TE = BundleMember->TE) {
2613           int Lane = BundleMember->Lane;
2614           assert(Lane >= 0 && "Lane not set");
2615 
2616           // Since vectorization tree is being built recursively this assertion
2617           // ensures that the tree entry has all operands set before reaching
2618           // this code. Couple of exceptions known at the moment are extracts
2619           // where their second (immediate) operand is not added. Since
2620           // immediates do not affect scheduler behavior this is considered
2621           // okay.
2622           auto *In = TE->getMainOp();
2623           assert(In &&
2624                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2625                   In->getNumOperands() == TE->getNumOperands()) &&
2626                  "Missed TreeEntry operands?");
2627           (void)In; // fake use to avoid build failure when assertions disabled
2628 
2629           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2630                OpIdx != NumOperands; ++OpIdx)
2631             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2632               DecrUnsched(I);
2633         } else {
2634           // If BundleMember is a stand-alone instruction, no operand reordering
2635           // has taken place, so we directly access its operands.
2636           for (Use &U : BundleMember->Inst->operands())
2637             if (auto *I = dyn_cast<Instruction>(U.get()))
2638               DecrUnsched(I);
2639         }
2640         // Handle the memory dependencies.
2641         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2642           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2643             // There are no more unscheduled dependencies after decrementing,
2644             // so we can put the dependent instruction into the ready list.
2645             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2646             assert(!DepBundle->IsScheduled &&
2647                    "already scheduled bundle gets ready");
2648             ReadyList.insert(DepBundle);
2649             LLVM_DEBUG(dbgs()
2650                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2651           }
2652         }
2653       }
2654     }
2655 
2656     void doForAllOpcodes(Value *V,
2657                          function_ref<void(ScheduleData *SD)> Action) {
2658       if (ScheduleData *SD = getScheduleData(V))
2659         Action(SD);
2660       auto I = ExtraScheduleDataMap.find(V);
2661       if (I != ExtraScheduleDataMap.end())
2662         for (auto &P : I->second)
2663           if (P.second->SchedulingRegionID == SchedulingRegionID)
2664             Action(P.second);
2665     }
2666 
2667     /// Put all instructions into the ReadyList which are ready for scheduling.
2668     template <typename ReadyListType>
2669     void initialFillReadyList(ReadyListType &ReadyList) {
2670       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2671         doForAllOpcodes(I, [&](ScheduleData *SD) {
2672           if (SD->isSchedulingEntity() && SD->isReady()) {
2673             ReadyList.insert(SD);
2674             LLVM_DEBUG(dbgs()
2675                        << "SLP:    initially in ready list: " << *I << "\n");
2676           }
2677         });
2678       }
2679     }
2680 
2681     /// Build a bundle from the ScheduleData nodes corresponding to the
2682     /// scalar instruction for each lane.
2683     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2684 
2685     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2686     /// cyclic dependencies. This is only a dry-run, no instructions are
2687     /// actually moved at this stage.
2688     /// \returns the scheduling bundle. The returned Optional value is non-None
2689     /// if \p VL is allowed to be scheduled.
2690     Optional<ScheduleData *>
2691     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2692                       const InstructionsState &S);
2693 
2694     /// Un-bundles a group of instructions.
2695     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2696 
2697     /// Allocates schedule data chunk.
2698     ScheduleData *allocateScheduleDataChunks();
2699 
2700     /// Extends the scheduling region so that V is inside the region.
2701     /// \returns true if the region size is within the limit.
2702     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2703 
2704     /// Initialize the ScheduleData structures for new instructions in the
2705     /// scheduling region.
2706     void initScheduleData(Instruction *FromI, Instruction *ToI,
2707                           ScheduleData *PrevLoadStore,
2708                           ScheduleData *NextLoadStore);
2709 
2710     /// Updates the dependency information of a bundle and of all instructions/
2711     /// bundles which depend on the original bundle.
2712     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2713                                BoUpSLP *SLP);
2714 
2715     /// Sets all instruction in the scheduling region to un-scheduled.
2716     void resetSchedule();
2717 
2718     BasicBlock *BB;
2719 
2720     /// Simple memory allocation for ScheduleData.
2721     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2722 
2723     /// The size of a ScheduleData array in ScheduleDataChunks.
2724     int ChunkSize;
2725 
2726     /// The allocator position in the current chunk, which is the last entry
2727     /// of ScheduleDataChunks.
2728     int ChunkPos;
2729 
2730     /// Attaches ScheduleData to Instruction.
2731     /// Note that the mapping survives during all vectorization iterations, i.e.
2732     /// ScheduleData structures are recycled.
2733     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2734 
2735     /// Attaches ScheduleData to Instruction with the leading key.
2736     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2737         ExtraScheduleDataMap;
2738 
2739     struct ReadyList : SmallVector<ScheduleData *, 8> {
2740       void insert(ScheduleData *SD) { push_back(SD); }
2741     };
2742 
2743     /// The ready-list for scheduling (only used for the dry-run).
2744     ReadyList ReadyInsts;
2745 
2746     /// The first instruction of the scheduling region.
2747     Instruction *ScheduleStart = nullptr;
2748 
2749     /// The first instruction _after_ the scheduling region.
2750     Instruction *ScheduleEnd = nullptr;
2751 
2752     /// The first memory accessing instruction in the scheduling region
2753     /// (can be null).
2754     ScheduleData *FirstLoadStoreInRegion = nullptr;
2755 
2756     /// The last memory accessing instruction in the scheduling region
2757     /// (can be null).
2758     ScheduleData *LastLoadStoreInRegion = nullptr;
2759 
2760     /// The current size of the scheduling region.
2761     int ScheduleRegionSize = 0;
2762 
2763     /// The maximum size allowed for the scheduling region.
2764     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2765 
2766     /// The ID of the scheduling region. For a new vectorization iteration this
2767     /// is incremented which "removes" all ScheduleData from the region.
2768     // Make sure that the initial SchedulingRegionID is greater than the
2769     // initial SchedulingRegionID in ScheduleData (which is 0).
2770     int SchedulingRegionID = 1;
2771   };
2772 
2773   /// Attaches the BlockScheduling structures to basic blocks.
2774   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2775 
2776   /// Performs the "real" scheduling. Done before vectorization is actually
2777   /// performed in a basic block.
2778   void scheduleBlock(BlockScheduling *BS);
2779 
2780   /// List of users to ignore during scheduling and that don't need extracting.
2781   ArrayRef<Value *> UserIgnoreList;
2782 
2783   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2784   /// sorted SmallVectors of unsigned.
2785   struct OrdersTypeDenseMapInfo {
2786     static OrdersType getEmptyKey() {
2787       OrdersType V;
2788       V.push_back(~1U);
2789       return V;
2790     }
2791 
2792     static OrdersType getTombstoneKey() {
2793       OrdersType V;
2794       V.push_back(~2U);
2795       return V;
2796     }
2797 
2798     static unsigned getHashValue(const OrdersType &V) {
2799       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2800     }
2801 
2802     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2803       return LHS == RHS;
2804     }
2805   };
2806 
2807   // Analysis and block reference.
2808   Function *F;
2809   ScalarEvolution *SE;
2810   TargetTransformInfo *TTI;
2811   TargetLibraryInfo *TLI;
2812   AAResults *AA;
2813   LoopInfo *LI;
2814   DominatorTree *DT;
2815   AssumptionCache *AC;
2816   DemandedBits *DB;
2817   const DataLayout *DL;
2818   OptimizationRemarkEmitter *ORE;
2819 
2820   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2821   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2822 
2823   /// Instruction builder to construct the vectorized tree.
2824   IRBuilder<> Builder;
2825 
2826   /// A map of scalar integer values to the smallest bit width with which they
2827   /// can legally be represented. The values map to (width, signed) pairs,
2828   /// where "width" indicates the minimum bit width and "signed" is True if the
2829   /// value must be signed-extended, rather than zero-extended, back to its
2830   /// original width.
2831   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2832 };
2833 
2834 } // end namespace slpvectorizer
2835 
2836 template <> struct GraphTraits<BoUpSLP *> {
2837   using TreeEntry = BoUpSLP::TreeEntry;
2838 
2839   /// NodeRef has to be a pointer per the GraphWriter.
2840   using NodeRef = TreeEntry *;
2841 
2842   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2843 
2844   /// Add the VectorizableTree to the index iterator to be able to return
2845   /// TreeEntry pointers.
2846   struct ChildIteratorType
2847       : public iterator_adaptor_base<
2848             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2849     ContainerTy &VectorizableTree;
2850 
2851     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2852                       ContainerTy &VT)
2853         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2854 
2855     NodeRef operator*() { return I->UserTE; }
2856   };
2857 
2858   static NodeRef getEntryNode(BoUpSLP &R) {
2859     return R.VectorizableTree[0].get();
2860   }
2861 
2862   static ChildIteratorType child_begin(NodeRef N) {
2863     return {N->UserTreeIndices.begin(), N->Container};
2864   }
2865 
2866   static ChildIteratorType child_end(NodeRef N) {
2867     return {N->UserTreeIndices.end(), N->Container};
2868   }
2869 
2870   /// For the node iterator we just need to turn the TreeEntry iterator into a
2871   /// TreeEntry* iterator so that it dereferences to NodeRef.
2872   class nodes_iterator {
2873     using ItTy = ContainerTy::iterator;
2874     ItTy It;
2875 
2876   public:
2877     nodes_iterator(const ItTy &It2) : It(It2) {}
2878     NodeRef operator*() { return It->get(); }
2879     nodes_iterator operator++() {
2880       ++It;
2881       return *this;
2882     }
2883     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2884   };
2885 
2886   static nodes_iterator nodes_begin(BoUpSLP *R) {
2887     return nodes_iterator(R->VectorizableTree.begin());
2888   }
2889 
2890   static nodes_iterator nodes_end(BoUpSLP *R) {
2891     return nodes_iterator(R->VectorizableTree.end());
2892   }
2893 
2894   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2895 };
2896 
2897 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2898   using TreeEntry = BoUpSLP::TreeEntry;
2899 
2900   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2901 
2902   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2903     std::string Str;
2904     raw_string_ostream OS(Str);
2905     if (isSplat(Entry->Scalars))
2906       OS << "<splat> ";
2907     for (auto V : Entry->Scalars) {
2908       OS << *V;
2909       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
2910             return EU.Scalar == V;
2911           }))
2912         OS << " <extract>";
2913       OS << "\n";
2914     }
2915     return Str;
2916   }
2917 
2918   static std::string getNodeAttributes(const TreeEntry *Entry,
2919                                        const BoUpSLP *) {
2920     if (Entry->State == TreeEntry::NeedToGather)
2921       return "color=red";
2922     return "";
2923   }
2924 };
2925 
2926 } // end namespace llvm
2927 
2928 BoUpSLP::~BoUpSLP() {
2929   for (const auto &Pair : DeletedInstructions) {
2930     // Replace operands of ignored instructions with Undefs in case if they were
2931     // marked for deletion.
2932     if (Pair.getSecond()) {
2933       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
2934       Pair.getFirst()->replaceAllUsesWith(Undef);
2935     }
2936     Pair.getFirst()->dropAllReferences();
2937   }
2938   for (const auto &Pair : DeletedInstructions) {
2939     assert(Pair.getFirst()->use_empty() &&
2940            "trying to erase instruction with users.");
2941     Pair.getFirst()->eraseFromParent();
2942   }
2943 #ifdef EXPENSIVE_CHECKS
2944   // If we could guarantee that this call is not extremely slow, we could
2945   // remove the ifdef limitation (see PR47712).
2946   assert(!verifyFunction(*F, &dbgs()));
2947 #endif
2948 }
2949 
2950 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
2951   for (auto *V : AV) {
2952     if (auto *I = dyn_cast<Instruction>(V))
2953       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
2954   };
2955 }
2956 
2957 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
2958 /// contains original mask for the scalars reused in the node. Procedure
2959 /// transform this mask in accordance with the given \p Mask.
2960 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
2961   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
2962          "Expected non-empty mask.");
2963   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
2964   Prev.swap(Reuses);
2965   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
2966     if (Mask[I] != UndefMaskElem)
2967       Reuses[Mask[I]] = Prev[I];
2968 }
2969 
2970 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
2971 /// the original order of the scalars. Procedure transforms the provided order
2972 /// in accordance with the given \p Mask. If the resulting \p Order is just an
2973 /// identity order, \p Order is cleared.
2974 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
2975   assert(!Mask.empty() && "Expected non-empty mask.");
2976   SmallVector<int> MaskOrder;
2977   if (Order.empty()) {
2978     MaskOrder.resize(Mask.size());
2979     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
2980   } else {
2981     inversePermutation(Order, MaskOrder);
2982   }
2983   reorderReuses(MaskOrder, Mask);
2984   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
2985     Order.clear();
2986     return;
2987   }
2988   Order.assign(Mask.size(), Mask.size());
2989   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
2990     if (MaskOrder[I] != UndefMaskElem)
2991       Order[MaskOrder[I]] = I;
2992   fixupOrderingIndices(Order);
2993 }
2994 
2995 Optional<BoUpSLP::OrdersType>
2996 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
2997   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
2998   unsigned NumScalars = TE.Scalars.size();
2999   OrdersType CurrentOrder(NumScalars, NumScalars);
3000   SmallVector<int> Positions;
3001   SmallBitVector UsedPositions(NumScalars);
3002   const TreeEntry *STE = nullptr;
3003   // Try to find all gathered scalars that are gets vectorized in other
3004   // vectorize node. Here we can have only one single tree vector node to
3005   // correctly identify order of the gathered scalars.
3006   for (unsigned I = 0; I < NumScalars; ++I) {
3007     Value *V = TE.Scalars[I];
3008     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3009       continue;
3010     if (const auto *LocalSTE = getTreeEntry(V)) {
3011       if (!STE)
3012         STE = LocalSTE;
3013       else if (STE != LocalSTE)
3014         // Take the order only from the single vector node.
3015         return None;
3016       unsigned Lane =
3017           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3018       if (Lane >= NumScalars)
3019         return None;
3020       if (CurrentOrder[Lane] != NumScalars) {
3021         if (Lane != I)
3022           continue;
3023         UsedPositions.reset(CurrentOrder[Lane]);
3024       }
3025       // The partial identity (where only some elements of the gather node are
3026       // in the identity order) is good.
3027       CurrentOrder[Lane] = I;
3028       UsedPositions.set(I);
3029     }
3030   }
3031   // Need to keep the order if we have a vector entry and at least 2 scalars or
3032   // the vectorized entry has just 2 scalars.
3033   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3034     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3035       for (unsigned I = 0; I < NumScalars; ++I)
3036         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3037           return false;
3038       return true;
3039     };
3040     if (IsIdentityOrder(CurrentOrder)) {
3041       CurrentOrder.clear();
3042       return CurrentOrder;
3043     }
3044     auto *It = CurrentOrder.begin();
3045     for (unsigned I = 0; I < NumScalars;) {
3046       if (UsedPositions.test(I)) {
3047         ++I;
3048         continue;
3049       }
3050       if (*It == NumScalars) {
3051         *It = I;
3052         ++I;
3053       }
3054       ++It;
3055     }
3056     return CurrentOrder;
3057   }
3058   return None;
3059 }
3060 
3061 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3062                                                          bool TopToBottom) {
3063   // No need to reorder if need to shuffle reuses, still need to shuffle the
3064   // node.
3065   if (!TE.ReuseShuffleIndices.empty())
3066     return None;
3067   if (TE.State == TreeEntry::Vectorize &&
3068       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3069        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3070       !TE.isAltShuffle())
3071     return TE.ReorderIndices;
3072   if (TE.State == TreeEntry::NeedToGather) {
3073     // TODO: add analysis of other gather nodes with extractelement
3074     // instructions and other values/instructions, not only undefs.
3075     if (((TE.getOpcode() == Instruction::ExtractElement &&
3076           !TE.isAltShuffle()) ||
3077          (all_of(TE.Scalars,
3078                  [](Value *V) {
3079                    return isa<UndefValue, ExtractElementInst>(V);
3080                  }) &&
3081           any_of(TE.Scalars,
3082                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3083         all_of(TE.Scalars,
3084                [](Value *V) {
3085                  auto *EE = dyn_cast<ExtractElementInst>(V);
3086                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3087                }) &&
3088         allSameType(TE.Scalars)) {
3089       // Check that gather of extractelements can be represented as
3090       // just a shuffle of a single vector.
3091       OrdersType CurrentOrder;
3092       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3093       if (Reuse || !CurrentOrder.empty()) {
3094         if (!CurrentOrder.empty())
3095           fixupOrderingIndices(CurrentOrder);
3096         return CurrentOrder;
3097       }
3098     }
3099     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3100       return CurrentOrder;
3101   }
3102   return None;
3103 }
3104 
3105 void BoUpSLP::reorderTopToBottom() {
3106   // Maps VF to the graph nodes.
3107   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3108   // ExtractElement gather nodes which can be vectorized and need to handle
3109   // their ordering.
3110   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3111   // Find all reorderable nodes with the given VF.
3112   // Currently the are vectorized stores,loads,extracts + some gathering of
3113   // extracts.
3114   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3115                                  const std::unique_ptr<TreeEntry> &TE) {
3116     if (Optional<OrdersType> CurrentOrder =
3117             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3118       // Do not include ordering for nodes used in the alt opcode vectorization,
3119       // better to reorder them during bottom-to-top stage. If follow the order
3120       // here, it causes reordering of the whole graph though actually it is
3121       // profitable just to reorder the subgraph that starts from the alternate
3122       // opcode vectorization node. Such nodes already end-up with the shuffle
3123       // instruction and it is just enough to change this shuffle rather than
3124       // rotate the scalars for the whole graph.
3125       unsigned Cnt = 0;
3126       const TreeEntry *UserTE = TE.get();
3127       while (UserTE && Cnt < RecursionMaxDepth) {
3128         if (UserTE->UserTreeIndices.size() != 1)
3129           break;
3130         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3131               return EI.UserTE->State == TreeEntry::Vectorize &&
3132                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3133             }))
3134           return;
3135         if (UserTE->UserTreeIndices.empty())
3136           UserTE = nullptr;
3137         else
3138           UserTE = UserTE->UserTreeIndices.back().UserTE;
3139         ++Cnt;
3140       }
3141       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3142       if (TE->State != TreeEntry::Vectorize)
3143         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3144     }
3145   });
3146 
3147   // Reorder the graph nodes according to their vectorization factor.
3148   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3149        VF /= 2) {
3150     auto It = VFToOrderedEntries.find(VF);
3151     if (It == VFToOrderedEntries.end())
3152       continue;
3153     // Try to find the most profitable order. We just are looking for the most
3154     // used order and reorder scalar elements in the nodes according to this
3155     // mostly used order.
3156     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3157     // All operands are reordered and used only in this node - propagate the
3158     // most used order to the user node.
3159     MapVector<OrdersType, unsigned,
3160               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3161         OrdersUses;
3162     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3163     for (const TreeEntry *OpTE : OrderedEntries) {
3164       // No need to reorder this nodes, still need to extend and to use shuffle,
3165       // just need to merge reordering shuffle and the reuse shuffle.
3166       if (!OpTE->ReuseShuffleIndices.empty())
3167         continue;
3168       // Count number of orders uses.
3169       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3170         if (OpTE->State == TreeEntry::NeedToGather)
3171           return GathersToOrders.find(OpTE)->second;
3172         return OpTE->ReorderIndices;
3173       }();
3174       // Stores actually store the mask, not the order, need to invert.
3175       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3176           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3177         SmallVector<int> Mask;
3178         inversePermutation(Order, Mask);
3179         unsigned E = Order.size();
3180         OrdersType CurrentOrder(E, E);
3181         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3182           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3183         });
3184         fixupOrderingIndices(CurrentOrder);
3185         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3186       } else {
3187         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3188       }
3189     }
3190     // Set order of the user node.
3191     if (OrdersUses.empty())
3192       continue;
3193     // Choose the most used order.
3194     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3195     unsigned Cnt = OrdersUses.front().second;
3196     for (const auto &Pair : drop_begin(OrdersUses)) {
3197       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3198         BestOrder = Pair.first;
3199         Cnt = Pair.second;
3200       }
3201     }
3202     // Set order of the user node.
3203     if (BestOrder.empty())
3204       continue;
3205     SmallVector<int> Mask;
3206     inversePermutation(BestOrder, Mask);
3207     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3208     unsigned E = BestOrder.size();
3209     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3210       return I < E ? static_cast<int>(I) : UndefMaskElem;
3211     });
3212     // Do an actual reordering, if profitable.
3213     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3214       // Just do the reordering for the nodes with the given VF.
3215       if (TE->Scalars.size() != VF) {
3216         if (TE->ReuseShuffleIndices.size() == VF) {
3217           // Need to reorder the reuses masks of the operands with smaller VF to
3218           // be able to find the match between the graph nodes and scalar
3219           // operands of the given node during vectorization/cost estimation.
3220           assert(all_of(TE->UserTreeIndices,
3221                         [VF, &TE](const EdgeInfo &EI) {
3222                           return EI.UserTE->Scalars.size() == VF ||
3223                                  EI.UserTE->Scalars.size() ==
3224                                      TE->Scalars.size();
3225                         }) &&
3226                  "All users must be of VF size.");
3227           // Update ordering of the operands with the smaller VF than the given
3228           // one.
3229           reorderReuses(TE->ReuseShuffleIndices, Mask);
3230         }
3231         continue;
3232       }
3233       if (TE->State == TreeEntry::Vectorize &&
3234           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3235               InsertElementInst>(TE->getMainOp()) &&
3236           !TE->isAltShuffle()) {
3237         // Build correct orders for extract{element,value}, loads and
3238         // stores.
3239         reorderOrder(TE->ReorderIndices, Mask);
3240         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3241           TE->reorderOperands(Mask);
3242       } else {
3243         // Reorder the node and its operands.
3244         TE->reorderOperands(Mask);
3245         assert(TE->ReorderIndices.empty() &&
3246                "Expected empty reorder sequence.");
3247         reorderScalars(TE->Scalars, Mask);
3248       }
3249       if (!TE->ReuseShuffleIndices.empty()) {
3250         // Apply reversed order to keep the original ordering of the reused
3251         // elements to avoid extra reorder indices shuffling.
3252         OrdersType CurrentOrder;
3253         reorderOrder(CurrentOrder, MaskOrder);
3254         SmallVector<int> NewReuses;
3255         inversePermutation(CurrentOrder, NewReuses);
3256         addMask(NewReuses, TE->ReuseShuffleIndices);
3257         TE->ReuseShuffleIndices.swap(NewReuses);
3258       }
3259     }
3260   }
3261 }
3262 
3263 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3264   SetVector<TreeEntry *> OrderedEntries;
3265   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3266   // Find all reorderable leaf nodes with the given VF.
3267   // Currently the are vectorized loads,extracts without alternate operands +
3268   // some gathering of extracts.
3269   SmallVector<TreeEntry *> NonVectorized;
3270   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3271                               &NonVectorized](
3272                                  const std::unique_ptr<TreeEntry> &TE) {
3273     if (TE->State != TreeEntry::Vectorize)
3274       NonVectorized.push_back(TE.get());
3275     if (Optional<OrdersType> CurrentOrder =
3276             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3277       OrderedEntries.insert(TE.get());
3278       if (TE->State != TreeEntry::Vectorize)
3279         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3280     }
3281   });
3282 
3283   // Checks if the operands of the users are reordarable and have only single
3284   // use.
3285   auto &&CheckOperands =
3286       [this, &NonVectorized](const auto &Data,
3287                              SmallVectorImpl<TreeEntry *> &GatherOps) {
3288         for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) {
3289           if (any_of(Data.second,
3290                      [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3291                        return OpData.first == I &&
3292                               OpData.second->State == TreeEntry::Vectorize;
3293                      }))
3294             continue;
3295           ArrayRef<Value *> VL = Data.first->getOperand(I);
3296           const TreeEntry *TE = nullptr;
3297           const auto *It = find_if(VL, [this, &TE](Value *V) {
3298             TE = getTreeEntry(V);
3299             return TE;
3300           });
3301           if (It != VL.end() && TE->isSame(VL))
3302             return false;
3303           TreeEntry *Gather = nullptr;
3304           if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) {
3305                 assert(TE->State != TreeEntry::Vectorize &&
3306                        "Only non-vectorized nodes are expected.");
3307                 if (TE->isSame(VL)) {
3308                   Gather = TE;
3309                   return true;
3310                 }
3311                 return false;
3312               }) > 1)
3313             return false;
3314           if (Gather)
3315             GatherOps.push_back(Gather);
3316         }
3317         return true;
3318       };
3319   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3320   // I.e., if the node has operands, that are reordered, try to make at least
3321   // one operand order in the natural order and reorder others + reorder the
3322   // user node itself.
3323   SmallPtrSet<const TreeEntry *, 4> Visited;
3324   while (!OrderedEntries.empty()) {
3325     // 1. Filter out only reordered nodes.
3326     // 2. If the entry has multiple uses - skip it and jump to the next node.
3327     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3328     SmallVector<TreeEntry *> Filtered;
3329     for (TreeEntry *TE : OrderedEntries) {
3330       if (!(TE->State == TreeEntry::Vectorize ||
3331             (TE->State == TreeEntry::NeedToGather &&
3332              GathersToOrders.count(TE))) ||
3333           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3334           !all_of(drop_begin(TE->UserTreeIndices),
3335                   [TE](const EdgeInfo &EI) {
3336                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3337                   }) ||
3338           !Visited.insert(TE).second) {
3339         Filtered.push_back(TE);
3340         continue;
3341       }
3342       // Build a map between user nodes and their operands order to speedup
3343       // search. The graph currently does not provide this dependency directly.
3344       for (EdgeInfo &EI : TE->UserTreeIndices) {
3345         TreeEntry *UserTE = EI.UserTE;
3346         auto It = Users.find(UserTE);
3347         if (It == Users.end())
3348           It = Users.insert({UserTE, {}}).first;
3349         It->second.emplace_back(EI.EdgeIdx, TE);
3350       }
3351     }
3352     // Erase filtered entries.
3353     for_each(Filtered,
3354              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3355     for (const auto &Data : Users) {
3356       // Check that operands are used only in the User node.
3357       SmallVector<TreeEntry *> GatherOps;
3358       if (!CheckOperands(Data, GatherOps)) {
3359         for_each(Data.second,
3360                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3361                    OrderedEntries.remove(Op.second);
3362                  });
3363         continue;
3364       }
3365       // All operands are reordered and used only in this node - propagate the
3366       // most used order to the user node.
3367       MapVector<OrdersType, unsigned,
3368                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3369           OrdersUses;
3370       // Do the analysis for each tree entry only once, otherwise the order of
3371       // the same node my be considered several times, though might be not
3372       // profitable.
3373       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3374       for (const auto &Op : Data.second) {
3375         TreeEntry *OpTE = Op.second;
3376         if (!VisitedOps.insert(OpTE).second)
3377           continue;
3378         if (!OpTE->ReuseShuffleIndices.empty() ||
3379             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3380           continue;
3381         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3382           if (OpTE->State == TreeEntry::NeedToGather)
3383             return GathersToOrders.find(OpTE)->second;
3384           return OpTE->ReorderIndices;
3385         }();
3386         // Stores actually store the mask, not the order, need to invert.
3387         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3388             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3389           SmallVector<int> Mask;
3390           inversePermutation(Order, Mask);
3391           unsigned E = Order.size();
3392           OrdersType CurrentOrder(E, E);
3393           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3394             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3395           });
3396           fixupOrderingIndices(CurrentOrder);
3397           ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3398         } else {
3399           ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3400         }
3401         OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
3402             OpTE->UserTreeIndices.size();
3403         assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0.");
3404         --OrdersUses[{}];
3405       }
3406       // If no orders - skip current nodes and jump to the next one, if any.
3407       if (OrdersUses.empty()) {
3408         for_each(Data.second,
3409                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3410                    OrderedEntries.remove(Op.second);
3411                  });
3412         continue;
3413       }
3414       // Choose the best order.
3415       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3416       unsigned Cnt = OrdersUses.front().second;
3417       for (const auto &Pair : drop_begin(OrdersUses)) {
3418         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3419           BestOrder = Pair.first;
3420           Cnt = Pair.second;
3421         }
3422       }
3423       // Set order of the user node (reordering of operands and user nodes).
3424       if (BestOrder.empty()) {
3425         for_each(Data.second,
3426                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3427                    OrderedEntries.remove(Op.second);
3428                  });
3429         continue;
3430       }
3431       // Erase operands from OrderedEntries list and adjust their orders.
3432       VisitedOps.clear();
3433       SmallVector<int> Mask;
3434       inversePermutation(BestOrder, Mask);
3435       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3436       unsigned E = BestOrder.size();
3437       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3438         return I < E ? static_cast<int>(I) : UndefMaskElem;
3439       });
3440       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3441         TreeEntry *TE = Op.second;
3442         OrderedEntries.remove(TE);
3443         if (!VisitedOps.insert(TE).second)
3444           continue;
3445         if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
3446           // Just reorder reuses indices.
3447           reorderReuses(TE->ReuseShuffleIndices, Mask);
3448           continue;
3449         }
3450         // Gathers are processed separately.
3451         if (TE->State != TreeEntry::Vectorize)
3452           continue;
3453         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3454                 TE->ReorderIndices.empty()) &&
3455                "Non-matching sizes of user/operand entries.");
3456         reorderOrder(TE->ReorderIndices, Mask);
3457       }
3458       // For gathers just need to reorder its scalars.
3459       for (TreeEntry *Gather : GatherOps) {
3460         assert(Gather->ReorderIndices.empty() &&
3461                "Unexpected reordering of gathers.");
3462         if (!Gather->ReuseShuffleIndices.empty()) {
3463           // Just reorder reuses indices.
3464           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3465           continue;
3466         }
3467         reorderScalars(Gather->Scalars, Mask);
3468         OrderedEntries.remove(Gather);
3469       }
3470       // Reorder operands of the user node and set the ordering for the user
3471       // node itself.
3472       if (Data.first->State != TreeEntry::Vectorize ||
3473           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3474               Data.first->getMainOp()) ||
3475           Data.first->isAltShuffle())
3476         Data.first->reorderOperands(Mask);
3477       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3478           Data.first->isAltShuffle()) {
3479         reorderScalars(Data.first->Scalars, Mask);
3480         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3481         if (Data.first->ReuseShuffleIndices.empty() &&
3482             !Data.first->ReorderIndices.empty() &&
3483             !Data.first->isAltShuffle()) {
3484           // Insert user node to the list to try to sink reordering deeper in
3485           // the graph.
3486           OrderedEntries.insert(Data.first);
3487         }
3488       } else {
3489         reorderOrder(Data.first->ReorderIndices, Mask);
3490       }
3491     }
3492   }
3493   // If the reordering is unnecessary, just remove the reorder.
3494   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3495       VectorizableTree.front()->ReuseShuffleIndices.empty())
3496     VectorizableTree.front()->ReorderIndices.clear();
3497 }
3498 
3499 void BoUpSLP::buildExternalUses(
3500     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3501   // Collect the values that we need to extract from the tree.
3502   for (auto &TEPtr : VectorizableTree) {
3503     TreeEntry *Entry = TEPtr.get();
3504 
3505     // No need to handle users of gathered values.
3506     if (Entry->State == TreeEntry::NeedToGather)
3507       continue;
3508 
3509     // For each lane:
3510     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3511       Value *Scalar = Entry->Scalars[Lane];
3512       int FoundLane = Entry->findLaneForValue(Scalar);
3513 
3514       // Check if the scalar is externally used as an extra arg.
3515       auto ExtI = ExternallyUsedValues.find(Scalar);
3516       if (ExtI != ExternallyUsedValues.end()) {
3517         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3518                           << Lane << " from " << *Scalar << ".\n");
3519         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3520       }
3521       for (User *U : Scalar->users()) {
3522         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3523 
3524         Instruction *UserInst = dyn_cast<Instruction>(U);
3525         if (!UserInst)
3526           continue;
3527 
3528         if (isDeleted(UserInst))
3529           continue;
3530 
3531         // Skip in-tree scalars that become vectors
3532         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3533           Value *UseScalar = UseEntry->Scalars[0];
3534           // Some in-tree scalars will remain as scalar in vectorized
3535           // instructions. If that is the case, the one in Lane 0 will
3536           // be used.
3537           if (UseScalar != U ||
3538               UseEntry->State == TreeEntry::ScatterVectorize ||
3539               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3540             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3541                               << ".\n");
3542             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3543             continue;
3544           }
3545         }
3546 
3547         // Ignore users in the user ignore list.
3548         if (is_contained(UserIgnoreList, UserInst))
3549           continue;
3550 
3551         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3552                           << Lane << " from " << *Scalar << ".\n");
3553         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3554       }
3555     }
3556   }
3557 }
3558 
3559 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3560                         ArrayRef<Value *> UserIgnoreLst) {
3561   deleteTree();
3562   UserIgnoreList = UserIgnoreLst;
3563   if (!allSameType(Roots))
3564     return;
3565   buildTree_rec(Roots, 0, EdgeInfo());
3566 }
3567 
3568 namespace {
3569 /// Tracks the state we can represent the loads in the given sequence.
3570 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3571 } // anonymous namespace
3572 
3573 /// Checks if the given array of loads can be represented as a vectorized,
3574 /// scatter or just simple gather.
3575 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3576                                     const TargetTransformInfo &TTI,
3577                                     const DataLayout &DL, ScalarEvolution &SE,
3578                                     SmallVectorImpl<unsigned> &Order,
3579                                     SmallVectorImpl<Value *> &PointerOps) {
3580   // Check that a vectorized load would load the same memory as a scalar
3581   // load. For example, we don't want to vectorize loads that are smaller
3582   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3583   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3584   // from such a struct, we read/write packed bits disagreeing with the
3585   // unvectorized version.
3586   Type *ScalarTy = VL0->getType();
3587 
3588   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3589     return LoadsState::Gather;
3590 
3591   // Make sure all loads in the bundle are simple - we can't vectorize
3592   // atomic or volatile loads.
3593   PointerOps.clear();
3594   PointerOps.resize(VL.size());
3595   auto *POIter = PointerOps.begin();
3596   for (Value *V : VL) {
3597     auto *L = cast<LoadInst>(V);
3598     if (!L->isSimple())
3599       return LoadsState::Gather;
3600     *POIter = L->getPointerOperand();
3601     ++POIter;
3602   }
3603 
3604   Order.clear();
3605   // Check the order of pointer operands.
3606   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3607     Value *Ptr0;
3608     Value *PtrN;
3609     if (Order.empty()) {
3610       Ptr0 = PointerOps.front();
3611       PtrN = PointerOps.back();
3612     } else {
3613       Ptr0 = PointerOps[Order.front()];
3614       PtrN = PointerOps[Order.back()];
3615     }
3616     Optional<int> Diff =
3617         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3618     // Check that the sorted loads are consecutive.
3619     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3620       return LoadsState::Vectorize;
3621     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3622     for (Value *V : VL)
3623       CommonAlignment =
3624           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3625     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3626                                 CommonAlignment))
3627       return LoadsState::ScatterVectorize;
3628   }
3629 
3630   return LoadsState::Gather;
3631 }
3632 
3633 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3634                             const EdgeInfo &UserTreeIdx) {
3635   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3636 
3637   SmallVector<int> ReuseShuffleIndicies;
3638   SmallVector<Value *> UniqueValues;
3639   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3640                                 &UserTreeIdx,
3641                                 this](const InstructionsState &S) {
3642     // Check that every instruction appears once in this bundle.
3643     DenseMap<Value *, unsigned> UniquePositions;
3644     for (Value *V : VL) {
3645       if (isConstant(V)) {
3646         ReuseShuffleIndicies.emplace_back(
3647             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3648         UniqueValues.emplace_back(V);
3649         continue;
3650       }
3651       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3652       ReuseShuffleIndicies.emplace_back(Res.first->second);
3653       if (Res.second)
3654         UniqueValues.emplace_back(V);
3655     }
3656     size_t NumUniqueScalarValues = UniqueValues.size();
3657     if (NumUniqueScalarValues == VL.size()) {
3658       ReuseShuffleIndicies.clear();
3659     } else {
3660       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3661       if (NumUniqueScalarValues <= 1 ||
3662           (UniquePositions.size() == 1 && all_of(UniqueValues,
3663                                                  [](Value *V) {
3664                                                    return isa<UndefValue>(V) ||
3665                                                           !isConstant(V);
3666                                                  })) ||
3667           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3668         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3669         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3670         return false;
3671       }
3672       VL = UniqueValues;
3673     }
3674     return true;
3675   };
3676 
3677   InstructionsState S = getSameOpcode(VL);
3678   if (Depth == RecursionMaxDepth) {
3679     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3680     if (TryToFindDuplicates(S))
3681       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3682                    ReuseShuffleIndicies);
3683     return;
3684   }
3685 
3686   // Don't handle scalable vectors
3687   if (S.getOpcode() == Instruction::ExtractElement &&
3688       isa<ScalableVectorType>(
3689           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3690     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3691     if (TryToFindDuplicates(S))
3692       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3693                    ReuseShuffleIndicies);
3694     return;
3695   }
3696 
3697   // Don't handle vectors.
3698   if (S.OpValue->getType()->isVectorTy() &&
3699       !isa<InsertElementInst>(S.OpValue)) {
3700     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3701     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3702     return;
3703   }
3704 
3705   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3706     if (SI->getValueOperand()->getType()->isVectorTy()) {
3707       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3708       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3709       return;
3710     }
3711 
3712   // If all of the operands are identical or constant we have a simple solution.
3713   // If we deal with insert/extract instructions, they all must have constant
3714   // indices, otherwise we should gather them, not try to vectorize.
3715   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3716       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3717        !all_of(VL, isVectorLikeInstWithConstOps))) {
3718     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3719     if (TryToFindDuplicates(S))
3720       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3721                    ReuseShuffleIndicies);
3722     return;
3723   }
3724 
3725   // We now know that this is a vector of instructions of the same type from
3726   // the same block.
3727 
3728   // Don't vectorize ephemeral values.
3729   for (Value *V : VL) {
3730     if (EphValues.count(V)) {
3731       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3732                         << ") is ephemeral.\n");
3733       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3734       return;
3735     }
3736   }
3737 
3738   // Check if this is a duplicate of another entry.
3739   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3740     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3741     if (!E->isSame(VL)) {
3742       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3743       if (TryToFindDuplicates(S))
3744         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3745                      ReuseShuffleIndicies);
3746       return;
3747     }
3748     // Record the reuse of the tree node.  FIXME, currently this is only used to
3749     // properly draw the graph rather than for the actual vectorization.
3750     E->UserTreeIndices.push_back(UserTreeIdx);
3751     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3752                       << ".\n");
3753     return;
3754   }
3755 
3756   // Check that none of the instructions in the bundle are already in the tree.
3757   for (Value *V : VL) {
3758     auto *I = dyn_cast<Instruction>(V);
3759     if (!I)
3760       continue;
3761     if (getTreeEntry(I)) {
3762       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3763                         << ") is already in tree.\n");
3764       if (TryToFindDuplicates(S))
3765         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3766                      ReuseShuffleIndicies);
3767       return;
3768     }
3769   }
3770 
3771   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3772   for (Value *V : VL) {
3773     if (is_contained(UserIgnoreList, V)) {
3774       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3775       if (TryToFindDuplicates(S))
3776         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3777                      ReuseShuffleIndicies);
3778       return;
3779     }
3780   }
3781 
3782   // Check that all of the users of the scalars that we want to vectorize are
3783   // schedulable.
3784   auto *VL0 = cast<Instruction>(S.OpValue);
3785   BasicBlock *BB = VL0->getParent();
3786 
3787   if (!DT->isReachableFromEntry(BB)) {
3788     // Don't go into unreachable blocks. They may contain instructions with
3789     // dependency cycles which confuse the final scheduling.
3790     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3791     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3792     return;
3793   }
3794 
3795   // Check that every instruction appears once in this bundle.
3796   if (!TryToFindDuplicates(S))
3797     return;
3798 
3799   auto &BSRef = BlocksSchedules[BB];
3800   if (!BSRef)
3801     BSRef = std::make_unique<BlockScheduling>(BB);
3802 
3803   BlockScheduling &BS = *BSRef.get();
3804 
3805   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
3806   if (!Bundle) {
3807     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
3808     assert((!BS.getScheduleData(VL0) ||
3809             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
3810            "tryScheduleBundle should cancelScheduling on failure");
3811     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3812                  ReuseShuffleIndicies);
3813     return;
3814   }
3815   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
3816 
3817   unsigned ShuffleOrOp = S.isAltShuffle() ?
3818                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3819   switch (ShuffleOrOp) {
3820     case Instruction::PHI: {
3821       auto *PH = cast<PHINode>(VL0);
3822 
3823       // Check for terminator values (e.g. invoke).
3824       for (Value *V : VL)
3825         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3826           Instruction *Term = dyn_cast<Instruction>(
3827               cast<PHINode>(V)->getIncomingValueForBlock(
3828                   PH->getIncomingBlock(I)));
3829           if (Term && Term->isTerminator()) {
3830             LLVM_DEBUG(dbgs()
3831                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
3832             BS.cancelScheduling(VL, VL0);
3833             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3834                          ReuseShuffleIndicies);
3835             return;
3836           }
3837         }
3838 
3839       TreeEntry *TE =
3840           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
3841       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
3842 
3843       // Keeps the reordered operands to avoid code duplication.
3844       SmallVector<ValueList, 2> OperandsVec;
3845       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3846         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
3847           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
3848           TE->setOperand(I, Operands);
3849           OperandsVec.push_back(Operands);
3850           continue;
3851         }
3852         ValueList Operands;
3853         // Prepare the operand vector.
3854         for (Value *V : VL)
3855           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
3856               PH->getIncomingBlock(I)));
3857         TE->setOperand(I, Operands);
3858         OperandsVec.push_back(Operands);
3859       }
3860       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
3861         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
3862       return;
3863     }
3864     case Instruction::ExtractValue:
3865     case Instruction::ExtractElement: {
3866       OrdersType CurrentOrder;
3867       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
3868       if (Reuse) {
3869         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
3870         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3871                      ReuseShuffleIndicies);
3872         // This is a special case, as it does not gather, but at the same time
3873         // we are not extending buildTree_rec() towards the operands.
3874         ValueList Op0;
3875         Op0.assign(VL.size(), VL0->getOperand(0));
3876         VectorizableTree.back()->setOperand(0, Op0);
3877         return;
3878       }
3879       if (!CurrentOrder.empty()) {
3880         LLVM_DEBUG({
3881           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
3882                     "with order";
3883           for (unsigned Idx : CurrentOrder)
3884             dbgs() << " " << Idx;
3885           dbgs() << "\n";
3886         });
3887         fixupOrderingIndices(CurrentOrder);
3888         // Insert new order with initial value 0, if it does not exist,
3889         // otherwise return the iterator to the existing one.
3890         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3891                      ReuseShuffleIndicies, CurrentOrder);
3892         // This is a special case, as it does not gather, but at the same time
3893         // we are not extending buildTree_rec() towards the operands.
3894         ValueList Op0;
3895         Op0.assign(VL.size(), VL0->getOperand(0));
3896         VectorizableTree.back()->setOperand(0, Op0);
3897         return;
3898       }
3899       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
3900       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3901                    ReuseShuffleIndicies);
3902       BS.cancelScheduling(VL, VL0);
3903       return;
3904     }
3905     case Instruction::InsertElement: {
3906       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
3907 
3908       // Check that we have a buildvector and not a shuffle of 2 or more
3909       // different vectors.
3910       ValueSet SourceVectors;
3911       int MinIdx = std::numeric_limits<int>::max();
3912       for (Value *V : VL) {
3913         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
3914         Optional<int> Idx = *getInsertIndex(V, 0);
3915         if (!Idx || *Idx == UndefMaskElem)
3916           continue;
3917         MinIdx = std::min(MinIdx, *Idx);
3918       }
3919 
3920       if (count_if(VL, [&SourceVectors](Value *V) {
3921             return !SourceVectors.contains(V);
3922           }) >= 2) {
3923         // Found 2nd source vector - cancel.
3924         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
3925                              "different source vectors.\n");
3926         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3927         BS.cancelScheduling(VL, VL0);
3928         return;
3929       }
3930 
3931       auto OrdCompare = [](const std::pair<int, int> &P1,
3932                            const std::pair<int, int> &P2) {
3933         return P1.first > P2.first;
3934       };
3935       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
3936                     decltype(OrdCompare)>
3937           Indices(OrdCompare);
3938       for (int I = 0, E = VL.size(); I < E; ++I) {
3939         Optional<int> Idx = *getInsertIndex(VL[I], 0);
3940         if (!Idx || *Idx == UndefMaskElem)
3941           continue;
3942         Indices.emplace(*Idx, I);
3943       }
3944       OrdersType CurrentOrder(VL.size(), VL.size());
3945       bool IsIdentity = true;
3946       for (int I = 0, E = VL.size(); I < E; ++I) {
3947         CurrentOrder[Indices.top().second] = I;
3948         IsIdentity &= Indices.top().second == I;
3949         Indices.pop();
3950       }
3951       if (IsIdentity)
3952         CurrentOrder.clear();
3953       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3954                                    None, CurrentOrder);
3955       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
3956 
3957       constexpr int NumOps = 2;
3958       ValueList VectorOperands[NumOps];
3959       for (int I = 0; I < NumOps; ++I) {
3960         for (Value *V : VL)
3961           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
3962 
3963         TE->setOperand(I, VectorOperands[I]);
3964       }
3965       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
3966       return;
3967     }
3968     case Instruction::Load: {
3969       // Check that a vectorized load would load the same memory as a scalar
3970       // load. For example, we don't want to vectorize loads that are smaller
3971       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3972       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3973       // from such a struct, we read/write packed bits disagreeing with the
3974       // unvectorized version.
3975       SmallVector<Value *> PointerOps;
3976       OrdersType CurrentOrder;
3977       TreeEntry *TE = nullptr;
3978       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
3979                                 PointerOps)) {
3980       case LoadsState::Vectorize:
3981         if (CurrentOrder.empty()) {
3982           // Original loads are consecutive and does not require reordering.
3983           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3984                             ReuseShuffleIndicies);
3985           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
3986         } else {
3987           fixupOrderingIndices(CurrentOrder);
3988           // Need to reorder.
3989           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3990                             ReuseShuffleIndicies, CurrentOrder);
3991           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
3992         }
3993         TE->setOperandsInOrder();
3994         break;
3995       case LoadsState::ScatterVectorize:
3996         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
3997         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
3998                           UserTreeIdx, ReuseShuffleIndicies);
3999         TE->setOperandsInOrder();
4000         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4001         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4002         break;
4003       case LoadsState::Gather:
4004         BS.cancelScheduling(VL, VL0);
4005         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4006                      ReuseShuffleIndicies);
4007 #ifndef NDEBUG
4008         Type *ScalarTy = VL0->getType();
4009         if (DL->getTypeSizeInBits(ScalarTy) !=
4010             DL->getTypeAllocSizeInBits(ScalarTy))
4011           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4012         else if (any_of(VL, [](Value *V) {
4013                    return !cast<LoadInst>(V)->isSimple();
4014                  }))
4015           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4016         else
4017           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4018 #endif // NDEBUG
4019         break;
4020       }
4021       return;
4022     }
4023     case Instruction::ZExt:
4024     case Instruction::SExt:
4025     case Instruction::FPToUI:
4026     case Instruction::FPToSI:
4027     case Instruction::FPExt:
4028     case Instruction::PtrToInt:
4029     case Instruction::IntToPtr:
4030     case Instruction::SIToFP:
4031     case Instruction::UIToFP:
4032     case Instruction::Trunc:
4033     case Instruction::FPTrunc:
4034     case Instruction::BitCast: {
4035       Type *SrcTy = VL0->getOperand(0)->getType();
4036       for (Value *V : VL) {
4037         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4038         if (Ty != SrcTy || !isValidElementType(Ty)) {
4039           BS.cancelScheduling(VL, VL0);
4040           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4041                        ReuseShuffleIndicies);
4042           LLVM_DEBUG(dbgs()
4043                      << "SLP: Gathering casts with different src types.\n");
4044           return;
4045         }
4046       }
4047       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4048                                    ReuseShuffleIndicies);
4049       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4050 
4051       TE->setOperandsInOrder();
4052       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4053         ValueList Operands;
4054         // Prepare the operand vector.
4055         for (Value *V : VL)
4056           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4057 
4058         buildTree_rec(Operands, Depth + 1, {TE, i});
4059       }
4060       return;
4061     }
4062     case Instruction::ICmp:
4063     case Instruction::FCmp: {
4064       // Check that all of the compares have the same predicate.
4065       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4066       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4067       Type *ComparedTy = VL0->getOperand(0)->getType();
4068       for (Value *V : VL) {
4069         CmpInst *Cmp = cast<CmpInst>(V);
4070         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4071             Cmp->getOperand(0)->getType() != ComparedTy) {
4072           BS.cancelScheduling(VL, VL0);
4073           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4074                        ReuseShuffleIndicies);
4075           LLVM_DEBUG(dbgs()
4076                      << "SLP: Gathering cmp with different predicate.\n");
4077           return;
4078         }
4079       }
4080 
4081       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4082                                    ReuseShuffleIndicies);
4083       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4084 
4085       ValueList Left, Right;
4086       if (cast<CmpInst>(VL0)->isCommutative()) {
4087         // Commutative predicate - collect + sort operands of the instructions
4088         // so that each side is more likely to have the same opcode.
4089         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4090         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4091       } else {
4092         // Collect operands - commute if it uses the swapped predicate.
4093         for (Value *V : VL) {
4094           auto *Cmp = cast<CmpInst>(V);
4095           Value *LHS = Cmp->getOperand(0);
4096           Value *RHS = Cmp->getOperand(1);
4097           if (Cmp->getPredicate() != P0)
4098             std::swap(LHS, RHS);
4099           Left.push_back(LHS);
4100           Right.push_back(RHS);
4101         }
4102       }
4103       TE->setOperand(0, Left);
4104       TE->setOperand(1, Right);
4105       buildTree_rec(Left, Depth + 1, {TE, 0});
4106       buildTree_rec(Right, Depth + 1, {TE, 1});
4107       return;
4108     }
4109     case Instruction::Select:
4110     case Instruction::FNeg:
4111     case Instruction::Add:
4112     case Instruction::FAdd:
4113     case Instruction::Sub:
4114     case Instruction::FSub:
4115     case Instruction::Mul:
4116     case Instruction::FMul:
4117     case Instruction::UDiv:
4118     case Instruction::SDiv:
4119     case Instruction::FDiv:
4120     case Instruction::URem:
4121     case Instruction::SRem:
4122     case Instruction::FRem:
4123     case Instruction::Shl:
4124     case Instruction::LShr:
4125     case Instruction::AShr:
4126     case Instruction::And:
4127     case Instruction::Or:
4128     case Instruction::Xor: {
4129       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4130                                    ReuseShuffleIndicies);
4131       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4132 
4133       // Sort operands of the instructions so that each side is more likely to
4134       // have the same opcode.
4135       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4136         ValueList Left, Right;
4137         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4138         TE->setOperand(0, Left);
4139         TE->setOperand(1, Right);
4140         buildTree_rec(Left, Depth + 1, {TE, 0});
4141         buildTree_rec(Right, Depth + 1, {TE, 1});
4142         return;
4143       }
4144 
4145       TE->setOperandsInOrder();
4146       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4147         ValueList Operands;
4148         // Prepare the operand vector.
4149         for (Value *V : VL)
4150           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4151 
4152         buildTree_rec(Operands, Depth + 1, {TE, i});
4153       }
4154       return;
4155     }
4156     case Instruction::GetElementPtr: {
4157       // We don't combine GEPs with complicated (nested) indexing.
4158       for (Value *V : VL) {
4159         if (cast<Instruction>(V)->getNumOperands() != 2) {
4160           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4161           BS.cancelScheduling(VL, VL0);
4162           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4163                        ReuseShuffleIndicies);
4164           return;
4165         }
4166       }
4167 
4168       // We can't combine several GEPs into one vector if they operate on
4169       // different types.
4170       Type *Ty0 = VL0->getOperand(0)->getType();
4171       for (Value *V : VL) {
4172         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
4173         if (Ty0 != CurTy) {
4174           LLVM_DEBUG(dbgs()
4175                      << "SLP: not-vectorizable GEP (different types).\n");
4176           BS.cancelScheduling(VL, VL0);
4177           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4178                        ReuseShuffleIndicies);
4179           return;
4180         }
4181       }
4182 
4183       // We don't combine GEPs with non-constant indexes.
4184       Type *Ty1 = VL0->getOperand(1)->getType();
4185       for (Value *V : VL) {
4186         auto Op = cast<Instruction>(V)->getOperand(1);
4187         if (!isa<ConstantInt>(Op) ||
4188             (Op->getType() != Ty1 &&
4189              Op->getType()->getScalarSizeInBits() >
4190                  DL->getIndexSizeInBits(
4191                      V->getType()->getPointerAddressSpace()))) {
4192           LLVM_DEBUG(dbgs()
4193                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4194           BS.cancelScheduling(VL, VL0);
4195           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4196                        ReuseShuffleIndicies);
4197           return;
4198         }
4199       }
4200 
4201       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4202                                    ReuseShuffleIndicies);
4203       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4204       SmallVector<ValueList, 2> Operands(2);
4205       // Prepare the operand vector for pointer operands.
4206       for (Value *V : VL)
4207         Operands.front().push_back(
4208             cast<GetElementPtrInst>(V)->getPointerOperand());
4209       TE->setOperand(0, Operands.front());
4210       // Need to cast all indices to the same type before vectorization to
4211       // avoid crash.
4212       // Required to be able to find correct matches between different gather
4213       // nodes and reuse the vectorized values rather than trying to gather them
4214       // again.
4215       int IndexIdx = 1;
4216       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4217       Type *Ty = all_of(VL,
4218                         [VL0Ty, IndexIdx](Value *V) {
4219                           return VL0Ty == cast<GetElementPtrInst>(V)
4220                                               ->getOperand(IndexIdx)
4221                                               ->getType();
4222                         })
4223                      ? VL0Ty
4224                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4225                                             ->getPointerOperandType()
4226                                             ->getScalarType());
4227       // Prepare the operand vector.
4228       for (Value *V : VL) {
4229         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4230         auto *CI = cast<ConstantInt>(Op);
4231         Operands.back().push_back(ConstantExpr::getIntegerCast(
4232             CI, Ty, CI->getValue().isSignBitSet()));
4233       }
4234       TE->setOperand(IndexIdx, Operands.back());
4235 
4236       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4237         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4238       return;
4239     }
4240     case Instruction::Store: {
4241       // Check if the stores are consecutive or if we need to swizzle them.
4242       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4243       // Avoid types that are padded when being allocated as scalars, while
4244       // being packed together in a vector (such as i1).
4245       if (DL->getTypeSizeInBits(ScalarTy) !=
4246           DL->getTypeAllocSizeInBits(ScalarTy)) {
4247         BS.cancelScheduling(VL, VL0);
4248         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4249                      ReuseShuffleIndicies);
4250         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4251         return;
4252       }
4253       // Make sure all stores in the bundle are simple - we can't vectorize
4254       // atomic or volatile stores.
4255       SmallVector<Value *, 4> PointerOps(VL.size());
4256       ValueList Operands(VL.size());
4257       auto POIter = PointerOps.begin();
4258       auto OIter = Operands.begin();
4259       for (Value *V : VL) {
4260         auto *SI = cast<StoreInst>(V);
4261         if (!SI->isSimple()) {
4262           BS.cancelScheduling(VL, VL0);
4263           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4264                        ReuseShuffleIndicies);
4265           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4266           return;
4267         }
4268         *POIter = SI->getPointerOperand();
4269         *OIter = SI->getValueOperand();
4270         ++POIter;
4271         ++OIter;
4272       }
4273 
4274       OrdersType CurrentOrder;
4275       // Check the order of pointer operands.
4276       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4277         Value *Ptr0;
4278         Value *PtrN;
4279         if (CurrentOrder.empty()) {
4280           Ptr0 = PointerOps.front();
4281           PtrN = PointerOps.back();
4282         } else {
4283           Ptr0 = PointerOps[CurrentOrder.front()];
4284           PtrN = PointerOps[CurrentOrder.back()];
4285         }
4286         Optional<int> Dist =
4287             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4288         // Check that the sorted pointer operands are consecutive.
4289         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4290           if (CurrentOrder.empty()) {
4291             // Original stores are consecutive and does not require reordering.
4292             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4293                                          UserTreeIdx, ReuseShuffleIndicies);
4294             TE->setOperandsInOrder();
4295             buildTree_rec(Operands, Depth + 1, {TE, 0});
4296             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4297           } else {
4298             fixupOrderingIndices(CurrentOrder);
4299             TreeEntry *TE =
4300                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4301                              ReuseShuffleIndicies, CurrentOrder);
4302             TE->setOperandsInOrder();
4303             buildTree_rec(Operands, Depth + 1, {TE, 0});
4304             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4305           }
4306           return;
4307         }
4308       }
4309 
4310       BS.cancelScheduling(VL, VL0);
4311       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4312                    ReuseShuffleIndicies);
4313       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4314       return;
4315     }
4316     case Instruction::Call: {
4317       // Check if the calls are all to the same vectorizable intrinsic or
4318       // library function.
4319       CallInst *CI = cast<CallInst>(VL0);
4320       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4321 
4322       VFShape Shape = VFShape::get(
4323           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4324           false /*HasGlobalPred*/);
4325       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4326 
4327       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4328         BS.cancelScheduling(VL, VL0);
4329         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4330                      ReuseShuffleIndicies);
4331         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4332         return;
4333       }
4334       Function *F = CI->getCalledFunction();
4335       unsigned NumArgs = CI->arg_size();
4336       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4337       for (unsigned j = 0; j != NumArgs; ++j)
4338         if (hasVectorInstrinsicScalarOpd(ID, j))
4339           ScalarArgs[j] = CI->getArgOperand(j);
4340       for (Value *V : VL) {
4341         CallInst *CI2 = dyn_cast<CallInst>(V);
4342         if (!CI2 || CI2->getCalledFunction() != F ||
4343             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4344             (VecFunc &&
4345              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4346             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4347           BS.cancelScheduling(VL, VL0);
4348           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4349                        ReuseShuffleIndicies);
4350           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4351                             << "\n");
4352           return;
4353         }
4354         // Some intrinsics have scalar arguments and should be same in order for
4355         // them to be vectorized.
4356         for (unsigned j = 0; j != NumArgs; ++j) {
4357           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4358             Value *A1J = CI2->getArgOperand(j);
4359             if (ScalarArgs[j] != A1J) {
4360               BS.cancelScheduling(VL, VL0);
4361               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4362                            ReuseShuffleIndicies);
4363               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4364                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4365                                 << "\n");
4366               return;
4367             }
4368           }
4369         }
4370         // Verify that the bundle operands are identical between the two calls.
4371         if (CI->hasOperandBundles() &&
4372             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4373                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4374                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4375           BS.cancelScheduling(VL, VL0);
4376           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4377                        ReuseShuffleIndicies);
4378           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4379                             << *CI << "!=" << *V << '\n');
4380           return;
4381         }
4382       }
4383 
4384       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4385                                    ReuseShuffleIndicies);
4386       TE->setOperandsInOrder();
4387       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4388         // For scalar operands no need to to create an entry since no need to
4389         // vectorize it.
4390         if (hasVectorInstrinsicScalarOpd(ID, i))
4391           continue;
4392         ValueList Operands;
4393         // Prepare the operand vector.
4394         for (Value *V : VL) {
4395           auto *CI2 = cast<CallInst>(V);
4396           Operands.push_back(CI2->getArgOperand(i));
4397         }
4398         buildTree_rec(Operands, Depth + 1, {TE, i});
4399       }
4400       return;
4401     }
4402     case Instruction::ShuffleVector: {
4403       // If this is not an alternate sequence of opcode like add-sub
4404       // then do not vectorize this instruction.
4405       if (!S.isAltShuffle()) {
4406         BS.cancelScheduling(VL, VL0);
4407         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4408                      ReuseShuffleIndicies);
4409         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4410         return;
4411       }
4412       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4413                                    ReuseShuffleIndicies);
4414       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4415 
4416       // Reorder operands if reordering would enable vectorization.
4417       auto *CI = dyn_cast<CmpInst>(VL0);
4418       if (isa<BinaryOperator>(VL0) || CI) {
4419         ValueList Left, Right;
4420         if (!CI || all_of(VL, [](Value *V) {
4421               return cast<CmpInst>(V)->isCommutative();
4422             })) {
4423           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4424         } else {
4425           CmpInst::Predicate P0 = CI->getPredicate();
4426           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4427           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4428           Value *BaseOp0 = VL0->getOperand(0);
4429           Value *BaseOp1 = VL0->getOperand(1);
4430           // Collect operands - commute if it uses the swapped predicate or
4431           // alternate operation.
4432           for (Value *V : VL) {
4433             auto *Cmp = cast<CmpInst>(V);
4434             Value *LHS = Cmp->getOperand(0);
4435             Value *RHS = Cmp->getOperand(1);
4436             CmpInst::Predicate CurrentPred = CI->getPredicate();
4437             CmpInst::Predicate CurrentPredSwapped =
4438                 CmpInst::getSwappedPredicate(CurrentPred);
4439             if (P0 == AltP0 || P0 == AltP0Swapped) {
4440               if ((P0 == CurrentPred &&
4441                    !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4442                   (P0 == CurrentPredSwapped &&
4443                    !areCompatibleCmpOps(BaseOp0, BaseOp1, RHS, LHS)))
4444                 std::swap(LHS, RHS);
4445             } else if (!areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) {
4446               std::swap(LHS, RHS);
4447             }
4448             Left.push_back(LHS);
4449             Right.push_back(RHS);
4450           }
4451         }
4452         TE->setOperand(0, Left);
4453         TE->setOperand(1, Right);
4454         buildTree_rec(Left, Depth + 1, {TE, 0});
4455         buildTree_rec(Right, Depth + 1, {TE, 1});
4456         return;
4457       }
4458 
4459       TE->setOperandsInOrder();
4460       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4461         ValueList Operands;
4462         // Prepare the operand vector.
4463         for (Value *V : VL)
4464           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4465 
4466         buildTree_rec(Operands, Depth + 1, {TE, i});
4467       }
4468       return;
4469     }
4470     default:
4471       BS.cancelScheduling(VL, VL0);
4472       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4473                    ReuseShuffleIndicies);
4474       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4475       return;
4476   }
4477 }
4478 
4479 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4480   unsigned N = 1;
4481   Type *EltTy = T;
4482 
4483   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4484          isa<VectorType>(EltTy)) {
4485     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4486       // Check that struct is homogeneous.
4487       for (const auto *Ty : ST->elements())
4488         if (Ty != *ST->element_begin())
4489           return 0;
4490       N *= ST->getNumElements();
4491       EltTy = *ST->element_begin();
4492     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4493       N *= AT->getNumElements();
4494       EltTy = AT->getElementType();
4495     } else {
4496       auto *VT = cast<FixedVectorType>(EltTy);
4497       N *= VT->getNumElements();
4498       EltTy = VT->getElementType();
4499     }
4500   }
4501 
4502   if (!isValidElementType(EltTy))
4503     return 0;
4504   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4505   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4506     return 0;
4507   return N;
4508 }
4509 
4510 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4511                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4512   const auto *It = find_if(VL, [](Value *V) {
4513     return isa<ExtractElementInst, ExtractValueInst>(V);
4514   });
4515   assert(It != VL.end() && "Expected at least one extract instruction.");
4516   auto *E0 = cast<Instruction>(*It);
4517   assert(all_of(VL,
4518                 [](Value *V) {
4519                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4520                       V);
4521                 }) &&
4522          "Invalid opcode");
4523   // Check if all of the extracts come from the same vector and from the
4524   // correct offset.
4525   Value *Vec = E0->getOperand(0);
4526 
4527   CurrentOrder.clear();
4528 
4529   // We have to extract from a vector/aggregate with the same number of elements.
4530   unsigned NElts;
4531   if (E0->getOpcode() == Instruction::ExtractValue) {
4532     const DataLayout &DL = E0->getModule()->getDataLayout();
4533     NElts = canMapToVector(Vec->getType(), DL);
4534     if (!NElts)
4535       return false;
4536     // Check if load can be rewritten as load of vector.
4537     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4538     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4539       return false;
4540   } else {
4541     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4542   }
4543 
4544   if (NElts != VL.size())
4545     return false;
4546 
4547   // Check that all of the indices extract from the correct offset.
4548   bool ShouldKeepOrder = true;
4549   unsigned E = VL.size();
4550   // Assign to all items the initial value E + 1 so we can check if the extract
4551   // instruction index was used already.
4552   // Also, later we can check that all the indices are used and we have a
4553   // consecutive access in the extract instructions, by checking that no
4554   // element of CurrentOrder still has value E + 1.
4555   CurrentOrder.assign(E, E);
4556   unsigned I = 0;
4557   for (; I < E; ++I) {
4558     auto *Inst = dyn_cast<Instruction>(VL[I]);
4559     if (!Inst)
4560       continue;
4561     if (Inst->getOperand(0) != Vec)
4562       break;
4563     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4564       if (isa<UndefValue>(EE->getIndexOperand()))
4565         continue;
4566     Optional<unsigned> Idx = getExtractIndex(Inst);
4567     if (!Idx)
4568       break;
4569     const unsigned ExtIdx = *Idx;
4570     if (ExtIdx != I) {
4571       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4572         break;
4573       ShouldKeepOrder = false;
4574       CurrentOrder[ExtIdx] = I;
4575     } else {
4576       if (CurrentOrder[I] != E)
4577         break;
4578       CurrentOrder[I] = I;
4579     }
4580   }
4581   if (I < E) {
4582     CurrentOrder.clear();
4583     return false;
4584   }
4585   if (ShouldKeepOrder)
4586     CurrentOrder.clear();
4587 
4588   return ShouldKeepOrder;
4589 }
4590 
4591 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4592                                     ArrayRef<Value *> VectorizedVals) const {
4593   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4594          all_of(I->users(), [this](User *U) {
4595            return ScalarToTreeEntry.count(U) > 0 || MustGather.contains(U);
4596          });
4597 }
4598 
4599 static std::pair<InstructionCost, InstructionCost>
4600 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4601                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4602   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4603 
4604   // Calculate the cost of the scalar and vector calls.
4605   SmallVector<Type *, 4> VecTys;
4606   for (Use &Arg : CI->args())
4607     VecTys.push_back(
4608         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4609   FastMathFlags FMF;
4610   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4611     FMF = FPCI->getFastMathFlags();
4612   SmallVector<const Value *> Arguments(CI->args());
4613   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4614                                     dyn_cast<IntrinsicInst>(CI));
4615   auto IntrinsicCost =
4616     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4617 
4618   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4619                                      VecTy->getNumElements())),
4620                             false /*HasGlobalPred*/);
4621   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4622   auto LibCost = IntrinsicCost;
4623   if (!CI->isNoBuiltin() && VecFunc) {
4624     // Calculate the cost of the vector library call.
4625     // If the corresponding vector call is cheaper, return its cost.
4626     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4627                                     TTI::TCK_RecipThroughput);
4628   }
4629   return {IntrinsicCost, LibCost};
4630 }
4631 
4632 /// Compute the cost of creating a vector of type \p VecTy containing the
4633 /// extracted values from \p VL.
4634 static InstructionCost
4635 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4636                    TargetTransformInfo::ShuffleKind ShuffleKind,
4637                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4638   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4639 
4640   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4641       VecTy->getNumElements() < NumOfParts)
4642     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4643 
4644   bool AllConsecutive = true;
4645   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4646   unsigned Idx = -1;
4647   InstructionCost Cost = 0;
4648 
4649   // Process extracts in blocks of EltsPerVector to check if the source vector
4650   // operand can be re-used directly. If not, add the cost of creating a shuffle
4651   // to extract the values into a vector register.
4652   for (auto *V : VL) {
4653     ++Idx;
4654 
4655     // Need to exclude undefs from analysis.
4656     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4657       continue;
4658 
4659     // Reached the start of a new vector registers.
4660     if (Idx % EltsPerVector == 0) {
4661       AllConsecutive = true;
4662       continue;
4663     }
4664 
4665     // Check all extracts for a vector register on the target directly
4666     // extract values in order.
4667     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4668     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4669       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4670       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4671                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4672     }
4673 
4674     if (AllConsecutive)
4675       continue;
4676 
4677     // Skip all indices, except for the last index per vector block.
4678     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4679       continue;
4680 
4681     // If we have a series of extracts which are not consecutive and hence
4682     // cannot re-use the source vector register directly, compute the shuffle
4683     // cost to extract the a vector with EltsPerVector elements.
4684     Cost += TTI.getShuffleCost(
4685         TargetTransformInfo::SK_PermuteSingleSrc,
4686         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4687   }
4688   return Cost;
4689 }
4690 
4691 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4692 /// operations operands.
4693 static void
4694 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4695                      ArrayRef<int> ReusesIndices,
4696                      const function_ref<bool(Instruction *)> IsAltOp,
4697                      SmallVectorImpl<int> &Mask,
4698                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4699                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4700   unsigned Sz = VL.size();
4701   Mask.assign(Sz, UndefMaskElem);
4702   SmallVector<int> OrderMask;
4703   if (!ReorderIndices.empty())
4704     inversePermutation(ReorderIndices, OrderMask);
4705   for (unsigned I = 0; I < Sz; ++I) {
4706     unsigned Idx = I;
4707     if (!ReorderIndices.empty())
4708       Idx = OrderMask[I];
4709     auto *OpInst = cast<Instruction>(VL[Idx]);
4710     if (IsAltOp(OpInst)) {
4711       Mask[I] = Sz + Idx;
4712       if (AltScalars)
4713         AltScalars->push_back(OpInst);
4714     } else {
4715       Mask[I] = Idx;
4716       if (OpScalars)
4717         OpScalars->push_back(OpInst);
4718     }
4719   }
4720   if (!ReusesIndices.empty()) {
4721     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4722     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4723       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4724     });
4725     Mask.swap(NewMask);
4726   }
4727 }
4728 
4729 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4730                                       ArrayRef<Value *> VectorizedVals) {
4731   ArrayRef<Value*> VL = E->Scalars;
4732 
4733   Type *ScalarTy = VL[0]->getType();
4734   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4735     ScalarTy = SI->getValueOperand()->getType();
4736   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4737     ScalarTy = CI->getOperand(0)->getType();
4738   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4739     ScalarTy = IE->getOperand(1)->getType();
4740   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4741   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4742 
4743   // If we have computed a smaller type for the expression, update VecTy so
4744   // that the costs will be accurate.
4745   if (MinBWs.count(VL[0]))
4746     VecTy = FixedVectorType::get(
4747         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4748   unsigned EntryVF = E->getVectorFactor();
4749   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4750 
4751   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4752   // FIXME: it tries to fix a problem with MSVC buildbots.
4753   TargetTransformInfo &TTIRef = *TTI;
4754   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4755                                VectorizedVals, E](InstructionCost &Cost) {
4756     DenseMap<Value *, int> ExtractVectorsTys;
4757     SmallPtrSet<Value *, 4> CheckedExtracts;
4758     for (auto *V : VL) {
4759       if (isa<UndefValue>(V))
4760         continue;
4761       // If all users of instruction are going to be vectorized and this
4762       // instruction itself is not going to be vectorized, consider this
4763       // instruction as dead and remove its cost from the final cost of the
4764       // vectorized tree.
4765       // Also, avoid adjusting the cost for extractelements with multiple uses
4766       // in different graph entries.
4767       const TreeEntry *VE = getTreeEntry(V);
4768       if (!CheckedExtracts.insert(V).second ||
4769           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4770           (VE && VE != E))
4771         continue;
4772       auto *EE = cast<ExtractElementInst>(V);
4773       Optional<unsigned> EEIdx = getExtractIndex(EE);
4774       if (!EEIdx)
4775         continue;
4776       unsigned Idx = *EEIdx;
4777       if (TTIRef.getNumberOfParts(VecTy) !=
4778           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4779         auto It =
4780             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4781         It->getSecond() = std::min<int>(It->second, Idx);
4782       }
4783       // Take credit for instruction that will become dead.
4784       if (EE->hasOneUse()) {
4785         Instruction *Ext = EE->user_back();
4786         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4787             all_of(Ext->users(),
4788                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4789           // Use getExtractWithExtendCost() to calculate the cost of
4790           // extractelement/ext pair.
4791           Cost -=
4792               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4793                                               EE->getVectorOperandType(), Idx);
4794           // Add back the cost of s|zext which is subtracted separately.
4795           Cost += TTIRef.getCastInstrCost(
4796               Ext->getOpcode(), Ext->getType(), EE->getType(),
4797               TTI::getCastContextHint(Ext), CostKind, Ext);
4798           continue;
4799         }
4800       }
4801       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4802                                         EE->getVectorOperandType(), Idx);
4803     }
4804     // Add a cost for subvector extracts/inserts if required.
4805     for (const auto &Data : ExtractVectorsTys) {
4806       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4807       unsigned NumElts = VecTy->getNumElements();
4808       if (Data.second % NumElts == 0)
4809         continue;
4810       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4811         unsigned Idx = (Data.second / NumElts) * NumElts;
4812         unsigned EENumElts = EEVTy->getNumElements();
4813         if (Idx + NumElts <= EENumElts) {
4814           Cost +=
4815               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4816                                     EEVTy, None, Idx, VecTy);
4817         } else {
4818           // Need to round up the subvector type vectorization factor to avoid a
4819           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4820           // <= EENumElts.
4821           auto *SubVT =
4822               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4823           Cost +=
4824               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4825                                     EEVTy, None, Idx, SubVT);
4826         }
4827       } else {
4828         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4829                                       VecTy, None, 0, EEVTy);
4830       }
4831     }
4832   };
4833   if (E->State == TreeEntry::NeedToGather) {
4834     if (allConstant(VL))
4835       return 0;
4836     if (isa<InsertElementInst>(VL[0]))
4837       return InstructionCost::getInvalid();
4838     SmallVector<int> Mask;
4839     SmallVector<const TreeEntry *> Entries;
4840     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4841         isGatherShuffledEntry(E, Mask, Entries);
4842     if (Shuffle.hasValue()) {
4843       InstructionCost GatherCost = 0;
4844       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4845         // Perfect match in the graph, will reuse the previously vectorized
4846         // node. Cost is 0.
4847         LLVM_DEBUG(
4848             dbgs()
4849             << "SLP: perfect diamond match for gather bundle that starts with "
4850             << *VL.front() << ".\n");
4851         if (NeedToShuffleReuses)
4852           GatherCost =
4853               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4854                                   FinalVecTy, E->ReuseShuffleIndices);
4855       } else {
4856         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4857                           << " entries for bundle that starts with "
4858                           << *VL.front() << ".\n");
4859         // Detected that instead of gather we can emit a shuffle of single/two
4860         // previously vectorized nodes. Add the cost of the permutation rather
4861         // than gather.
4862         ::addMask(Mask, E->ReuseShuffleIndices);
4863         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4864       }
4865       return GatherCost;
4866     }
4867     if ((E->getOpcode() == Instruction::ExtractElement ||
4868          all_of(E->Scalars,
4869                 [](Value *V) {
4870                   return isa<ExtractElementInst, UndefValue>(V);
4871                 })) &&
4872         allSameType(VL)) {
4873       // Check that gather of extractelements can be represented as just a
4874       // shuffle of a single/two vectors the scalars are extracted from.
4875       SmallVector<int> Mask;
4876       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4877           isFixedVectorShuffle(VL, Mask);
4878       if (ShuffleKind.hasValue()) {
4879         // Found the bunch of extractelement instructions that must be gathered
4880         // into a vector and can be represented as a permutation elements in a
4881         // single input vector or of 2 input vectors.
4882         InstructionCost Cost =
4883             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4884         AdjustExtractsCost(Cost);
4885         if (NeedToShuffleReuses)
4886           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4887                                       FinalVecTy, E->ReuseShuffleIndices);
4888         return Cost;
4889       }
4890     }
4891     if (isSplat(VL)) {
4892       // Found the broadcasting of the single scalar, calculate the cost as the
4893       // broadcast.
4894       assert(VecTy == FinalVecTy &&
4895              "No reused scalars expected for broadcast.");
4896       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
4897     }
4898     InstructionCost ReuseShuffleCost = 0;
4899     if (NeedToShuffleReuses)
4900       ReuseShuffleCost = TTI->getShuffleCost(
4901           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
4902     // Improve gather cost for gather of loads, if we can group some of the
4903     // loads into vector loads.
4904     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
4905         !E->isAltShuffle()) {
4906       BoUpSLP::ValueSet VectorizedLoads;
4907       unsigned StartIdx = 0;
4908       unsigned VF = VL.size() / 2;
4909       unsigned VectorizedCnt = 0;
4910       unsigned ScatterVectorizeCnt = 0;
4911       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
4912       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
4913         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
4914              Cnt += VF) {
4915           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
4916           if (!VectorizedLoads.count(Slice.front()) &&
4917               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
4918             SmallVector<Value *> PointerOps;
4919             OrdersType CurrentOrder;
4920             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
4921                                               *SE, CurrentOrder, PointerOps);
4922             switch (LS) {
4923             case LoadsState::Vectorize:
4924             case LoadsState::ScatterVectorize:
4925               // Mark the vectorized loads so that we don't vectorize them
4926               // again.
4927               if (LS == LoadsState::Vectorize)
4928                 ++VectorizedCnt;
4929               else
4930                 ++ScatterVectorizeCnt;
4931               VectorizedLoads.insert(Slice.begin(), Slice.end());
4932               // If we vectorized initial block, no need to try to vectorize it
4933               // again.
4934               if (Cnt == StartIdx)
4935                 StartIdx += VF;
4936               break;
4937             case LoadsState::Gather:
4938               break;
4939             }
4940           }
4941         }
4942         // Check if the whole array was vectorized already - exit.
4943         if (StartIdx >= VL.size())
4944           break;
4945         // Found vectorizable parts - exit.
4946         if (!VectorizedLoads.empty())
4947           break;
4948       }
4949       if (!VectorizedLoads.empty()) {
4950         InstructionCost GatherCost = 0;
4951         unsigned NumParts = TTI->getNumberOfParts(VecTy);
4952         bool NeedInsertSubvectorAnalysis =
4953             !NumParts || (VL.size() / VF) > NumParts;
4954         // Get the cost for gathered loads.
4955         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
4956           if (VectorizedLoads.contains(VL[I]))
4957             continue;
4958           GatherCost += getGatherCost(VL.slice(I, VF));
4959         }
4960         // The cost for vectorized loads.
4961         InstructionCost ScalarsCost = 0;
4962         for (Value *V : VectorizedLoads) {
4963           auto *LI = cast<LoadInst>(V);
4964           ScalarsCost += TTI->getMemoryOpCost(
4965               Instruction::Load, LI->getType(), LI->getAlign(),
4966               LI->getPointerAddressSpace(), CostKind, LI);
4967         }
4968         auto *LI = cast<LoadInst>(E->getMainOp());
4969         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
4970         Align Alignment = LI->getAlign();
4971         GatherCost +=
4972             VectorizedCnt *
4973             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
4974                                  LI->getPointerAddressSpace(), CostKind, LI);
4975         GatherCost += ScatterVectorizeCnt *
4976                       TTI->getGatherScatterOpCost(
4977                           Instruction::Load, LoadTy, LI->getPointerOperand(),
4978                           /*VariableMask=*/false, Alignment, CostKind, LI);
4979         if (NeedInsertSubvectorAnalysis) {
4980           // Add the cost for the subvectors insert.
4981           for (int I = VF, E = VL.size(); I < E; I += VF)
4982             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
4983                                               None, I, LoadTy);
4984         }
4985         return ReuseShuffleCost + GatherCost - ScalarsCost;
4986       }
4987     }
4988     return ReuseShuffleCost + getGatherCost(VL);
4989   }
4990   InstructionCost CommonCost = 0;
4991   SmallVector<int> Mask;
4992   if (!E->ReorderIndices.empty()) {
4993     SmallVector<int> NewMask;
4994     if (E->getOpcode() == Instruction::Store) {
4995       // For stores the order is actually a mask.
4996       NewMask.resize(E->ReorderIndices.size());
4997       copy(E->ReorderIndices, NewMask.begin());
4998     } else {
4999       inversePermutation(E->ReorderIndices, NewMask);
5000     }
5001     ::addMask(Mask, NewMask);
5002   }
5003   if (NeedToShuffleReuses)
5004     ::addMask(Mask, E->ReuseShuffleIndices);
5005   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5006     CommonCost =
5007         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5008   assert((E->State == TreeEntry::Vectorize ||
5009           E->State == TreeEntry::ScatterVectorize) &&
5010          "Unhandled state");
5011   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5012   Instruction *VL0 = E->getMainOp();
5013   unsigned ShuffleOrOp =
5014       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5015   switch (ShuffleOrOp) {
5016     case Instruction::PHI:
5017       return 0;
5018 
5019     case Instruction::ExtractValue:
5020     case Instruction::ExtractElement: {
5021       // The common cost of removal ExtractElement/ExtractValue instructions +
5022       // the cost of shuffles, if required to resuffle the original vector.
5023       if (NeedToShuffleReuses) {
5024         unsigned Idx = 0;
5025         for (unsigned I : E->ReuseShuffleIndices) {
5026           if (ShuffleOrOp == Instruction::ExtractElement) {
5027             auto *EE = cast<ExtractElementInst>(VL[I]);
5028             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5029                                                   EE->getVectorOperandType(),
5030                                                   *getExtractIndex(EE));
5031           } else {
5032             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5033                                                   VecTy, Idx);
5034             ++Idx;
5035           }
5036         }
5037         Idx = EntryVF;
5038         for (Value *V : VL) {
5039           if (ShuffleOrOp == Instruction::ExtractElement) {
5040             auto *EE = cast<ExtractElementInst>(V);
5041             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5042                                                   EE->getVectorOperandType(),
5043                                                   *getExtractIndex(EE));
5044           } else {
5045             --Idx;
5046             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5047                                                   VecTy, Idx);
5048           }
5049         }
5050       }
5051       if (ShuffleOrOp == Instruction::ExtractValue) {
5052         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5053           auto *EI = cast<Instruction>(VL[I]);
5054           // Take credit for instruction that will become dead.
5055           if (EI->hasOneUse()) {
5056             Instruction *Ext = EI->user_back();
5057             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5058                 all_of(Ext->users(),
5059                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5060               // Use getExtractWithExtendCost() to calculate the cost of
5061               // extractelement/ext pair.
5062               CommonCost -= TTI->getExtractWithExtendCost(
5063                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5064               // Add back the cost of s|zext which is subtracted separately.
5065               CommonCost += TTI->getCastInstrCost(
5066                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5067                   TTI::getCastContextHint(Ext), CostKind, Ext);
5068               continue;
5069             }
5070           }
5071           CommonCost -=
5072               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5073         }
5074       } else {
5075         AdjustExtractsCost(CommonCost);
5076       }
5077       return CommonCost;
5078     }
5079     case Instruction::InsertElement: {
5080       assert(E->ReuseShuffleIndices.empty() &&
5081              "Unique insertelements only are expected.");
5082       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5083 
5084       unsigned const NumElts = SrcVecTy->getNumElements();
5085       unsigned const NumScalars = VL.size();
5086       APInt DemandedElts = APInt::getZero(NumElts);
5087       // TODO: Add support for Instruction::InsertValue.
5088       SmallVector<int> Mask;
5089       if (!E->ReorderIndices.empty()) {
5090         inversePermutation(E->ReorderIndices, Mask);
5091         Mask.append(NumElts - NumScalars, UndefMaskElem);
5092       } else {
5093         Mask.assign(NumElts, UndefMaskElem);
5094         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5095       }
5096       unsigned Offset = *getInsertIndex(VL0, 0);
5097       bool IsIdentity = true;
5098       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5099       Mask.swap(PrevMask);
5100       for (unsigned I = 0; I < NumScalars; ++I) {
5101         Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0);
5102         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5103           continue;
5104         DemandedElts.setBit(*InsertIdx);
5105         IsIdentity &= *InsertIdx - Offset == I;
5106         Mask[*InsertIdx - Offset] = I;
5107       }
5108       assert(Offset < NumElts && "Failed to find vector index offset");
5109 
5110       InstructionCost Cost = 0;
5111       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5112                                             /*Insert*/ true, /*Extract*/ false);
5113 
5114       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5115         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5116         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5117         Cost += TTI->getShuffleCost(
5118             TargetTransformInfo::SK_PermuteSingleSrc,
5119             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5120       } else if (!IsIdentity) {
5121         auto *FirstInsert =
5122             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5123               return !is_contained(E->Scalars,
5124                                    cast<Instruction>(V)->getOperand(0));
5125             }));
5126         if (isUndefVector(FirstInsert->getOperand(0))) {
5127           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5128         } else {
5129           SmallVector<int> InsertMask(NumElts);
5130           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5131           for (unsigned I = 0; I < NumElts; I++) {
5132             if (Mask[I] != UndefMaskElem)
5133               InsertMask[Offset + I] = NumElts + I;
5134           }
5135           Cost +=
5136               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5137         }
5138       }
5139 
5140       return Cost;
5141     }
5142     case Instruction::ZExt:
5143     case Instruction::SExt:
5144     case Instruction::FPToUI:
5145     case Instruction::FPToSI:
5146     case Instruction::FPExt:
5147     case Instruction::PtrToInt:
5148     case Instruction::IntToPtr:
5149     case Instruction::SIToFP:
5150     case Instruction::UIToFP:
5151     case Instruction::Trunc:
5152     case Instruction::FPTrunc:
5153     case Instruction::BitCast: {
5154       Type *SrcTy = VL0->getOperand(0)->getType();
5155       InstructionCost ScalarEltCost =
5156           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5157                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5158       if (NeedToShuffleReuses) {
5159         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5160       }
5161 
5162       // Calculate the cost of this instruction.
5163       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5164 
5165       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5166       InstructionCost VecCost = 0;
5167       // Check if the values are candidates to demote.
5168       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5169         VecCost = CommonCost + TTI->getCastInstrCost(
5170                                    E->getOpcode(), VecTy, SrcVecTy,
5171                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5172       }
5173       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5174       return VecCost - ScalarCost;
5175     }
5176     case Instruction::FCmp:
5177     case Instruction::ICmp:
5178     case Instruction::Select: {
5179       // Calculate the cost of this instruction.
5180       InstructionCost ScalarEltCost =
5181           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5182                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5183       if (NeedToShuffleReuses) {
5184         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5185       }
5186       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5187       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5188 
5189       // Check if all entries in VL are either compares or selects with compares
5190       // as condition that have the same predicates.
5191       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5192       bool First = true;
5193       for (auto *V : VL) {
5194         CmpInst::Predicate CurrentPred;
5195         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5196         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5197              !match(V, MatchCmp)) ||
5198             (!First && VecPred != CurrentPred)) {
5199           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5200           break;
5201         }
5202         First = false;
5203         VecPred = CurrentPred;
5204       }
5205 
5206       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5207           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5208       // Check if it is possible and profitable to use min/max for selects in
5209       // VL.
5210       //
5211       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5212       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5213         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5214                                           {VecTy, VecTy});
5215         InstructionCost IntrinsicCost =
5216             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5217         // If the selects are the only uses of the compares, they will be dead
5218         // and we can adjust the cost by removing their cost.
5219         if (IntrinsicAndUse.second)
5220           IntrinsicCost -=
5221               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
5222                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
5223         VecCost = std::min(VecCost, IntrinsicCost);
5224       }
5225       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5226       return CommonCost + VecCost - ScalarCost;
5227     }
5228     case Instruction::FNeg:
5229     case Instruction::Add:
5230     case Instruction::FAdd:
5231     case Instruction::Sub:
5232     case Instruction::FSub:
5233     case Instruction::Mul:
5234     case Instruction::FMul:
5235     case Instruction::UDiv:
5236     case Instruction::SDiv:
5237     case Instruction::FDiv:
5238     case Instruction::URem:
5239     case Instruction::SRem:
5240     case Instruction::FRem:
5241     case Instruction::Shl:
5242     case Instruction::LShr:
5243     case Instruction::AShr:
5244     case Instruction::And:
5245     case Instruction::Or:
5246     case Instruction::Xor: {
5247       // Certain instructions can be cheaper to vectorize if they have a
5248       // constant second vector operand.
5249       TargetTransformInfo::OperandValueKind Op1VK =
5250           TargetTransformInfo::OK_AnyValue;
5251       TargetTransformInfo::OperandValueKind Op2VK =
5252           TargetTransformInfo::OK_UniformConstantValue;
5253       TargetTransformInfo::OperandValueProperties Op1VP =
5254           TargetTransformInfo::OP_None;
5255       TargetTransformInfo::OperandValueProperties Op2VP =
5256           TargetTransformInfo::OP_PowerOf2;
5257 
5258       // If all operands are exactly the same ConstantInt then set the
5259       // operand kind to OK_UniformConstantValue.
5260       // If instead not all operands are constants, then set the operand kind
5261       // to OK_AnyValue. If all operands are constants but not the same,
5262       // then set the operand kind to OK_NonUniformConstantValue.
5263       ConstantInt *CInt0 = nullptr;
5264       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5265         const Instruction *I = cast<Instruction>(VL[i]);
5266         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5267         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5268         if (!CInt) {
5269           Op2VK = TargetTransformInfo::OK_AnyValue;
5270           Op2VP = TargetTransformInfo::OP_None;
5271           break;
5272         }
5273         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5274             !CInt->getValue().isPowerOf2())
5275           Op2VP = TargetTransformInfo::OP_None;
5276         if (i == 0) {
5277           CInt0 = CInt;
5278           continue;
5279         }
5280         if (CInt0 != CInt)
5281           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5282       }
5283 
5284       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5285       InstructionCost ScalarEltCost =
5286           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5287                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5288       if (NeedToShuffleReuses) {
5289         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5290       }
5291       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5292       InstructionCost VecCost =
5293           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5294                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5295       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5296       return CommonCost + VecCost - ScalarCost;
5297     }
5298     case Instruction::GetElementPtr: {
5299       TargetTransformInfo::OperandValueKind Op1VK =
5300           TargetTransformInfo::OK_AnyValue;
5301       TargetTransformInfo::OperandValueKind Op2VK =
5302           TargetTransformInfo::OK_UniformConstantValue;
5303 
5304       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5305           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5306       if (NeedToShuffleReuses) {
5307         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5308       }
5309       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5310       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5311           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5312       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5313       return CommonCost + VecCost - ScalarCost;
5314     }
5315     case Instruction::Load: {
5316       // Cost of wide load - cost of scalar loads.
5317       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5318       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5319           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5320       if (NeedToShuffleReuses) {
5321         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5322       }
5323       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5324       InstructionCost VecLdCost;
5325       if (E->State == TreeEntry::Vectorize) {
5326         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5327                                          CostKind, VL0);
5328       } else {
5329         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5330         Align CommonAlignment = Alignment;
5331         for (Value *V : VL)
5332           CommonAlignment =
5333               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5334         VecLdCost = TTI->getGatherScatterOpCost(
5335             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5336             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5337       }
5338       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5339       return CommonCost + VecLdCost - ScalarLdCost;
5340     }
5341     case Instruction::Store: {
5342       // We know that we can merge the stores. Calculate the cost.
5343       bool IsReorder = !E->ReorderIndices.empty();
5344       auto *SI =
5345           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5346       Align Alignment = SI->getAlign();
5347       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5348           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5349       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5350       InstructionCost VecStCost = TTI->getMemoryOpCost(
5351           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5352       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5353       return CommonCost + VecStCost - ScalarStCost;
5354     }
5355     case Instruction::Call: {
5356       CallInst *CI = cast<CallInst>(VL0);
5357       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5358 
5359       // Calculate the cost of the scalar and vector calls.
5360       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5361       InstructionCost ScalarEltCost =
5362           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5363       if (NeedToShuffleReuses) {
5364         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5365       }
5366       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5367 
5368       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5369       InstructionCost VecCallCost =
5370           std::min(VecCallCosts.first, VecCallCosts.second);
5371 
5372       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5373                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5374                         << " for " << *CI << "\n");
5375 
5376       return CommonCost + VecCallCost - ScalarCallCost;
5377     }
5378     case Instruction::ShuffleVector: {
5379       assert(E->isAltShuffle() &&
5380              ((Instruction::isBinaryOp(E->getOpcode()) &&
5381                Instruction::isBinaryOp(E->getAltOpcode())) ||
5382               (Instruction::isCast(E->getOpcode()) &&
5383                Instruction::isCast(E->getAltOpcode())) ||
5384               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5385              "Invalid Shuffle Vector Operand");
5386       InstructionCost ScalarCost = 0;
5387       if (NeedToShuffleReuses) {
5388         for (unsigned Idx : E->ReuseShuffleIndices) {
5389           Instruction *I = cast<Instruction>(VL[Idx]);
5390           CommonCost -= TTI->getInstructionCost(I, CostKind);
5391         }
5392         for (Value *V : VL) {
5393           Instruction *I = cast<Instruction>(V);
5394           CommonCost += TTI->getInstructionCost(I, CostKind);
5395         }
5396       }
5397       for (Value *V : VL) {
5398         Instruction *I = cast<Instruction>(V);
5399         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5400         ScalarCost += TTI->getInstructionCost(I, CostKind);
5401       }
5402       // VecCost is equal to sum of the cost of creating 2 vectors
5403       // and the cost of creating shuffle.
5404       InstructionCost VecCost = 0;
5405       // Try to find the previous shuffle node with the same operands and same
5406       // main/alternate ops.
5407       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5408         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5409           if (TE.get() == E)
5410             break;
5411           if (TE->isAltShuffle() &&
5412               ((TE->getOpcode() == E->getOpcode() &&
5413                 TE->getAltOpcode() == E->getAltOpcode()) ||
5414                (TE->getOpcode() == E->getAltOpcode() &&
5415                 TE->getAltOpcode() == E->getOpcode())) &&
5416               TE->hasEqualOperands(*E))
5417             return true;
5418         }
5419         return false;
5420       };
5421       if (TryFindNodeWithEqualOperands()) {
5422         LLVM_DEBUG({
5423           dbgs() << "SLP: diamond match for alternate node found.\n";
5424           E->dump();
5425         });
5426         // No need to add new vector costs here since we're going to reuse
5427         // same main/alternate vector ops, just do different shuffling.
5428       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5429         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5430         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5431                                                CostKind);
5432       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5433         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5434                                           Builder.getInt1Ty(),
5435                                           CI0->getPredicate(), CostKind, VL0);
5436         VecCost += TTI->getCmpSelInstrCost(
5437             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5438             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5439             E->getAltOp());
5440       } else {
5441         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5442         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5443         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5444         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5445         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5446                                         TTI::CastContextHint::None, CostKind);
5447         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5448                                          TTI::CastContextHint::None, CostKind);
5449       }
5450 
5451       SmallVector<int> Mask;
5452       buildSuffleEntryMask(
5453           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5454           [E](Instruction *I) {
5455             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5456             if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) {
5457               auto *AltCI0 = cast<CmpInst>(E->getAltOp());
5458               auto *CI = cast<CmpInst>(I);
5459               CmpInst::Predicate P0 = CI0->getPredicate();
5460               CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5461               CmpInst::Predicate AltP0Swapped =
5462                   CmpInst::getSwappedPredicate(AltP0);
5463               CmpInst::Predicate CurrentPred = CI->getPredicate();
5464               CmpInst::Predicate CurrentPredSwapped =
5465                   CmpInst::getSwappedPredicate(CurrentPred);
5466               if (P0 == AltP0 || P0 == AltP0Swapped) {
5467                 unsigned Idx =
5468                     std::distance(E->Scalars.begin(), find(E->Scalars, I));
5469                 // Alternate cmps have same/swapped predicate as main cmps but
5470                 // different order of compatible operands.
5471                 ArrayRef<Value *> VLOp0 = E->getOperand(0);
5472                 return (P0 == CurrentPred && CI->getOperand(0) != VLOp0[Idx]) ||
5473                        (P0 == CurrentPredSwapped &&
5474                         CI->getOperand(1) != VLOp0[Idx]);
5475               }
5476               return CurrentPred != P0 && CurrentPredSwapped != P0;
5477             }
5478             return I->getOpcode() == E->getAltOpcode();
5479           },
5480           Mask);
5481       CommonCost =
5482           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5483       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5484       return CommonCost + VecCost - ScalarCost;
5485     }
5486     default:
5487       llvm_unreachable("Unknown instruction");
5488   }
5489 }
5490 
5491 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5492   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5493                     << VectorizableTree.size() << " is fully vectorizable .\n");
5494 
5495   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5496     SmallVector<int> Mask;
5497     return TE->State == TreeEntry::NeedToGather &&
5498            !any_of(TE->Scalars,
5499                    [this](Value *V) { return EphValues.contains(V); }) &&
5500            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5501             TE->Scalars.size() < Limit ||
5502             ((TE->getOpcode() == Instruction::ExtractElement ||
5503               all_of(TE->Scalars,
5504                      [](Value *V) {
5505                        return isa<ExtractElementInst, UndefValue>(V);
5506                      })) &&
5507              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5508             (TE->State == TreeEntry::NeedToGather &&
5509              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5510   };
5511 
5512   // We only handle trees of heights 1 and 2.
5513   if (VectorizableTree.size() == 1 &&
5514       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5515        (ForReduction &&
5516         AreVectorizableGathers(VectorizableTree[0].get(),
5517                                VectorizableTree[0]->Scalars.size()) &&
5518         VectorizableTree[0]->getVectorFactor() > 2)))
5519     return true;
5520 
5521   if (VectorizableTree.size() != 2)
5522     return false;
5523 
5524   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5525   // with the second gather nodes if they have less scalar operands rather than
5526   // the initial tree element (may be profitable to shuffle the second gather)
5527   // or they are extractelements, which form shuffle.
5528   SmallVector<int> Mask;
5529   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5530       AreVectorizableGathers(VectorizableTree[1].get(),
5531                              VectorizableTree[0]->Scalars.size()))
5532     return true;
5533 
5534   // Gathering cost would be too much for tiny trees.
5535   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5536       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5537        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5538     return false;
5539 
5540   return true;
5541 }
5542 
5543 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5544                                        TargetTransformInfo *TTI,
5545                                        bool MustMatchOrInst) {
5546   // Look past the root to find a source value. Arbitrarily follow the
5547   // path through operand 0 of any 'or'. Also, peek through optional
5548   // shift-left-by-multiple-of-8-bits.
5549   Value *ZextLoad = Root;
5550   const APInt *ShAmtC;
5551   bool FoundOr = false;
5552   while (!isa<ConstantExpr>(ZextLoad) &&
5553          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5554           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5555            ShAmtC->urem(8) == 0))) {
5556     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5557     ZextLoad = BinOp->getOperand(0);
5558     if (BinOp->getOpcode() == Instruction::Or)
5559       FoundOr = true;
5560   }
5561   // Check if the input is an extended load of the required or/shift expression.
5562   Value *Load;
5563   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5564       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5565     return false;
5566 
5567   // Require that the total load bit width is a legal integer type.
5568   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5569   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5570   Type *SrcTy = Load->getType();
5571   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5572   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5573     return false;
5574 
5575   // Everything matched - assume that we can fold the whole sequence using
5576   // load combining.
5577   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5578              << *(cast<Instruction>(Root)) << "\n");
5579 
5580   return true;
5581 }
5582 
5583 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5584   if (RdxKind != RecurKind::Or)
5585     return false;
5586 
5587   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5588   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5589   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5590                                     /* MatchOr */ false);
5591 }
5592 
5593 bool BoUpSLP::isLoadCombineCandidate() const {
5594   // Peek through a final sequence of stores and check if all operations are
5595   // likely to be load-combined.
5596   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5597   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5598     Value *X;
5599     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5600         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5601       return false;
5602   }
5603   return true;
5604 }
5605 
5606 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5607   // No need to vectorize inserts of gathered values.
5608   if (VectorizableTree.size() == 2 &&
5609       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5610       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5611     return true;
5612 
5613   // We can vectorize the tree if its size is greater than or equal to the
5614   // minimum size specified by the MinTreeSize command line option.
5615   if (VectorizableTree.size() >= MinTreeSize)
5616     return false;
5617 
5618   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5619   // can vectorize it if we can prove it fully vectorizable.
5620   if (isFullyVectorizableTinyTree(ForReduction))
5621     return false;
5622 
5623   assert(VectorizableTree.empty()
5624              ? ExternalUses.empty()
5625              : true && "We shouldn't have any external users");
5626 
5627   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5628   // vectorizable.
5629   return true;
5630 }
5631 
5632 InstructionCost BoUpSLP::getSpillCost() const {
5633   // Walk from the bottom of the tree to the top, tracking which values are
5634   // live. When we see a call instruction that is not part of our tree,
5635   // query TTI to see if there is a cost to keeping values live over it
5636   // (for example, if spills and fills are required).
5637   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5638   InstructionCost Cost = 0;
5639 
5640   SmallPtrSet<Instruction*, 4> LiveValues;
5641   Instruction *PrevInst = nullptr;
5642 
5643   // The entries in VectorizableTree are not necessarily ordered by their
5644   // position in basic blocks. Collect them and order them by dominance so later
5645   // instructions are guaranteed to be visited first. For instructions in
5646   // different basic blocks, we only scan to the beginning of the block, so
5647   // their order does not matter, as long as all instructions in a basic block
5648   // are grouped together. Using dominance ensures a deterministic order.
5649   SmallVector<Instruction *, 16> OrderedScalars;
5650   for (const auto &TEPtr : VectorizableTree) {
5651     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5652     if (!Inst)
5653       continue;
5654     OrderedScalars.push_back(Inst);
5655   }
5656   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5657     auto *NodeA = DT->getNode(A->getParent());
5658     auto *NodeB = DT->getNode(B->getParent());
5659     assert(NodeA && "Should only process reachable instructions");
5660     assert(NodeB && "Should only process reachable instructions");
5661     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5662            "Different nodes should have different DFS numbers");
5663     if (NodeA != NodeB)
5664       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5665     return B->comesBefore(A);
5666   });
5667 
5668   for (Instruction *Inst : OrderedScalars) {
5669     if (!PrevInst) {
5670       PrevInst = Inst;
5671       continue;
5672     }
5673 
5674     // Update LiveValues.
5675     LiveValues.erase(PrevInst);
5676     for (auto &J : PrevInst->operands()) {
5677       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5678         LiveValues.insert(cast<Instruction>(&*J));
5679     }
5680 
5681     LLVM_DEBUG({
5682       dbgs() << "SLP: #LV: " << LiveValues.size();
5683       for (auto *X : LiveValues)
5684         dbgs() << " " << X->getName();
5685       dbgs() << ", Looking at ";
5686       Inst->dump();
5687     });
5688 
5689     // Now find the sequence of instructions between PrevInst and Inst.
5690     unsigned NumCalls = 0;
5691     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5692                                  PrevInstIt =
5693                                      PrevInst->getIterator().getReverse();
5694     while (InstIt != PrevInstIt) {
5695       if (PrevInstIt == PrevInst->getParent()->rend()) {
5696         PrevInstIt = Inst->getParent()->rbegin();
5697         continue;
5698       }
5699 
5700       // Debug information does not impact spill cost.
5701       if ((isa<CallInst>(&*PrevInstIt) &&
5702            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5703           &*PrevInstIt != PrevInst)
5704         NumCalls++;
5705 
5706       ++PrevInstIt;
5707     }
5708 
5709     if (NumCalls) {
5710       SmallVector<Type*, 4> V;
5711       for (auto *II : LiveValues) {
5712         auto *ScalarTy = II->getType();
5713         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5714           ScalarTy = VectorTy->getElementType();
5715         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5716       }
5717       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5718     }
5719 
5720     PrevInst = Inst;
5721   }
5722 
5723   return Cost;
5724 }
5725 
5726 /// Check if two insertelement instructions are from the same buildvector.
5727 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5728                                             InsertElementInst *V) {
5729   // Instructions must be from the same basic blocks.
5730   if (VU->getParent() != V->getParent())
5731     return false;
5732   // Checks if 2 insertelements are from the same buildvector.
5733   if (VU->getType() != V->getType())
5734     return false;
5735   // Multiple used inserts are separate nodes.
5736   if (!VU->hasOneUse() && !V->hasOneUse())
5737     return false;
5738   auto *IE1 = VU;
5739   auto *IE2 = V;
5740   // Go through the vector operand of insertelement instructions trying to find
5741   // either VU as the original vector for IE2 or V as the original vector for
5742   // IE1.
5743   do {
5744     if (IE2 == VU || IE1 == V)
5745       return true;
5746     if (IE1) {
5747       if (IE1 != VU && !IE1->hasOneUse())
5748         IE1 = nullptr;
5749       else
5750         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5751     }
5752     if (IE2) {
5753       if (IE2 != V && !IE2->hasOneUse())
5754         IE2 = nullptr;
5755       else
5756         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5757     }
5758   } while (IE1 || IE2);
5759   return false;
5760 }
5761 
5762 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5763   InstructionCost Cost = 0;
5764   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5765                     << VectorizableTree.size() << ".\n");
5766 
5767   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5768 
5769   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5770     TreeEntry &TE = *VectorizableTree[I].get();
5771 
5772     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5773     Cost += C;
5774     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5775                       << " for bundle that starts with " << *TE.Scalars[0]
5776                       << ".\n"
5777                       << "SLP: Current total cost = " << Cost << "\n");
5778   }
5779 
5780   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5781   InstructionCost ExtractCost = 0;
5782   SmallVector<unsigned> VF;
5783   SmallVector<SmallVector<int>> ShuffleMask;
5784   SmallVector<Value *> FirstUsers;
5785   SmallVector<APInt> DemandedElts;
5786   for (ExternalUser &EU : ExternalUses) {
5787     // We only add extract cost once for the same scalar.
5788     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
5789         !ExtractCostCalculated.insert(EU.Scalar).second)
5790       continue;
5791 
5792     // Uses by ephemeral values are free (because the ephemeral value will be
5793     // removed prior to code generation, and so the extraction will be
5794     // removed as well).
5795     if (EphValues.count(EU.User))
5796       continue;
5797 
5798     // No extract cost for vector "scalar"
5799     if (isa<FixedVectorType>(EU.Scalar->getType()))
5800       continue;
5801 
5802     // Already counted the cost for external uses when tried to adjust the cost
5803     // for extractelements, no need to add it again.
5804     if (isa<ExtractElementInst>(EU.Scalar))
5805       continue;
5806 
5807     // If found user is an insertelement, do not calculate extract cost but try
5808     // to detect it as a final shuffled/identity match.
5809     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
5810       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
5811         Optional<int> InsertIdx = getInsertIndex(VU, 0);
5812         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5813           continue;
5814         auto *It = find_if(FirstUsers, [VU](Value *V) {
5815           return areTwoInsertFromSameBuildVector(VU,
5816                                                  cast<InsertElementInst>(V));
5817         });
5818         int VecId = -1;
5819         if (It == FirstUsers.end()) {
5820           VF.push_back(FTy->getNumElements());
5821           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5822           // Find the insertvector, vectorized in tree, if any.
5823           Value *Base = VU;
5824           while (isa<InsertElementInst>(Base)) {
5825             // Build the mask for the vectorized insertelement instructions.
5826             if (const TreeEntry *E = getTreeEntry(Base)) {
5827               VU = cast<InsertElementInst>(Base);
5828               do {
5829                 int Idx = E->findLaneForValue(Base);
5830                 ShuffleMask.back()[Idx] = Idx;
5831                 Base = cast<InsertElementInst>(Base)->getOperand(0);
5832               } while (E == getTreeEntry(Base));
5833               break;
5834             }
5835             Base = cast<InsertElementInst>(Base)->getOperand(0);
5836           }
5837           FirstUsers.push_back(VU);
5838           DemandedElts.push_back(APInt::getZero(VF.back()));
5839           VecId = FirstUsers.size() - 1;
5840         } else {
5841           VecId = std::distance(FirstUsers.begin(), It);
5842         }
5843         int Idx = *InsertIdx;
5844         ShuffleMask[VecId][Idx] = EU.Lane;
5845         DemandedElts[VecId].setBit(Idx);
5846         continue;
5847       }
5848     }
5849 
5850     // If we plan to rewrite the tree in a smaller type, we will need to sign
5851     // extend the extracted value back to the original type. Here, we account
5852     // for the extract and the added cost of the sign extend if needed.
5853     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5854     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5855     if (MinBWs.count(ScalarRoot)) {
5856       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5857       auto Extend =
5858           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5859       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5860       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5861                                                    VecTy, EU.Lane);
5862     } else {
5863       ExtractCost +=
5864           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5865     }
5866   }
5867 
5868   InstructionCost SpillCost = getSpillCost();
5869   Cost += SpillCost + ExtractCost;
5870   if (FirstUsers.size() == 1) {
5871     int Limit = ShuffleMask.front().size() * 2;
5872     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
5873         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
5874       InstructionCost C = TTI->getShuffleCost(
5875           TTI::SK_PermuteSingleSrc,
5876           cast<FixedVectorType>(FirstUsers.front()->getType()),
5877           ShuffleMask.front());
5878       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5879                         << " for final shuffle of insertelement external users "
5880                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5881                         << "SLP: Current total cost = " << Cost << "\n");
5882       Cost += C;
5883     }
5884     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5885         cast<FixedVectorType>(FirstUsers.front()->getType()),
5886         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
5887     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5888                       << " for insertelements gather.\n"
5889                       << "SLP: Current total cost = " << Cost << "\n");
5890     Cost -= InsertCost;
5891   } else if (FirstUsers.size() >= 2) {
5892     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
5893     // Combined masks of the first 2 vectors.
5894     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
5895     copy(ShuffleMask.front(), CombinedMask.begin());
5896     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
5897     auto *VecTy = FixedVectorType::get(
5898         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
5899         MaxVF);
5900     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
5901       if (ShuffleMask[1][I] != UndefMaskElem) {
5902         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
5903         CombinedDemandedElts.setBit(I);
5904       }
5905     }
5906     InstructionCost C =
5907         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5908     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5909                       << " for final shuffle of vector node and external "
5910                          "insertelement users "
5911                       << *VectorizableTree.front()->Scalars.front() << ".\n"
5912                       << "SLP: Current total cost = " << Cost << "\n");
5913     Cost += C;
5914     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5915         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
5916     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5917                       << " for insertelements gather.\n"
5918                       << "SLP: Current total cost = " << Cost << "\n");
5919     Cost -= InsertCost;
5920     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
5921       // Other elements - permutation of 2 vectors (the initial one and the
5922       // next Ith incoming vector).
5923       unsigned VF = ShuffleMask[I].size();
5924       for (unsigned Idx = 0; Idx < VF; ++Idx) {
5925         int Mask = ShuffleMask[I][Idx];
5926         if (Mask != UndefMaskElem)
5927           CombinedMask[Idx] = MaxVF + Mask;
5928         else if (CombinedMask[Idx] != UndefMaskElem)
5929           CombinedMask[Idx] = Idx;
5930       }
5931       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
5932         if (CombinedMask[Idx] != UndefMaskElem)
5933           CombinedMask[Idx] = Idx;
5934       InstructionCost C =
5935           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
5936       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5937                         << " for final shuffle of vector node and external "
5938                            "insertelement users "
5939                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5940                         << "SLP: Current total cost = " << Cost << "\n");
5941       Cost += C;
5942       InstructionCost InsertCost = TTI->getScalarizationOverhead(
5943           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
5944           /*Insert*/ true, /*Extract*/ false);
5945       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5946                         << " for insertelements gather.\n"
5947                         << "SLP: Current total cost = " << Cost << "\n");
5948       Cost -= InsertCost;
5949     }
5950   }
5951 
5952 #ifndef NDEBUG
5953   SmallString<256> Str;
5954   {
5955     raw_svector_ostream OS(Str);
5956     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
5957        << "SLP: Extract Cost = " << ExtractCost << ".\n"
5958        << "SLP: Total Cost = " << Cost << ".\n";
5959   }
5960   LLVM_DEBUG(dbgs() << Str);
5961   if (ViewSLPTree)
5962     ViewGraph(this, "SLP" + F->getName(), false, Str);
5963 #endif
5964 
5965   return Cost;
5966 }
5967 
5968 Optional<TargetTransformInfo::ShuffleKind>
5969 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
5970                                SmallVectorImpl<const TreeEntry *> &Entries) {
5971   // TODO: currently checking only for Scalars in the tree entry, need to count
5972   // reused elements too for better cost estimation.
5973   Mask.assign(TE->Scalars.size(), UndefMaskElem);
5974   Entries.clear();
5975   // Build a lists of values to tree entries.
5976   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
5977   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
5978     if (EntryPtr.get() == TE)
5979       break;
5980     if (EntryPtr->State != TreeEntry::NeedToGather)
5981       continue;
5982     for (Value *V : EntryPtr->Scalars)
5983       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
5984   }
5985   // Find all tree entries used by the gathered values. If no common entries
5986   // found - not a shuffle.
5987   // Here we build a set of tree nodes for each gathered value and trying to
5988   // find the intersection between these sets. If we have at least one common
5989   // tree node for each gathered value - we have just a permutation of the
5990   // single vector. If we have 2 different sets, we're in situation where we
5991   // have a permutation of 2 input vectors.
5992   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
5993   DenseMap<Value *, int> UsedValuesEntry;
5994   for (Value *V : TE->Scalars) {
5995     if (isa<UndefValue>(V))
5996       continue;
5997     // Build a list of tree entries where V is used.
5998     SmallPtrSet<const TreeEntry *, 4> VToTEs;
5999     auto It = ValueToTEs.find(V);
6000     if (It != ValueToTEs.end())
6001       VToTEs = It->second;
6002     if (const TreeEntry *VTE = getTreeEntry(V))
6003       VToTEs.insert(VTE);
6004     if (VToTEs.empty())
6005       return None;
6006     if (UsedTEs.empty()) {
6007       // The first iteration, just insert the list of nodes to vector.
6008       UsedTEs.push_back(VToTEs);
6009     } else {
6010       // Need to check if there are any previously used tree nodes which use V.
6011       // If there are no such nodes, consider that we have another one input
6012       // vector.
6013       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6014       unsigned Idx = 0;
6015       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6016         // Do we have a non-empty intersection of previously listed tree entries
6017         // and tree entries using current V?
6018         set_intersect(VToTEs, Set);
6019         if (!VToTEs.empty()) {
6020           // Yes, write the new subset and continue analysis for the next
6021           // scalar.
6022           Set.swap(VToTEs);
6023           break;
6024         }
6025         VToTEs = SavedVToTEs;
6026         ++Idx;
6027       }
6028       // No non-empty intersection found - need to add a second set of possible
6029       // source vectors.
6030       if (Idx == UsedTEs.size()) {
6031         // If the number of input vectors is greater than 2 - not a permutation,
6032         // fallback to the regular gather.
6033         if (UsedTEs.size() == 2)
6034           return None;
6035         UsedTEs.push_back(SavedVToTEs);
6036         Idx = UsedTEs.size() - 1;
6037       }
6038       UsedValuesEntry.try_emplace(V, Idx);
6039     }
6040   }
6041 
6042   unsigned VF = 0;
6043   if (UsedTEs.size() == 1) {
6044     // Try to find the perfect match in another gather node at first.
6045     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6046       return EntryPtr->isSame(TE->Scalars);
6047     });
6048     if (It != UsedTEs.front().end()) {
6049       Entries.push_back(*It);
6050       std::iota(Mask.begin(), Mask.end(), 0);
6051       return TargetTransformInfo::SK_PermuteSingleSrc;
6052     }
6053     // No perfect match, just shuffle, so choose the first tree node.
6054     Entries.push_back(*UsedTEs.front().begin());
6055   } else {
6056     // Try to find nodes with the same vector factor.
6057     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6058     DenseMap<int, const TreeEntry *> VFToTE;
6059     for (const TreeEntry *TE : UsedTEs.front())
6060       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6061     for (const TreeEntry *TE : UsedTEs.back()) {
6062       auto It = VFToTE.find(TE->getVectorFactor());
6063       if (It != VFToTE.end()) {
6064         VF = It->first;
6065         Entries.push_back(It->second);
6066         Entries.push_back(TE);
6067         break;
6068       }
6069     }
6070     // No 2 source vectors with the same vector factor - give up and do regular
6071     // gather.
6072     if (Entries.empty())
6073       return None;
6074   }
6075 
6076   // Build a shuffle mask for better cost estimation and vector emission.
6077   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6078     Value *V = TE->Scalars[I];
6079     if (isa<UndefValue>(V))
6080       continue;
6081     unsigned Idx = UsedValuesEntry.lookup(V);
6082     const TreeEntry *VTE = Entries[Idx];
6083     int FoundLane = VTE->findLaneForValue(V);
6084     Mask[I] = Idx * VF + FoundLane;
6085     // Extra check required by isSingleSourceMaskImpl function (called by
6086     // ShuffleVectorInst::isSingleSourceMask).
6087     if (Mask[I] >= 2 * E)
6088       return None;
6089   }
6090   switch (Entries.size()) {
6091   case 1:
6092     return TargetTransformInfo::SK_PermuteSingleSrc;
6093   case 2:
6094     return TargetTransformInfo::SK_PermuteTwoSrc;
6095   default:
6096     break;
6097   }
6098   return None;
6099 }
6100 
6101 InstructionCost
6102 BoUpSLP::getGatherCost(FixedVectorType *Ty,
6103                        const DenseSet<unsigned> &ShuffledIndices,
6104                        bool NeedToShuffle) const {
6105   unsigned NumElts = Ty->getNumElements();
6106   APInt DemandedElts = APInt::getZero(NumElts);
6107   for (unsigned I = 0; I < NumElts; ++I)
6108     if (!ShuffledIndices.count(I))
6109       DemandedElts.setBit(I);
6110   InstructionCost Cost =
6111       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
6112                                     /*Extract*/ false);
6113   if (NeedToShuffle)
6114     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6115   return Cost;
6116 }
6117 
6118 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6119   // Find the type of the operands in VL.
6120   Type *ScalarTy = VL[0]->getType();
6121   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6122     ScalarTy = SI->getValueOperand()->getType();
6123   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6124   bool DuplicateNonConst = false;
6125   // Find the cost of inserting/extracting values from the vector.
6126   // Check if the same elements are inserted several times and count them as
6127   // shuffle candidates.
6128   DenseSet<unsigned> ShuffledElements;
6129   DenseSet<Value *> UniqueElements;
6130   // Iterate in reverse order to consider insert elements with the high cost.
6131   for (unsigned I = VL.size(); I > 0; --I) {
6132     unsigned Idx = I - 1;
6133     // No need to shuffle duplicates for constants.
6134     if (isConstant(VL[Idx])) {
6135       ShuffledElements.insert(Idx);
6136       continue;
6137     }
6138     if (!UniqueElements.insert(VL[Idx]).second) {
6139       DuplicateNonConst = true;
6140       ShuffledElements.insert(Idx);
6141     }
6142   }
6143   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6144 }
6145 
6146 // Perform operand reordering on the instructions in VL and return the reordered
6147 // operands in Left and Right.
6148 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6149                                              SmallVectorImpl<Value *> &Left,
6150                                              SmallVectorImpl<Value *> &Right,
6151                                              const DataLayout &DL,
6152                                              ScalarEvolution &SE,
6153                                              const BoUpSLP &R) {
6154   if (VL.empty())
6155     return;
6156   VLOperands Ops(VL, DL, SE, R);
6157   // Reorder the operands in place.
6158   Ops.reorder();
6159   Left = Ops.getVL(0);
6160   Right = Ops.getVL(1);
6161 }
6162 
6163 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6164   // Get the basic block this bundle is in. All instructions in the bundle
6165   // should be in this block.
6166   auto *Front = E->getMainOp();
6167   auto *BB = Front->getParent();
6168   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6169     auto *I = cast<Instruction>(V);
6170     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6171   }));
6172 
6173   // The last instruction in the bundle in program order.
6174   Instruction *LastInst = nullptr;
6175 
6176   // Find the last instruction. The common case should be that BB has been
6177   // scheduled, and the last instruction is VL.back(). So we start with
6178   // VL.back() and iterate over schedule data until we reach the end of the
6179   // bundle. The end of the bundle is marked by null ScheduleData.
6180   if (BlocksSchedules.count(BB)) {
6181     auto *Bundle =
6182         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6183     if (Bundle && Bundle->isPartOfBundle())
6184       for (; Bundle; Bundle = Bundle->NextInBundle)
6185         if (Bundle->OpValue == Bundle->Inst)
6186           LastInst = Bundle->Inst;
6187   }
6188 
6189   // LastInst can still be null at this point if there's either not an entry
6190   // for BB in BlocksSchedules or there's no ScheduleData available for
6191   // VL.back(). This can be the case if buildTree_rec aborts for various
6192   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6193   // size is reached, etc.). ScheduleData is initialized in the scheduling
6194   // "dry-run".
6195   //
6196   // If this happens, we can still find the last instruction by brute force. We
6197   // iterate forwards from Front (inclusive) until we either see all
6198   // instructions in the bundle or reach the end of the block. If Front is the
6199   // last instruction in program order, LastInst will be set to Front, and we
6200   // will visit all the remaining instructions in the block.
6201   //
6202   // One of the reasons we exit early from buildTree_rec is to place an upper
6203   // bound on compile-time. Thus, taking an additional compile-time hit here is
6204   // not ideal. However, this should be exceedingly rare since it requires that
6205   // we both exit early from buildTree_rec and that the bundle be out-of-order
6206   // (causing us to iterate all the way to the end of the block).
6207   if (!LastInst) {
6208     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6209     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6210       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6211         LastInst = &I;
6212       if (Bundle.empty())
6213         break;
6214     }
6215   }
6216   assert(LastInst && "Failed to find last instruction in bundle");
6217 
6218   // Set the insertion point after the last instruction in the bundle. Set the
6219   // debug location to Front.
6220   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6221   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6222 }
6223 
6224 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6225   // List of instructions/lanes from current block and/or the blocks which are
6226   // part of the current loop. These instructions will be inserted at the end to
6227   // make it possible to optimize loops and hoist invariant instructions out of
6228   // the loops body with better chances for success.
6229   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6230   SmallSet<int, 4> PostponedIndices;
6231   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6232   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6233     SmallPtrSet<BasicBlock *, 4> Visited;
6234     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6235       InsertBB = InsertBB->getSinglePredecessor();
6236     return InsertBB && InsertBB == InstBB;
6237   };
6238   for (int I = 0, E = VL.size(); I < E; ++I) {
6239     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6240       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6241            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6242           PostponedIndices.insert(I).second)
6243         PostponedInsts.emplace_back(Inst, I);
6244   }
6245 
6246   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6247     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6248     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6249     if (!InsElt)
6250       return Vec;
6251     GatherShuffleSeq.insert(InsElt);
6252     CSEBlocks.insert(InsElt->getParent());
6253     // Add to our 'need-to-extract' list.
6254     if (TreeEntry *Entry = getTreeEntry(V)) {
6255       // Find which lane we need to extract.
6256       unsigned FoundLane = Entry->findLaneForValue(V);
6257       ExternalUses.emplace_back(V, InsElt, FoundLane);
6258     }
6259     return Vec;
6260   };
6261   Value *Val0 =
6262       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6263   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6264   Value *Vec = PoisonValue::get(VecTy);
6265   SmallVector<int> NonConsts;
6266   // Insert constant values at first.
6267   for (int I = 0, E = VL.size(); I < E; ++I) {
6268     if (PostponedIndices.contains(I))
6269       continue;
6270     if (!isConstant(VL[I])) {
6271       NonConsts.push_back(I);
6272       continue;
6273     }
6274     Vec = CreateInsertElement(Vec, VL[I], I);
6275   }
6276   // Insert non-constant values.
6277   for (int I : NonConsts)
6278     Vec = CreateInsertElement(Vec, VL[I], I);
6279   // Append instructions, which are/may be part of the loop, in the end to make
6280   // it possible to hoist non-loop-based instructions.
6281   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6282     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6283 
6284   return Vec;
6285 }
6286 
6287 namespace {
6288 /// Merges shuffle masks and emits final shuffle instruction, if required.
6289 class ShuffleInstructionBuilder {
6290   IRBuilderBase &Builder;
6291   const unsigned VF = 0;
6292   bool IsFinalized = false;
6293   SmallVector<int, 4> Mask;
6294   /// Holds all of the instructions that we gathered.
6295   SetVector<Instruction *> &GatherShuffleSeq;
6296   /// A list of blocks that we are going to CSE.
6297   SetVector<BasicBlock *> &CSEBlocks;
6298 
6299 public:
6300   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6301                             SetVector<Instruction *> &GatherShuffleSeq,
6302                             SetVector<BasicBlock *> &CSEBlocks)
6303       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6304         CSEBlocks(CSEBlocks) {}
6305 
6306   /// Adds a mask, inverting it before applying.
6307   void addInversedMask(ArrayRef<unsigned> SubMask) {
6308     if (SubMask.empty())
6309       return;
6310     SmallVector<int, 4> NewMask;
6311     inversePermutation(SubMask, NewMask);
6312     addMask(NewMask);
6313   }
6314 
6315   /// Functions adds masks, merging them into  single one.
6316   void addMask(ArrayRef<unsigned> SubMask) {
6317     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6318     addMask(NewMask);
6319   }
6320 
6321   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6322 
6323   Value *finalize(Value *V) {
6324     IsFinalized = true;
6325     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6326     if (VF == ValueVF && Mask.empty())
6327       return V;
6328     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6329     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6330     addMask(NormalizedMask);
6331 
6332     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6333       return V;
6334     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6335     if (auto *I = dyn_cast<Instruction>(Vec)) {
6336       GatherShuffleSeq.insert(I);
6337       CSEBlocks.insert(I->getParent());
6338     }
6339     return Vec;
6340   }
6341 
6342   ~ShuffleInstructionBuilder() {
6343     assert((IsFinalized || Mask.empty()) &&
6344            "Shuffle construction must be finalized.");
6345   }
6346 };
6347 } // namespace
6348 
6349 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6350   unsigned VF = VL.size();
6351   InstructionsState S = getSameOpcode(VL);
6352   if (S.getOpcode()) {
6353     if (TreeEntry *E = getTreeEntry(S.OpValue))
6354       if (E->isSame(VL)) {
6355         Value *V = vectorizeTree(E);
6356         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6357           if (!E->ReuseShuffleIndices.empty()) {
6358             // Reshuffle to get only unique values.
6359             // If some of the scalars are duplicated in the vectorization tree
6360             // entry, we do not vectorize them but instead generate a mask for
6361             // the reuses. But if there are several users of the same entry,
6362             // they may have different vectorization factors. This is especially
6363             // important for PHI nodes. In this case, we need to adapt the
6364             // resulting instruction for the user vectorization factor and have
6365             // to reshuffle it again to take only unique elements of the vector.
6366             // Without this code the function incorrectly returns reduced vector
6367             // instruction with the same elements, not with the unique ones.
6368 
6369             // block:
6370             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6371             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6372             // ... (use %2)
6373             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6374             // br %block
6375             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6376             SmallSet<int, 4> UsedIdxs;
6377             int Pos = 0;
6378             int Sz = VL.size();
6379             for (int Idx : E->ReuseShuffleIndices) {
6380               if (Idx != Sz && Idx != UndefMaskElem &&
6381                   UsedIdxs.insert(Idx).second)
6382                 UniqueIdxs[Idx] = Pos;
6383               ++Pos;
6384             }
6385             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6386                                             "less than original vector size.");
6387             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6388             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6389           } else {
6390             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6391                    "Expected vectorization factor less "
6392                    "than original vector size.");
6393             SmallVector<int> UniformMask(VF, 0);
6394             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6395             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6396           }
6397           if (auto *I = dyn_cast<Instruction>(V)) {
6398             GatherShuffleSeq.insert(I);
6399             CSEBlocks.insert(I->getParent());
6400           }
6401         }
6402         return V;
6403       }
6404   }
6405 
6406   // Check that every instruction appears once in this bundle.
6407   SmallVector<int> ReuseShuffleIndicies;
6408   SmallVector<Value *> UniqueValues;
6409   if (VL.size() > 2) {
6410     DenseMap<Value *, unsigned> UniquePositions;
6411     unsigned NumValues =
6412         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6413                                     return !isa<UndefValue>(V);
6414                                   }).base());
6415     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6416     int UniqueVals = 0;
6417     for (Value *V : VL.drop_back(VL.size() - VF)) {
6418       if (isa<UndefValue>(V)) {
6419         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6420         continue;
6421       }
6422       if (isConstant(V)) {
6423         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6424         UniqueValues.emplace_back(V);
6425         continue;
6426       }
6427       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6428       ReuseShuffleIndicies.emplace_back(Res.first->second);
6429       if (Res.second) {
6430         UniqueValues.emplace_back(V);
6431         ++UniqueVals;
6432       }
6433     }
6434     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6435       // Emit pure splat vector.
6436       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6437                                   UndefMaskElem);
6438     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6439       ReuseShuffleIndicies.clear();
6440       UniqueValues.clear();
6441       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6442     }
6443     UniqueValues.append(VF - UniqueValues.size(),
6444                         PoisonValue::get(VL[0]->getType()));
6445     VL = UniqueValues;
6446   }
6447 
6448   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6449                                            CSEBlocks);
6450   Value *Vec = gather(VL);
6451   if (!ReuseShuffleIndicies.empty()) {
6452     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6453     Vec = ShuffleBuilder.finalize(Vec);
6454   }
6455   return Vec;
6456 }
6457 
6458 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6459   IRBuilder<>::InsertPointGuard Guard(Builder);
6460 
6461   if (E->VectorizedValue) {
6462     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6463     return E->VectorizedValue;
6464   }
6465 
6466   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6467   unsigned VF = E->getVectorFactor();
6468   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6469                                            CSEBlocks);
6470   if (E->State == TreeEntry::NeedToGather) {
6471     if (E->getMainOp())
6472       setInsertPointAfterBundle(E);
6473     Value *Vec;
6474     SmallVector<int> Mask;
6475     SmallVector<const TreeEntry *> Entries;
6476     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6477         isGatherShuffledEntry(E, Mask, Entries);
6478     if (Shuffle.hasValue()) {
6479       assert((Entries.size() == 1 || Entries.size() == 2) &&
6480              "Expected shuffle of 1 or 2 entries.");
6481       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6482                                         Entries.back()->VectorizedValue, Mask);
6483       if (auto *I = dyn_cast<Instruction>(Vec)) {
6484         GatherShuffleSeq.insert(I);
6485         CSEBlocks.insert(I->getParent());
6486       }
6487     } else {
6488       Vec = gather(E->Scalars);
6489     }
6490     if (NeedToShuffleReuses) {
6491       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6492       Vec = ShuffleBuilder.finalize(Vec);
6493     }
6494     E->VectorizedValue = Vec;
6495     return Vec;
6496   }
6497 
6498   assert((E->State == TreeEntry::Vectorize ||
6499           E->State == TreeEntry::ScatterVectorize) &&
6500          "Unhandled state");
6501   unsigned ShuffleOrOp =
6502       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6503   Instruction *VL0 = E->getMainOp();
6504   Type *ScalarTy = VL0->getType();
6505   if (auto *Store = dyn_cast<StoreInst>(VL0))
6506     ScalarTy = Store->getValueOperand()->getType();
6507   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6508     ScalarTy = IE->getOperand(1)->getType();
6509   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6510   switch (ShuffleOrOp) {
6511     case Instruction::PHI: {
6512       assert(
6513           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6514           "PHI reordering is free.");
6515       auto *PH = cast<PHINode>(VL0);
6516       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6517       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6518       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6519       Value *V = NewPhi;
6520       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6521       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6522       V = ShuffleBuilder.finalize(V);
6523 
6524       E->VectorizedValue = V;
6525 
6526       // PHINodes may have multiple entries from the same block. We want to
6527       // visit every block once.
6528       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6529 
6530       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6531         ValueList Operands;
6532         BasicBlock *IBB = PH->getIncomingBlock(i);
6533 
6534         if (!VisitedBBs.insert(IBB).second) {
6535           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6536           continue;
6537         }
6538 
6539         Builder.SetInsertPoint(IBB->getTerminator());
6540         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6541         Value *Vec = vectorizeTree(E->getOperand(i));
6542         NewPhi->addIncoming(Vec, IBB);
6543       }
6544 
6545       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6546              "Invalid number of incoming values");
6547       return V;
6548     }
6549 
6550     case Instruction::ExtractElement: {
6551       Value *V = E->getSingleOperand(0);
6552       Builder.SetInsertPoint(VL0);
6553       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6554       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6555       V = ShuffleBuilder.finalize(V);
6556       E->VectorizedValue = V;
6557       return V;
6558     }
6559     case Instruction::ExtractValue: {
6560       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6561       Builder.SetInsertPoint(LI);
6562       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6563       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6564       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6565       Value *NewV = propagateMetadata(V, E->Scalars);
6566       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6567       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6568       NewV = ShuffleBuilder.finalize(NewV);
6569       E->VectorizedValue = NewV;
6570       return NewV;
6571     }
6572     case Instruction::InsertElement: {
6573       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6574       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6575       Value *V = vectorizeTree(E->getOperand(1));
6576 
6577       // Create InsertVector shuffle if necessary
6578       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6579         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6580       }));
6581       const unsigned NumElts =
6582           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6583       const unsigned NumScalars = E->Scalars.size();
6584 
6585       unsigned Offset = *getInsertIndex(VL0, 0);
6586       assert(Offset < NumElts && "Failed to find vector index offset");
6587 
6588       // Create shuffle to resize vector
6589       SmallVector<int> Mask;
6590       if (!E->ReorderIndices.empty()) {
6591         inversePermutation(E->ReorderIndices, Mask);
6592         Mask.append(NumElts - NumScalars, UndefMaskElem);
6593       } else {
6594         Mask.assign(NumElts, UndefMaskElem);
6595         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6596       }
6597       // Create InsertVector shuffle if necessary
6598       bool IsIdentity = true;
6599       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6600       Mask.swap(PrevMask);
6601       for (unsigned I = 0; I < NumScalars; ++I) {
6602         Value *Scalar = E->Scalars[PrevMask[I]];
6603         Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
6604         if (!InsertIdx || *InsertIdx == UndefMaskElem)
6605           continue;
6606         IsIdentity &= *InsertIdx - Offset == I;
6607         Mask[*InsertIdx - Offset] = I;
6608       }
6609       if (!IsIdentity || NumElts != NumScalars) {
6610         V = Builder.CreateShuffleVector(V, Mask);
6611         if (auto *I = dyn_cast<Instruction>(V)) {
6612           GatherShuffleSeq.insert(I);
6613           CSEBlocks.insert(I->getParent());
6614         }
6615       }
6616 
6617       if ((!IsIdentity || Offset != 0 ||
6618            !isUndefVector(FirstInsert->getOperand(0))) &&
6619           NumElts != NumScalars) {
6620         SmallVector<int> InsertMask(NumElts);
6621         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6622         for (unsigned I = 0; I < NumElts; I++) {
6623           if (Mask[I] != UndefMaskElem)
6624             InsertMask[Offset + I] = NumElts + I;
6625         }
6626 
6627         V = Builder.CreateShuffleVector(
6628             FirstInsert->getOperand(0), V, InsertMask,
6629             cast<Instruction>(E->Scalars.back())->getName());
6630         if (auto *I = dyn_cast<Instruction>(V)) {
6631           GatherShuffleSeq.insert(I);
6632           CSEBlocks.insert(I->getParent());
6633         }
6634       }
6635 
6636       ++NumVectorInstructions;
6637       E->VectorizedValue = V;
6638       return V;
6639     }
6640     case Instruction::ZExt:
6641     case Instruction::SExt:
6642     case Instruction::FPToUI:
6643     case Instruction::FPToSI:
6644     case Instruction::FPExt:
6645     case Instruction::PtrToInt:
6646     case Instruction::IntToPtr:
6647     case Instruction::SIToFP:
6648     case Instruction::UIToFP:
6649     case Instruction::Trunc:
6650     case Instruction::FPTrunc:
6651     case Instruction::BitCast: {
6652       setInsertPointAfterBundle(E);
6653 
6654       Value *InVec = vectorizeTree(E->getOperand(0));
6655 
6656       if (E->VectorizedValue) {
6657         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6658         return E->VectorizedValue;
6659       }
6660 
6661       auto *CI = cast<CastInst>(VL0);
6662       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6663       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6664       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6665       V = ShuffleBuilder.finalize(V);
6666 
6667       E->VectorizedValue = V;
6668       ++NumVectorInstructions;
6669       return V;
6670     }
6671     case Instruction::FCmp:
6672     case Instruction::ICmp: {
6673       setInsertPointAfterBundle(E);
6674 
6675       Value *L = vectorizeTree(E->getOperand(0));
6676       Value *R = vectorizeTree(E->getOperand(1));
6677 
6678       if (E->VectorizedValue) {
6679         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6680         return E->VectorizedValue;
6681       }
6682 
6683       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6684       Value *V = Builder.CreateCmp(P0, L, R);
6685       propagateIRFlags(V, E->Scalars, VL0);
6686       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6687       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6688       V = ShuffleBuilder.finalize(V);
6689 
6690       E->VectorizedValue = V;
6691       ++NumVectorInstructions;
6692       return V;
6693     }
6694     case Instruction::Select: {
6695       setInsertPointAfterBundle(E);
6696 
6697       Value *Cond = vectorizeTree(E->getOperand(0));
6698       Value *True = vectorizeTree(E->getOperand(1));
6699       Value *False = vectorizeTree(E->getOperand(2));
6700 
6701       if (E->VectorizedValue) {
6702         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6703         return E->VectorizedValue;
6704       }
6705 
6706       Value *V = Builder.CreateSelect(Cond, True, False);
6707       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6708       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6709       V = ShuffleBuilder.finalize(V);
6710 
6711       E->VectorizedValue = V;
6712       ++NumVectorInstructions;
6713       return V;
6714     }
6715     case Instruction::FNeg: {
6716       setInsertPointAfterBundle(E);
6717 
6718       Value *Op = vectorizeTree(E->getOperand(0));
6719 
6720       if (E->VectorizedValue) {
6721         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6722         return E->VectorizedValue;
6723       }
6724 
6725       Value *V = Builder.CreateUnOp(
6726           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6727       propagateIRFlags(V, E->Scalars, VL0);
6728       if (auto *I = dyn_cast<Instruction>(V))
6729         V = propagateMetadata(I, E->Scalars);
6730 
6731       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6732       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6733       V = ShuffleBuilder.finalize(V);
6734 
6735       E->VectorizedValue = V;
6736       ++NumVectorInstructions;
6737 
6738       return V;
6739     }
6740     case Instruction::Add:
6741     case Instruction::FAdd:
6742     case Instruction::Sub:
6743     case Instruction::FSub:
6744     case Instruction::Mul:
6745     case Instruction::FMul:
6746     case Instruction::UDiv:
6747     case Instruction::SDiv:
6748     case Instruction::FDiv:
6749     case Instruction::URem:
6750     case Instruction::SRem:
6751     case Instruction::FRem:
6752     case Instruction::Shl:
6753     case Instruction::LShr:
6754     case Instruction::AShr:
6755     case Instruction::And:
6756     case Instruction::Or:
6757     case Instruction::Xor: {
6758       setInsertPointAfterBundle(E);
6759 
6760       Value *LHS = vectorizeTree(E->getOperand(0));
6761       Value *RHS = vectorizeTree(E->getOperand(1));
6762 
6763       if (E->VectorizedValue) {
6764         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6765         return E->VectorizedValue;
6766       }
6767 
6768       Value *V = Builder.CreateBinOp(
6769           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6770           RHS);
6771       propagateIRFlags(V, E->Scalars, VL0);
6772       if (auto *I = dyn_cast<Instruction>(V))
6773         V = propagateMetadata(I, E->Scalars);
6774 
6775       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6776       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6777       V = ShuffleBuilder.finalize(V);
6778 
6779       E->VectorizedValue = V;
6780       ++NumVectorInstructions;
6781 
6782       return V;
6783     }
6784     case Instruction::Load: {
6785       // Loads are inserted at the head of the tree because we don't want to
6786       // sink them all the way down past store instructions.
6787       setInsertPointAfterBundle(E);
6788 
6789       LoadInst *LI = cast<LoadInst>(VL0);
6790       Instruction *NewLI;
6791       unsigned AS = LI->getPointerAddressSpace();
6792       Value *PO = LI->getPointerOperand();
6793       if (E->State == TreeEntry::Vectorize) {
6794 
6795         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6796 
6797         // The pointer operand uses an in-tree scalar so we add the new BitCast
6798         // to ExternalUses list to make sure that an extract will be generated
6799         // in the future.
6800         if (TreeEntry *Entry = getTreeEntry(PO)) {
6801           // Find which lane we need to extract.
6802           unsigned FoundLane = Entry->findLaneForValue(PO);
6803           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6804         }
6805 
6806         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6807       } else {
6808         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6809         Value *VecPtr = vectorizeTree(E->getOperand(0));
6810         // Use the minimum alignment of the gathered loads.
6811         Align CommonAlignment = LI->getAlign();
6812         for (Value *V : E->Scalars)
6813           CommonAlignment =
6814               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6815         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6816       }
6817       Value *V = propagateMetadata(NewLI, E->Scalars);
6818 
6819       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6820       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6821       V = ShuffleBuilder.finalize(V);
6822       E->VectorizedValue = V;
6823       ++NumVectorInstructions;
6824       return V;
6825     }
6826     case Instruction::Store: {
6827       auto *SI = cast<StoreInst>(VL0);
6828       unsigned AS = SI->getPointerAddressSpace();
6829 
6830       setInsertPointAfterBundle(E);
6831 
6832       Value *VecValue = vectorizeTree(E->getOperand(0));
6833       ShuffleBuilder.addMask(E->ReorderIndices);
6834       VecValue = ShuffleBuilder.finalize(VecValue);
6835 
6836       Value *ScalarPtr = SI->getPointerOperand();
6837       Value *VecPtr = Builder.CreateBitCast(
6838           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6839       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6840                                                  SI->getAlign());
6841 
6842       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6843       // ExternalUses to make sure that an extract will be generated in the
6844       // future.
6845       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6846         // Find which lane we need to extract.
6847         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6848         ExternalUses.push_back(
6849             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6850       }
6851 
6852       Value *V = propagateMetadata(ST, E->Scalars);
6853 
6854       E->VectorizedValue = V;
6855       ++NumVectorInstructions;
6856       return V;
6857     }
6858     case Instruction::GetElementPtr: {
6859       auto *GEP0 = cast<GetElementPtrInst>(VL0);
6860       setInsertPointAfterBundle(E);
6861 
6862       Value *Op0 = vectorizeTree(E->getOperand(0));
6863 
6864       SmallVector<Value *> OpVecs;
6865       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
6866         Value *OpVec = vectorizeTree(E->getOperand(J));
6867         OpVecs.push_back(OpVec);
6868       }
6869 
6870       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
6871       if (Instruction *I = dyn_cast<Instruction>(V))
6872         V = propagateMetadata(I, E->Scalars);
6873 
6874       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6875       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6876       V = ShuffleBuilder.finalize(V);
6877 
6878       E->VectorizedValue = V;
6879       ++NumVectorInstructions;
6880 
6881       return V;
6882     }
6883     case Instruction::Call: {
6884       CallInst *CI = cast<CallInst>(VL0);
6885       setInsertPointAfterBundle(E);
6886 
6887       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6888       if (Function *FI = CI->getCalledFunction())
6889         IID = FI->getIntrinsicID();
6890 
6891       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6892 
6893       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6894       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6895                           VecCallCosts.first <= VecCallCosts.second;
6896 
6897       Value *ScalarArg = nullptr;
6898       std::vector<Value *> OpVecs;
6899       SmallVector<Type *, 2> TysForDecl =
6900           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6901       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
6902         ValueList OpVL;
6903         // Some intrinsics have scalar arguments. This argument should not be
6904         // vectorized.
6905         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
6906           CallInst *CEI = cast<CallInst>(VL0);
6907           ScalarArg = CEI->getArgOperand(j);
6908           OpVecs.push_back(CEI->getArgOperand(j));
6909           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
6910             TysForDecl.push_back(ScalarArg->getType());
6911           continue;
6912         }
6913 
6914         Value *OpVec = vectorizeTree(E->getOperand(j));
6915         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
6916         OpVecs.push_back(OpVec);
6917       }
6918 
6919       Function *CF;
6920       if (!UseIntrinsic) {
6921         VFShape Shape =
6922             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
6923                                   VecTy->getNumElements())),
6924                          false /*HasGlobalPred*/);
6925         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
6926       } else {
6927         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
6928       }
6929 
6930       SmallVector<OperandBundleDef, 1> OpBundles;
6931       CI->getOperandBundlesAsDefs(OpBundles);
6932       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
6933 
6934       // The scalar argument uses an in-tree scalar so we add the new vectorized
6935       // call to ExternalUses list to make sure that an extract will be
6936       // generated in the future.
6937       if (ScalarArg) {
6938         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
6939           // Find which lane we need to extract.
6940           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
6941           ExternalUses.push_back(
6942               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
6943         }
6944       }
6945 
6946       propagateIRFlags(V, E->Scalars, VL0);
6947       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6948       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6949       V = ShuffleBuilder.finalize(V);
6950 
6951       E->VectorizedValue = V;
6952       ++NumVectorInstructions;
6953       return V;
6954     }
6955     case Instruction::ShuffleVector: {
6956       assert(E->isAltShuffle() &&
6957              ((Instruction::isBinaryOp(E->getOpcode()) &&
6958                Instruction::isBinaryOp(E->getAltOpcode())) ||
6959               (Instruction::isCast(E->getOpcode()) &&
6960                Instruction::isCast(E->getAltOpcode())) ||
6961               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
6962              "Invalid Shuffle Vector Operand");
6963 
6964       Value *LHS = nullptr, *RHS = nullptr;
6965       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
6966         setInsertPointAfterBundle(E);
6967         LHS = vectorizeTree(E->getOperand(0));
6968         RHS = vectorizeTree(E->getOperand(1));
6969       } else {
6970         setInsertPointAfterBundle(E);
6971         LHS = vectorizeTree(E->getOperand(0));
6972       }
6973 
6974       if (E->VectorizedValue) {
6975         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6976         return E->VectorizedValue;
6977       }
6978 
6979       Value *V0, *V1;
6980       if (Instruction::isBinaryOp(E->getOpcode())) {
6981         V0 = Builder.CreateBinOp(
6982             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
6983         V1 = Builder.CreateBinOp(
6984             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
6985       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
6986         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
6987         auto *AltCI = cast<CmpInst>(E->getAltOp());
6988         CmpInst::Predicate AltPred = AltCI->getPredicate();
6989         unsigned AltIdx =
6990             std::distance(E->Scalars.begin(), find(E->Scalars, AltCI));
6991         if (AltCI->getOperand(0) != E->getOperand(0)[AltIdx])
6992           AltPred = CmpInst::getSwappedPredicate(AltPred);
6993         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
6994       } else {
6995         V0 = Builder.CreateCast(
6996             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
6997         V1 = Builder.CreateCast(
6998             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
6999       }
7000       // Add V0 and V1 to later analysis to try to find and remove matching
7001       // instruction, if any.
7002       for (Value *V : {V0, V1}) {
7003         if (auto *I = dyn_cast<Instruction>(V)) {
7004           GatherShuffleSeq.insert(I);
7005           CSEBlocks.insert(I->getParent());
7006         }
7007       }
7008 
7009       // Create shuffle to take alternate operations from the vector.
7010       // Also, gather up main and alt scalar ops to propagate IR flags to
7011       // each vector operation.
7012       ValueList OpScalars, AltScalars;
7013       SmallVector<int> Mask;
7014       buildSuffleEntryMask(
7015           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7016           [E](Instruction *I) {
7017             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7018             if (auto *CI0 = dyn_cast<CmpInst>(E->getMainOp())) {
7019               auto *AltCI0 = cast<CmpInst>(E->getAltOp());
7020               auto *CI = cast<CmpInst>(I);
7021               CmpInst::Predicate P0 = CI0->getPredicate();
7022               CmpInst::Predicate AltP0 = AltCI0->getPredicate();
7023               CmpInst::Predicate AltP0Swapped =
7024                   CmpInst::getSwappedPredicate(AltP0);
7025               CmpInst::Predicate CurrentPred = CI->getPredicate();
7026               CmpInst::Predicate CurrentPredSwapped =
7027                   CmpInst::getSwappedPredicate(CurrentPred);
7028               if (P0 == AltP0 || P0 == AltP0Swapped) {
7029                 unsigned Idx =
7030                     std::distance(E->Scalars.begin(), find(E->Scalars, I));
7031                 // Alternate cmps have same/swapped predicate as main cmps but
7032                 // different order of compatible operands.
7033                 ArrayRef<Value *> VLOp0 = E->getOperand(0);
7034                 return (P0 == CurrentPred && CI->getOperand(0) != VLOp0[Idx]) ||
7035                        (P0 == CurrentPredSwapped &&
7036                         CI->getOperand(1) != VLOp0[Idx]);
7037               }
7038               return CurrentPred != P0 && CurrentPredSwapped != P0;
7039             }
7040             return I->getOpcode() == E->getAltOpcode();
7041           },
7042           Mask, &OpScalars, &AltScalars);
7043 
7044       propagateIRFlags(V0, OpScalars);
7045       propagateIRFlags(V1, AltScalars);
7046 
7047       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7048       if (auto *I = dyn_cast<Instruction>(V)) {
7049         V = propagateMetadata(I, E->Scalars);
7050         GatherShuffleSeq.insert(I);
7051         CSEBlocks.insert(I->getParent());
7052       }
7053       V = ShuffleBuilder.finalize(V);
7054 
7055       E->VectorizedValue = V;
7056       ++NumVectorInstructions;
7057 
7058       return V;
7059     }
7060     default:
7061     llvm_unreachable("unknown inst");
7062   }
7063   return nullptr;
7064 }
7065 
7066 Value *BoUpSLP::vectorizeTree() {
7067   ExtraValueToDebugLocsMap ExternallyUsedValues;
7068   return vectorizeTree(ExternallyUsedValues);
7069 }
7070 
7071 Value *
7072 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7073   // All blocks must be scheduled before any instructions are inserted.
7074   for (auto &BSIter : BlocksSchedules) {
7075     scheduleBlock(BSIter.second.get());
7076   }
7077 
7078   Builder.SetInsertPoint(&F->getEntryBlock().front());
7079   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7080 
7081   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7082   // vectorized root. InstCombine will then rewrite the entire expression. We
7083   // sign extend the extracted values below.
7084   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7085   if (MinBWs.count(ScalarRoot)) {
7086     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7087       // If current instr is a phi and not the last phi, insert it after the
7088       // last phi node.
7089       if (isa<PHINode>(I))
7090         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7091       else
7092         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7093     }
7094     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7095     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7096     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7097     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7098     VectorizableTree[0]->VectorizedValue = Trunc;
7099   }
7100 
7101   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7102                     << " values .\n");
7103 
7104   // Extract all of the elements with the external uses.
7105   for (const auto &ExternalUse : ExternalUses) {
7106     Value *Scalar = ExternalUse.Scalar;
7107     llvm::User *User = ExternalUse.User;
7108 
7109     // Skip users that we already RAUW. This happens when one instruction
7110     // has multiple uses of the same value.
7111     if (User && !is_contained(Scalar->users(), User))
7112       continue;
7113     TreeEntry *E = getTreeEntry(Scalar);
7114     assert(E && "Invalid scalar");
7115     assert(E->State != TreeEntry::NeedToGather &&
7116            "Extracting from a gather list");
7117 
7118     Value *Vec = E->VectorizedValue;
7119     assert(Vec && "Can't find vectorizable value");
7120 
7121     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7122     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7123       if (Scalar->getType() != Vec->getType()) {
7124         Value *Ex;
7125         // "Reuse" the existing extract to improve final codegen.
7126         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7127           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7128                                             ES->getOperand(1));
7129         } else {
7130           Ex = Builder.CreateExtractElement(Vec, Lane);
7131         }
7132         // If necessary, sign-extend or zero-extend ScalarRoot
7133         // to the larger type.
7134         if (!MinBWs.count(ScalarRoot))
7135           return Ex;
7136         if (MinBWs[ScalarRoot].second)
7137           return Builder.CreateSExt(Ex, Scalar->getType());
7138         return Builder.CreateZExt(Ex, Scalar->getType());
7139       }
7140       assert(isa<FixedVectorType>(Scalar->getType()) &&
7141              isa<InsertElementInst>(Scalar) &&
7142              "In-tree scalar of vector type is not insertelement?");
7143       return Vec;
7144     };
7145     // If User == nullptr, the Scalar is used as extra arg. Generate
7146     // ExtractElement instruction and update the record for this scalar in
7147     // ExternallyUsedValues.
7148     if (!User) {
7149       assert(ExternallyUsedValues.count(Scalar) &&
7150              "Scalar with nullptr as an external user must be registered in "
7151              "ExternallyUsedValues map");
7152       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7153         Builder.SetInsertPoint(VecI->getParent(),
7154                                std::next(VecI->getIterator()));
7155       } else {
7156         Builder.SetInsertPoint(&F->getEntryBlock().front());
7157       }
7158       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7159       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7160       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7161       auto It = ExternallyUsedValues.find(Scalar);
7162       assert(It != ExternallyUsedValues.end() &&
7163              "Externally used scalar is not found in ExternallyUsedValues");
7164       NewInstLocs.append(It->second);
7165       ExternallyUsedValues.erase(Scalar);
7166       // Required to update internally referenced instructions.
7167       Scalar->replaceAllUsesWith(NewInst);
7168       continue;
7169     }
7170 
7171     // Generate extracts for out-of-tree users.
7172     // Find the insertion point for the extractelement lane.
7173     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7174       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7175         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7176           if (PH->getIncomingValue(i) == Scalar) {
7177             Instruction *IncomingTerminator =
7178                 PH->getIncomingBlock(i)->getTerminator();
7179             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7180               Builder.SetInsertPoint(VecI->getParent(),
7181                                      std::next(VecI->getIterator()));
7182             } else {
7183               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7184             }
7185             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7186             CSEBlocks.insert(PH->getIncomingBlock(i));
7187             PH->setOperand(i, NewInst);
7188           }
7189         }
7190       } else {
7191         Builder.SetInsertPoint(cast<Instruction>(User));
7192         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7193         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7194         User->replaceUsesOfWith(Scalar, NewInst);
7195       }
7196     } else {
7197       Builder.SetInsertPoint(&F->getEntryBlock().front());
7198       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7199       CSEBlocks.insert(&F->getEntryBlock());
7200       User->replaceUsesOfWith(Scalar, NewInst);
7201     }
7202 
7203     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7204   }
7205 
7206   // For each vectorized value:
7207   for (auto &TEPtr : VectorizableTree) {
7208     TreeEntry *Entry = TEPtr.get();
7209 
7210     // No need to handle users of gathered values.
7211     if (Entry->State == TreeEntry::NeedToGather)
7212       continue;
7213 
7214     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7215 
7216     // For each lane:
7217     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7218       Value *Scalar = Entry->Scalars[Lane];
7219 
7220 #ifndef NDEBUG
7221       Type *Ty = Scalar->getType();
7222       if (!Ty->isVoidTy()) {
7223         for (User *U : Scalar->users()) {
7224           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7225 
7226           // It is legal to delete users in the ignorelist.
7227           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7228                   (isa_and_nonnull<Instruction>(U) &&
7229                    isDeleted(cast<Instruction>(U)))) &&
7230                  "Deleting out-of-tree value");
7231         }
7232       }
7233 #endif
7234       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7235       eraseInstruction(cast<Instruction>(Scalar));
7236     }
7237   }
7238 
7239   Builder.ClearInsertionPoint();
7240   InstrElementSize.clear();
7241 
7242   return VectorizableTree[0]->VectorizedValue;
7243 }
7244 
7245 void BoUpSLP::optimizeGatherSequence() {
7246   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7247                     << " gather sequences instructions.\n");
7248   // LICM InsertElementInst sequences.
7249   for (Instruction *I : GatherShuffleSeq) {
7250     if (isDeleted(I))
7251       continue;
7252 
7253     // Check if this block is inside a loop.
7254     Loop *L = LI->getLoopFor(I->getParent());
7255     if (!L)
7256       continue;
7257 
7258     // Check if it has a preheader.
7259     BasicBlock *PreHeader = L->getLoopPreheader();
7260     if (!PreHeader)
7261       continue;
7262 
7263     // If the vector or the element that we insert into it are
7264     // instructions that are defined in this basic block then we can't
7265     // hoist this instruction.
7266     if (any_of(I->operands(), [L](Value *V) {
7267           auto *OpI = dyn_cast<Instruction>(V);
7268           return OpI && L->contains(OpI);
7269         }))
7270       continue;
7271 
7272     // We can hoist this instruction. Move it to the pre-header.
7273     I->moveBefore(PreHeader->getTerminator());
7274   }
7275 
7276   // Make a list of all reachable blocks in our CSE queue.
7277   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7278   CSEWorkList.reserve(CSEBlocks.size());
7279   for (BasicBlock *BB : CSEBlocks)
7280     if (DomTreeNode *N = DT->getNode(BB)) {
7281       assert(DT->isReachableFromEntry(N));
7282       CSEWorkList.push_back(N);
7283     }
7284 
7285   // Sort blocks by domination. This ensures we visit a block after all blocks
7286   // dominating it are visited.
7287   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7288     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7289            "Different nodes should have different DFS numbers");
7290     return A->getDFSNumIn() < B->getDFSNumIn();
7291   });
7292 
7293   // Less defined shuffles can be replaced by the more defined copies.
7294   // Between two shuffles one is less defined if it has the same vector operands
7295   // and its mask indeces are the same as in the first one or undefs. E.g.
7296   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7297   // poison, <0, 0, 0, 0>.
7298   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7299                                            SmallVectorImpl<int> &NewMask) {
7300     if (I1->getType() != I2->getType())
7301       return false;
7302     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7303     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7304     if (!SI1 || !SI2)
7305       return I1->isIdenticalTo(I2);
7306     if (SI1->isIdenticalTo(SI2))
7307       return true;
7308     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7309       if (SI1->getOperand(I) != SI2->getOperand(I))
7310         return false;
7311     // Check if the second instruction is more defined than the first one.
7312     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7313     ArrayRef<int> SM1 = SI1->getShuffleMask();
7314     // Count trailing undefs in the mask to check the final number of used
7315     // registers.
7316     unsigned LastUndefsCnt = 0;
7317     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7318       if (SM1[I] == UndefMaskElem)
7319         ++LastUndefsCnt;
7320       else
7321         LastUndefsCnt = 0;
7322       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7323           NewMask[I] != SM1[I])
7324         return false;
7325       if (NewMask[I] == UndefMaskElem)
7326         NewMask[I] = SM1[I];
7327     }
7328     // Check if the last undefs actually change the final number of used vector
7329     // registers.
7330     return SM1.size() - LastUndefsCnt > 1 &&
7331            TTI->getNumberOfParts(SI1->getType()) ==
7332                TTI->getNumberOfParts(
7333                    FixedVectorType::get(SI1->getType()->getElementType(),
7334                                         SM1.size() - LastUndefsCnt));
7335   };
7336   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7337   // instructions. TODO: We can further optimize this scan if we split the
7338   // instructions into different buckets based on the insert lane.
7339   SmallVector<Instruction *, 16> Visited;
7340   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7341     assert(*I &&
7342            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7343            "Worklist not sorted properly!");
7344     BasicBlock *BB = (*I)->getBlock();
7345     // For all instructions in blocks containing gather sequences:
7346     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7347       if (isDeleted(&In))
7348         continue;
7349       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7350           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7351         continue;
7352 
7353       // Check if we can replace this instruction with any of the
7354       // visited instructions.
7355       bool Replaced = false;
7356       for (Instruction *&V : Visited) {
7357         SmallVector<int> NewMask;
7358         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7359             DT->dominates(V->getParent(), In.getParent())) {
7360           In.replaceAllUsesWith(V);
7361           eraseInstruction(&In);
7362           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7363             if (!NewMask.empty())
7364               SI->setShuffleMask(NewMask);
7365           Replaced = true;
7366           break;
7367         }
7368         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7369             GatherShuffleSeq.contains(V) &&
7370             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7371             DT->dominates(In.getParent(), V->getParent())) {
7372           In.moveAfter(V);
7373           V->replaceAllUsesWith(&In);
7374           eraseInstruction(V);
7375           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7376             if (!NewMask.empty())
7377               SI->setShuffleMask(NewMask);
7378           V = &In;
7379           Replaced = true;
7380           break;
7381         }
7382       }
7383       if (!Replaced) {
7384         assert(!is_contained(Visited, &In));
7385         Visited.push_back(&In);
7386       }
7387     }
7388   }
7389   CSEBlocks.clear();
7390   GatherShuffleSeq.clear();
7391 }
7392 
7393 BoUpSLP::ScheduleData *
7394 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7395   ScheduleData *Bundle = nullptr;
7396   ScheduleData *PrevInBundle = nullptr;
7397   for (Value *V : VL) {
7398     ScheduleData *BundleMember = getScheduleData(V);
7399     assert(BundleMember &&
7400            "no ScheduleData for bundle member "
7401            "(maybe not in same basic block)");
7402     assert(BundleMember->isSchedulingEntity() &&
7403            "bundle member already part of other bundle");
7404     if (PrevInBundle) {
7405       PrevInBundle->NextInBundle = BundleMember;
7406     } else {
7407       Bundle = BundleMember;
7408     }
7409     BundleMember->UnscheduledDepsInBundle = 0;
7410     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
7411 
7412     // Group the instructions to a bundle.
7413     BundleMember->FirstInBundle = Bundle;
7414     PrevInBundle = BundleMember;
7415   }
7416   assert(Bundle && "Failed to find schedule bundle");
7417   return Bundle;
7418 }
7419 
7420 // Groups the instructions to a bundle (which is then a single scheduling entity)
7421 // and schedules instructions until the bundle gets ready.
7422 Optional<BoUpSLP::ScheduleData *>
7423 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7424                                             const InstructionsState &S) {
7425   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7426   // instructions.
7427   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7428     return nullptr;
7429 
7430   // Initialize the instruction bundle.
7431   Instruction *OldScheduleEnd = ScheduleEnd;
7432   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7433 
7434   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7435                                                          ScheduleData *Bundle) {
7436     // The scheduling region got new instructions at the lower end (or it is a
7437     // new region for the first bundle). This makes it necessary to
7438     // recalculate all dependencies.
7439     // It is seldom that this needs to be done a second time after adding the
7440     // initial bundle to the region.
7441     if (ScheduleEnd != OldScheduleEnd) {
7442       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7443         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7444       ReSchedule = true;
7445     }
7446     if (ReSchedule) {
7447       resetSchedule();
7448       initialFillReadyList(ReadyInsts);
7449     }
7450     if (Bundle) {
7451       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7452                         << " in block " << BB->getName() << "\n");
7453       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7454     }
7455 
7456     // Now try to schedule the new bundle or (if no bundle) just calculate
7457     // dependencies. As soon as the bundle is "ready" it means that there are no
7458     // cyclic dependencies and we can schedule it. Note that's important that we
7459     // don't "schedule" the bundle yet (see cancelScheduling).
7460     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7461            !ReadyInsts.empty()) {
7462       ScheduleData *Picked = ReadyInsts.pop_back_val();
7463       if (Picked->isSchedulingEntity() && Picked->isReady())
7464         schedule(Picked, ReadyInsts);
7465     }
7466   };
7467 
7468   // Make sure that the scheduling region contains all
7469   // instructions of the bundle.
7470   for (Value *V : VL) {
7471     if (!extendSchedulingRegion(V, S)) {
7472       // If the scheduling region got new instructions at the lower end (or it
7473       // is a new region for the first bundle). This makes it necessary to
7474       // recalculate all dependencies.
7475       // Otherwise the compiler may crash trying to incorrectly calculate
7476       // dependencies and emit instruction in the wrong order at the actual
7477       // scheduling.
7478       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7479       return None;
7480     }
7481   }
7482 
7483   bool ReSchedule = false;
7484   for (Value *V : VL) {
7485     ScheduleData *BundleMember = getScheduleData(V);
7486     assert(BundleMember &&
7487            "no ScheduleData for bundle member (maybe not in same basic block)");
7488     if (!BundleMember->IsScheduled)
7489       continue;
7490     // A bundle member was scheduled as single instruction before and now
7491     // needs to be scheduled as part of the bundle. We just get rid of the
7492     // existing schedule.
7493     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7494                       << " was already scheduled\n");
7495     ReSchedule = true;
7496   }
7497 
7498   auto *Bundle = buildBundle(VL);
7499   TryScheduleBundleImpl(ReSchedule, Bundle);
7500   if (!Bundle->isReady()) {
7501     cancelScheduling(VL, S.OpValue);
7502     return None;
7503   }
7504   return Bundle;
7505 }
7506 
7507 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7508                                                 Value *OpValue) {
7509   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7510     return;
7511 
7512   ScheduleData *Bundle = getScheduleData(OpValue);
7513   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7514   assert(!Bundle->IsScheduled &&
7515          "Can't cancel bundle which is already scheduled");
7516   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7517          "tried to unbundle something which is not a bundle");
7518 
7519   // Un-bundle: make single instructions out of the bundle.
7520   ScheduleData *BundleMember = Bundle;
7521   while (BundleMember) {
7522     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7523     BundleMember->FirstInBundle = BundleMember;
7524     ScheduleData *Next = BundleMember->NextInBundle;
7525     BundleMember->NextInBundle = nullptr;
7526     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
7527     if (BundleMember->UnscheduledDepsInBundle == 0) {
7528       ReadyInsts.insert(BundleMember);
7529     }
7530     BundleMember = Next;
7531   }
7532 }
7533 
7534 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7535   // Allocate a new ScheduleData for the instruction.
7536   if (ChunkPos >= ChunkSize) {
7537     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7538     ChunkPos = 0;
7539   }
7540   return &(ScheduleDataChunks.back()[ChunkPos++]);
7541 }
7542 
7543 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7544                                                       const InstructionsState &S) {
7545   if (getScheduleData(V, isOneOf(S, V)))
7546     return true;
7547   Instruction *I = dyn_cast<Instruction>(V);
7548   assert(I && "bundle member must be an instruction");
7549   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7550          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7551          "be scheduled");
7552   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
7553     ScheduleData *ISD = getScheduleData(I);
7554     if (!ISD)
7555       return false;
7556     assert(isInSchedulingRegion(ISD) &&
7557            "ScheduleData not in scheduling region");
7558     ScheduleData *SD = allocateScheduleDataChunks();
7559     SD->Inst = I;
7560     SD->init(SchedulingRegionID, S.OpValue);
7561     ExtraScheduleDataMap[I][S.OpValue] = SD;
7562     return true;
7563   };
7564   if (CheckSheduleForI(I))
7565     return true;
7566   if (!ScheduleStart) {
7567     // It's the first instruction in the new region.
7568     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7569     ScheduleStart = I;
7570     ScheduleEnd = I->getNextNode();
7571     if (isOneOf(S, I) != I)
7572       CheckSheduleForI(I);
7573     assert(ScheduleEnd && "tried to vectorize a terminator?");
7574     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7575     return true;
7576   }
7577   // Search up and down at the same time, because we don't know if the new
7578   // instruction is above or below the existing scheduling region.
7579   BasicBlock::reverse_iterator UpIter =
7580       ++ScheduleStart->getIterator().getReverse();
7581   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7582   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7583   BasicBlock::iterator LowerEnd = BB->end();
7584   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7585          &*DownIter != I) {
7586     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7587       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7588       return false;
7589     }
7590 
7591     ++UpIter;
7592     ++DownIter;
7593   }
7594   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7595     assert(I->getParent() == ScheduleStart->getParent() &&
7596            "Instruction is in wrong basic block.");
7597     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7598     ScheduleStart = I;
7599     if (isOneOf(S, I) != I)
7600       CheckSheduleForI(I);
7601     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7602                       << "\n");
7603     return true;
7604   }
7605   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7606          "Expected to reach top of the basic block or instruction down the "
7607          "lower end.");
7608   assert(I->getParent() == ScheduleEnd->getParent() &&
7609          "Instruction is in wrong basic block.");
7610   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7611                    nullptr);
7612   ScheduleEnd = I->getNextNode();
7613   if (isOneOf(S, I) != I)
7614     CheckSheduleForI(I);
7615   assert(ScheduleEnd && "tried to vectorize a terminator?");
7616   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7617   return true;
7618 }
7619 
7620 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7621                                                 Instruction *ToI,
7622                                                 ScheduleData *PrevLoadStore,
7623                                                 ScheduleData *NextLoadStore) {
7624   ScheduleData *CurrentLoadStore = PrevLoadStore;
7625   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7626     ScheduleData *SD = ScheduleDataMap[I];
7627     if (!SD) {
7628       SD = allocateScheduleDataChunks();
7629       ScheduleDataMap[I] = SD;
7630       SD->Inst = I;
7631     }
7632     assert(!isInSchedulingRegion(SD) &&
7633            "new ScheduleData already in scheduling region");
7634     SD->init(SchedulingRegionID, I);
7635 
7636     if (I->mayReadOrWriteMemory() &&
7637         (!isa<IntrinsicInst>(I) ||
7638          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7639           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7640               Intrinsic::pseudoprobe))) {
7641       // Update the linked list of memory accessing instructions.
7642       if (CurrentLoadStore) {
7643         CurrentLoadStore->NextLoadStore = SD;
7644       } else {
7645         FirstLoadStoreInRegion = SD;
7646       }
7647       CurrentLoadStore = SD;
7648     }
7649   }
7650   if (NextLoadStore) {
7651     if (CurrentLoadStore)
7652       CurrentLoadStore->NextLoadStore = NextLoadStore;
7653   } else {
7654     LastLoadStoreInRegion = CurrentLoadStore;
7655   }
7656 }
7657 
7658 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7659                                                      bool InsertInReadyList,
7660                                                      BoUpSLP *SLP) {
7661   assert(SD->isSchedulingEntity());
7662 
7663   SmallVector<ScheduleData *, 10> WorkList;
7664   WorkList.push_back(SD);
7665 
7666   while (!WorkList.empty()) {
7667     ScheduleData *SD = WorkList.pop_back_val();
7668     for (ScheduleData *BundleMember = SD; BundleMember;
7669          BundleMember = BundleMember->NextInBundle) {
7670       assert(isInSchedulingRegion(BundleMember));
7671       if (BundleMember->hasValidDependencies())
7672         continue;
7673 
7674       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7675                  << "\n");
7676       BundleMember->Dependencies = 0;
7677       BundleMember->resetUnscheduledDeps();
7678 
7679       // Handle def-use chain dependencies.
7680       if (BundleMember->OpValue != BundleMember->Inst) {
7681         ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
7682         if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7683           BundleMember->Dependencies++;
7684           ScheduleData *DestBundle = UseSD->FirstInBundle;
7685           if (!DestBundle->IsScheduled)
7686             BundleMember->incrementUnscheduledDeps(1);
7687           if (!DestBundle->hasValidDependencies())
7688             WorkList.push_back(DestBundle);
7689         }
7690       } else {
7691         for (User *U : BundleMember->Inst->users()) {
7692           assert(isa<Instruction>(U) &&
7693                  "user of instruction must be instruction");
7694           ScheduleData *UseSD = getScheduleData(U);
7695           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7696             BundleMember->Dependencies++;
7697             ScheduleData *DestBundle = UseSD->FirstInBundle;
7698             if (!DestBundle->IsScheduled)
7699               BundleMember->incrementUnscheduledDeps(1);
7700             if (!DestBundle->hasValidDependencies())
7701               WorkList.push_back(DestBundle);
7702           }
7703         }
7704       }
7705 
7706       // Handle the memory dependencies (if any).
7707       ScheduleData *DepDest = BundleMember->NextLoadStore;
7708       if (!DepDest)
7709         continue;
7710       Instruction *SrcInst = BundleMember->Inst;
7711       assert(SrcInst->mayReadOrWriteMemory() &&
7712              "NextLoadStore list for non memory effecting bundle?");
7713       MemoryLocation SrcLoc = getLocation(SrcInst);
7714       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7715       unsigned numAliased = 0;
7716       unsigned DistToSrc = 1;
7717 
7718       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7719         assert(isInSchedulingRegion(DepDest));
7720 
7721         // We have two limits to reduce the complexity:
7722         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7723         //    SLP->isAliased (which is the expensive part in this loop).
7724         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7725         //    the whole loop (even if the loop is fast, it's quadratic).
7726         //    It's important for the loop break condition (see below) to
7727         //    check this limit even between two read-only instructions.
7728         if (DistToSrc >= MaxMemDepDistance ||
7729             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7730              (numAliased >= AliasedCheckLimit ||
7731               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7732 
7733           // We increment the counter only if the locations are aliased
7734           // (instead of counting all alias checks). This gives a better
7735           // balance between reduced runtime and accurate dependencies.
7736           numAliased++;
7737 
7738           DepDest->MemoryDependencies.push_back(BundleMember);
7739           BundleMember->Dependencies++;
7740           ScheduleData *DestBundle = DepDest->FirstInBundle;
7741           if (!DestBundle->IsScheduled) {
7742             BundleMember->incrementUnscheduledDeps(1);
7743           }
7744           if (!DestBundle->hasValidDependencies()) {
7745             WorkList.push_back(DestBundle);
7746           }
7747         }
7748 
7749         // Example, explaining the loop break condition: Let's assume our
7750         // starting instruction is i0 and MaxMemDepDistance = 3.
7751         //
7752         //                      +--------v--v--v
7753         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7754         //             +--------^--^--^
7755         //
7756         // MaxMemDepDistance let us stop alias-checking at i3 and we add
7757         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7758         // Previously we already added dependencies from i3 to i6,i7,i8
7759         // (because of MaxMemDepDistance). As we added a dependency from
7760         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7761         // and we can abort this loop at i6.
7762         if (DistToSrc >= 2 * MaxMemDepDistance)
7763           break;
7764         DistToSrc++;
7765       }
7766     }
7767     if (InsertInReadyList && SD->isReady()) {
7768       ReadyInsts.push_back(SD);
7769       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7770                         << "\n");
7771     }
7772   }
7773 }
7774 
7775 void BoUpSLP::BlockScheduling::resetSchedule() {
7776   assert(ScheduleStart &&
7777          "tried to reset schedule on block which has not been scheduled");
7778   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7779     doForAllOpcodes(I, [&](ScheduleData *SD) {
7780       assert(isInSchedulingRegion(SD) &&
7781              "ScheduleData not in scheduling region");
7782       SD->IsScheduled = false;
7783       SD->resetUnscheduledDeps();
7784     });
7785   }
7786   ReadyInsts.clear();
7787 }
7788 
7789 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7790   if (!BS->ScheduleStart)
7791     return;
7792 
7793   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7794 
7795   BS->resetSchedule();
7796 
7797   // For the real scheduling we use a more sophisticated ready-list: it is
7798   // sorted by the original instruction location. This lets the final schedule
7799   // be as  close as possible to the original instruction order.
7800   struct ScheduleDataCompare {
7801     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7802       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7803     }
7804   };
7805   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7806 
7807   // Ensure that all dependency data is updated and fill the ready-list with
7808   // initial instructions.
7809   int Idx = 0;
7810   int NumToSchedule = 0;
7811   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7812        I = I->getNextNode()) {
7813     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7814       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7815               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7816              "scheduler and vectorizer bundle mismatch");
7817       SD->FirstInBundle->SchedulingPriority = Idx++;
7818       if (SD->isSchedulingEntity()) {
7819         BS->calculateDependencies(SD, false, this);
7820         NumToSchedule++;
7821       }
7822     });
7823   }
7824   BS->initialFillReadyList(ReadyInsts);
7825 
7826   Instruction *LastScheduledInst = BS->ScheduleEnd;
7827 
7828   // Do the "real" scheduling.
7829   while (!ReadyInsts.empty()) {
7830     ScheduleData *picked = *ReadyInsts.begin();
7831     ReadyInsts.erase(ReadyInsts.begin());
7832 
7833     // Move the scheduled instruction(s) to their dedicated places, if not
7834     // there yet.
7835     for (ScheduleData *BundleMember = picked; BundleMember;
7836          BundleMember = BundleMember->NextInBundle) {
7837       Instruction *pickedInst = BundleMember->Inst;
7838       if (pickedInst->getNextNode() != LastScheduledInst)
7839         pickedInst->moveBefore(LastScheduledInst);
7840       LastScheduledInst = pickedInst;
7841     }
7842 
7843     BS->schedule(picked, ReadyInsts);
7844     NumToSchedule--;
7845   }
7846   assert(NumToSchedule == 0 && "could not schedule all instructions");
7847 
7848   // Avoid duplicate scheduling of the block.
7849   BS->ScheduleStart = nullptr;
7850 }
7851 
7852 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7853   // If V is a store, just return the width of the stored value (or value
7854   // truncated just before storing) without traversing the expression tree.
7855   // This is the common case.
7856   if (auto *Store = dyn_cast<StoreInst>(V)) {
7857     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7858       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7859     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7860   }
7861 
7862   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7863     return getVectorElementSize(IEI->getOperand(1));
7864 
7865   auto E = InstrElementSize.find(V);
7866   if (E != InstrElementSize.end())
7867     return E->second;
7868 
7869   // If V is not a store, we can traverse the expression tree to find loads
7870   // that feed it. The type of the loaded value may indicate a more suitable
7871   // width than V's type. We want to base the vector element size on the width
7872   // of memory operations where possible.
7873   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7874   SmallPtrSet<Instruction *, 16> Visited;
7875   if (auto *I = dyn_cast<Instruction>(V)) {
7876     Worklist.emplace_back(I, I->getParent());
7877     Visited.insert(I);
7878   }
7879 
7880   // Traverse the expression tree in bottom-up order looking for loads. If we
7881   // encounter an instruction we don't yet handle, we give up.
7882   auto Width = 0u;
7883   while (!Worklist.empty()) {
7884     Instruction *I;
7885     BasicBlock *Parent;
7886     std::tie(I, Parent) = Worklist.pop_back_val();
7887 
7888     // We should only be looking at scalar instructions here. If the current
7889     // instruction has a vector type, skip.
7890     auto *Ty = I->getType();
7891     if (isa<VectorType>(Ty))
7892       continue;
7893 
7894     // If the current instruction is a load, update MaxWidth to reflect the
7895     // width of the loaded value.
7896     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
7897         isa<ExtractValueInst>(I))
7898       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
7899 
7900     // Otherwise, we need to visit the operands of the instruction. We only
7901     // handle the interesting cases from buildTree here. If an operand is an
7902     // instruction we haven't yet visited and from the same basic block as the
7903     // user or the use is a PHI node, we add it to the worklist.
7904     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7905              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
7906              isa<UnaryOperator>(I)) {
7907       for (Use &U : I->operands())
7908         if (auto *J = dyn_cast<Instruction>(U.get()))
7909           if (Visited.insert(J).second &&
7910               (isa<PHINode>(I) || J->getParent() == Parent))
7911             Worklist.emplace_back(J, J->getParent());
7912     } else {
7913       break;
7914     }
7915   }
7916 
7917   // If we didn't encounter a memory access in the expression tree, or if we
7918   // gave up for some reason, just return the width of V. Otherwise, return the
7919   // maximum width we found.
7920   if (!Width) {
7921     if (auto *CI = dyn_cast<CmpInst>(V))
7922       V = CI->getOperand(0);
7923     Width = DL->getTypeSizeInBits(V->getType());
7924   }
7925 
7926   for (Instruction *I : Visited)
7927     InstrElementSize[I] = Width;
7928 
7929   return Width;
7930 }
7931 
7932 // Determine if a value V in a vectorizable expression Expr can be demoted to a
7933 // smaller type with a truncation. We collect the values that will be demoted
7934 // in ToDemote and additional roots that require investigating in Roots.
7935 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
7936                                   SmallVectorImpl<Value *> &ToDemote,
7937                                   SmallVectorImpl<Value *> &Roots) {
7938   // We can always demote constants.
7939   if (isa<Constant>(V)) {
7940     ToDemote.push_back(V);
7941     return true;
7942   }
7943 
7944   // If the value is not an instruction in the expression with only one use, it
7945   // cannot be demoted.
7946   auto *I = dyn_cast<Instruction>(V);
7947   if (!I || !I->hasOneUse() || !Expr.count(I))
7948     return false;
7949 
7950   switch (I->getOpcode()) {
7951 
7952   // We can always demote truncations and extensions. Since truncations can
7953   // seed additional demotion, we save the truncated value.
7954   case Instruction::Trunc:
7955     Roots.push_back(I->getOperand(0));
7956     break;
7957   case Instruction::ZExt:
7958   case Instruction::SExt:
7959     if (isa<ExtractElementInst>(I->getOperand(0)) ||
7960         isa<InsertElementInst>(I->getOperand(0)))
7961       return false;
7962     break;
7963 
7964   // We can demote certain binary operations if we can demote both of their
7965   // operands.
7966   case Instruction::Add:
7967   case Instruction::Sub:
7968   case Instruction::Mul:
7969   case Instruction::And:
7970   case Instruction::Or:
7971   case Instruction::Xor:
7972     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
7973         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
7974       return false;
7975     break;
7976 
7977   // We can demote selects if we can demote their true and false values.
7978   case Instruction::Select: {
7979     SelectInst *SI = cast<SelectInst>(I);
7980     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
7981         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
7982       return false;
7983     break;
7984   }
7985 
7986   // We can demote phis if we can demote all their incoming operands. Note that
7987   // we don't need to worry about cycles since we ensure single use above.
7988   case Instruction::PHI: {
7989     PHINode *PN = cast<PHINode>(I);
7990     for (Value *IncValue : PN->incoming_values())
7991       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
7992         return false;
7993     break;
7994   }
7995 
7996   // Otherwise, conservatively give up.
7997   default:
7998     return false;
7999   }
8000 
8001   // Record the value that we can demote.
8002   ToDemote.push_back(V);
8003   return true;
8004 }
8005 
8006 void BoUpSLP::computeMinimumValueSizes() {
8007   // If there are no external uses, the expression tree must be rooted by a
8008   // store. We can't demote in-memory values, so there is nothing to do here.
8009   if (ExternalUses.empty())
8010     return;
8011 
8012   // We only attempt to truncate integer expressions.
8013   auto &TreeRoot = VectorizableTree[0]->Scalars;
8014   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8015   if (!TreeRootIT)
8016     return;
8017 
8018   // If the expression is not rooted by a store, these roots should have
8019   // external uses. We will rely on InstCombine to rewrite the expression in
8020   // the narrower type. However, InstCombine only rewrites single-use values.
8021   // This means that if a tree entry other than a root is used externally, it
8022   // must have multiple uses and InstCombine will not rewrite it. The code
8023   // below ensures that only the roots are used externally.
8024   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8025   for (auto &EU : ExternalUses)
8026     if (!Expr.erase(EU.Scalar))
8027       return;
8028   if (!Expr.empty())
8029     return;
8030 
8031   // Collect the scalar values of the vectorizable expression. We will use this
8032   // context to determine which values can be demoted. If we see a truncation,
8033   // we mark it as seeding another demotion.
8034   for (auto &EntryPtr : VectorizableTree)
8035     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8036 
8037   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8038   // have a single external user that is not in the vectorizable tree.
8039   for (auto *Root : TreeRoot)
8040     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8041       return;
8042 
8043   // Conservatively determine if we can actually truncate the roots of the
8044   // expression. Collect the values that can be demoted in ToDemote and
8045   // additional roots that require investigating in Roots.
8046   SmallVector<Value *, 32> ToDemote;
8047   SmallVector<Value *, 4> Roots;
8048   for (auto *Root : TreeRoot)
8049     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8050       return;
8051 
8052   // The maximum bit width required to represent all the values that can be
8053   // demoted without loss of precision. It would be safe to truncate the roots
8054   // of the expression to this width.
8055   auto MaxBitWidth = 8u;
8056 
8057   // We first check if all the bits of the roots are demanded. If they're not,
8058   // we can truncate the roots to this narrower type.
8059   for (auto *Root : TreeRoot) {
8060     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8061     MaxBitWidth = std::max<unsigned>(
8062         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8063   }
8064 
8065   // True if the roots can be zero-extended back to their original type, rather
8066   // than sign-extended. We know that if the leading bits are not demanded, we
8067   // can safely zero-extend. So we initialize IsKnownPositive to True.
8068   bool IsKnownPositive = true;
8069 
8070   // If all the bits of the roots are demanded, we can try a little harder to
8071   // compute a narrower type. This can happen, for example, if the roots are
8072   // getelementptr indices. InstCombine promotes these indices to the pointer
8073   // width. Thus, all their bits are technically demanded even though the
8074   // address computation might be vectorized in a smaller type.
8075   //
8076   // We start by looking at each entry that can be demoted. We compute the
8077   // maximum bit width required to store the scalar by using ValueTracking to
8078   // compute the number of high-order bits we can truncate.
8079   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8080       llvm::all_of(TreeRoot, [](Value *R) {
8081         assert(R->hasOneUse() && "Root should have only one use!");
8082         return isa<GetElementPtrInst>(R->user_back());
8083       })) {
8084     MaxBitWidth = 8u;
8085 
8086     // Determine if the sign bit of all the roots is known to be zero. If not,
8087     // IsKnownPositive is set to False.
8088     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8089       KnownBits Known = computeKnownBits(R, *DL);
8090       return Known.isNonNegative();
8091     });
8092 
8093     // Determine the maximum number of bits required to store the scalar
8094     // values.
8095     for (auto *Scalar : ToDemote) {
8096       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8097       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8098       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8099     }
8100 
8101     // If we can't prove that the sign bit is zero, we must add one to the
8102     // maximum bit width to account for the unknown sign bit. This preserves
8103     // the existing sign bit so we can safely sign-extend the root back to the
8104     // original type. Otherwise, if we know the sign bit is zero, we will
8105     // zero-extend the root instead.
8106     //
8107     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8108     //        one to the maximum bit width will yield a larger-than-necessary
8109     //        type. In general, we need to add an extra bit only if we can't
8110     //        prove that the upper bit of the original type is equal to the
8111     //        upper bit of the proposed smaller type. If these two bits are the
8112     //        same (either zero or one) we know that sign-extending from the
8113     //        smaller type will result in the same value. Here, since we can't
8114     //        yet prove this, we are just making the proposed smaller type
8115     //        larger to ensure correctness.
8116     if (!IsKnownPositive)
8117       ++MaxBitWidth;
8118   }
8119 
8120   // Round MaxBitWidth up to the next power-of-two.
8121   if (!isPowerOf2_64(MaxBitWidth))
8122     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8123 
8124   // If the maximum bit width we compute is less than the with of the roots'
8125   // type, we can proceed with the narrowing. Otherwise, do nothing.
8126   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8127     return;
8128 
8129   // If we can truncate the root, we must collect additional values that might
8130   // be demoted as a result. That is, those seeded by truncations we will
8131   // modify.
8132   while (!Roots.empty())
8133     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8134 
8135   // Finally, map the values we can demote to the maximum bit with we computed.
8136   for (auto *Scalar : ToDemote)
8137     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8138 }
8139 
8140 namespace {
8141 
8142 /// The SLPVectorizer Pass.
8143 struct SLPVectorizer : public FunctionPass {
8144   SLPVectorizerPass Impl;
8145 
8146   /// Pass identification, replacement for typeid
8147   static char ID;
8148 
8149   explicit SLPVectorizer() : FunctionPass(ID) {
8150     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8151   }
8152 
8153   bool doInitialization(Module &M) override { return false; }
8154 
8155   bool runOnFunction(Function &F) override {
8156     if (skipFunction(F))
8157       return false;
8158 
8159     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8160     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8161     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8162     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8163     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8164     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8165     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8166     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8167     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8168     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8169 
8170     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8171   }
8172 
8173   void getAnalysisUsage(AnalysisUsage &AU) const override {
8174     FunctionPass::getAnalysisUsage(AU);
8175     AU.addRequired<AssumptionCacheTracker>();
8176     AU.addRequired<ScalarEvolutionWrapperPass>();
8177     AU.addRequired<AAResultsWrapperPass>();
8178     AU.addRequired<TargetTransformInfoWrapperPass>();
8179     AU.addRequired<LoopInfoWrapperPass>();
8180     AU.addRequired<DominatorTreeWrapperPass>();
8181     AU.addRequired<DemandedBitsWrapperPass>();
8182     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8183     AU.addRequired<InjectTLIMappingsLegacy>();
8184     AU.addPreserved<LoopInfoWrapperPass>();
8185     AU.addPreserved<DominatorTreeWrapperPass>();
8186     AU.addPreserved<AAResultsWrapperPass>();
8187     AU.addPreserved<GlobalsAAWrapperPass>();
8188     AU.setPreservesCFG();
8189   }
8190 };
8191 
8192 } // end anonymous namespace
8193 
8194 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8195   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8196   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8197   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8198   auto *AA = &AM.getResult<AAManager>(F);
8199   auto *LI = &AM.getResult<LoopAnalysis>(F);
8200   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8201   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8202   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8203   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8204 
8205   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8206   if (!Changed)
8207     return PreservedAnalyses::all();
8208 
8209   PreservedAnalyses PA;
8210   PA.preserveSet<CFGAnalyses>();
8211   return PA;
8212 }
8213 
8214 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8215                                 TargetTransformInfo *TTI_,
8216                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8217                                 LoopInfo *LI_, DominatorTree *DT_,
8218                                 AssumptionCache *AC_, DemandedBits *DB_,
8219                                 OptimizationRemarkEmitter *ORE_) {
8220   if (!RunSLPVectorization)
8221     return false;
8222   SE = SE_;
8223   TTI = TTI_;
8224   TLI = TLI_;
8225   AA = AA_;
8226   LI = LI_;
8227   DT = DT_;
8228   AC = AC_;
8229   DB = DB_;
8230   DL = &F.getParent()->getDataLayout();
8231 
8232   Stores.clear();
8233   GEPs.clear();
8234   bool Changed = false;
8235 
8236   // If the target claims to have no vector registers don't attempt
8237   // vectorization.
8238   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8239     LLVM_DEBUG(
8240         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8241     return false;
8242   }
8243 
8244   // Don't vectorize when the attribute NoImplicitFloat is used.
8245   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8246     return false;
8247 
8248   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8249 
8250   // Use the bottom up slp vectorizer to construct chains that start with
8251   // store instructions.
8252   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8253 
8254   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8255   // delete instructions.
8256 
8257   // Update DFS numbers now so that we can use them for ordering.
8258   DT->updateDFSNumbers();
8259 
8260   // Scan the blocks in the function in post order.
8261   for (auto BB : post_order(&F.getEntryBlock())) {
8262     collectSeedInstructions(BB);
8263 
8264     // Vectorize trees that end at stores.
8265     if (!Stores.empty()) {
8266       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8267                         << " underlying objects.\n");
8268       Changed |= vectorizeStoreChains(R);
8269     }
8270 
8271     // Vectorize trees that end at reductions.
8272     Changed |= vectorizeChainsInBlock(BB, R);
8273 
8274     // Vectorize the index computations of getelementptr instructions. This
8275     // is primarily intended to catch gather-like idioms ending at
8276     // non-consecutive loads.
8277     if (!GEPs.empty()) {
8278       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8279                         << " underlying objects.\n");
8280       Changed |= vectorizeGEPIndices(BB, R);
8281     }
8282   }
8283 
8284   if (Changed) {
8285     R.optimizeGatherSequence();
8286     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8287   }
8288   return Changed;
8289 }
8290 
8291 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8292                                             unsigned Idx) {
8293   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8294                     << "\n");
8295   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8296   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8297   unsigned VF = Chain.size();
8298 
8299   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8300     return false;
8301 
8302   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8303                     << "\n");
8304 
8305   R.buildTree(Chain);
8306   if (R.isTreeTinyAndNotFullyVectorizable())
8307     return false;
8308   if (R.isLoadCombineCandidate())
8309     return false;
8310   R.reorderTopToBottom();
8311   R.reorderBottomToTop();
8312   R.buildExternalUses();
8313 
8314   R.computeMinimumValueSizes();
8315 
8316   InstructionCost Cost = R.getTreeCost();
8317 
8318   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8319   if (Cost < -SLPCostThreshold) {
8320     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8321 
8322     using namespace ore;
8323 
8324     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8325                                         cast<StoreInst>(Chain[0]))
8326                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8327                      << " and with tree size "
8328                      << NV("TreeSize", R.getTreeSize()));
8329 
8330     R.vectorizeTree();
8331     return true;
8332   }
8333 
8334   return false;
8335 }
8336 
8337 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8338                                         BoUpSLP &R) {
8339   // We may run into multiple chains that merge into a single chain. We mark the
8340   // stores that we vectorized so that we don't visit the same store twice.
8341   BoUpSLP::ValueSet VectorizedStores;
8342   bool Changed = false;
8343 
8344   int E = Stores.size();
8345   SmallBitVector Tails(E, false);
8346   int MaxIter = MaxStoreLookup.getValue();
8347   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8348       E, std::make_pair(E, INT_MAX));
8349   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8350   int IterCnt;
8351   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8352                                   &CheckedPairs,
8353                                   &ConsecutiveChain](int K, int Idx) {
8354     if (IterCnt >= MaxIter)
8355       return true;
8356     if (CheckedPairs[Idx].test(K))
8357       return ConsecutiveChain[K].second == 1 &&
8358              ConsecutiveChain[K].first == Idx;
8359     ++IterCnt;
8360     CheckedPairs[Idx].set(K);
8361     CheckedPairs[K].set(Idx);
8362     Optional<int> Diff = getPointersDiff(
8363         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8364         Stores[Idx]->getValueOperand()->getType(),
8365         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8366     if (!Diff || *Diff == 0)
8367       return false;
8368     int Val = *Diff;
8369     if (Val < 0) {
8370       if (ConsecutiveChain[Idx].second > -Val) {
8371         Tails.set(K);
8372         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8373       }
8374       return false;
8375     }
8376     if (ConsecutiveChain[K].second <= Val)
8377       return false;
8378 
8379     Tails.set(Idx);
8380     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8381     return Val == 1;
8382   };
8383   // Do a quadratic search on all of the given stores in reverse order and find
8384   // all of the pairs of stores that follow each other.
8385   for (int Idx = E - 1; Idx >= 0; --Idx) {
8386     // If a store has multiple consecutive store candidates, search according
8387     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8388     // This is because usually pairing with immediate succeeding or preceding
8389     // candidate create the best chance to find slp vectorization opportunity.
8390     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8391     IterCnt = 0;
8392     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8393       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8394           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8395         break;
8396   }
8397 
8398   // Tracks if we tried to vectorize stores starting from the given tail
8399   // already.
8400   SmallBitVector TriedTails(E, false);
8401   // For stores that start but don't end a link in the chain:
8402   for (int Cnt = E; Cnt > 0; --Cnt) {
8403     int I = Cnt - 1;
8404     if (ConsecutiveChain[I].first == E || Tails.test(I))
8405       continue;
8406     // We found a store instr that starts a chain. Now follow the chain and try
8407     // to vectorize it.
8408     BoUpSLP::ValueList Operands;
8409     // Collect the chain into a list.
8410     while (I != E && !VectorizedStores.count(Stores[I])) {
8411       Operands.push_back(Stores[I]);
8412       Tails.set(I);
8413       if (ConsecutiveChain[I].second != 1) {
8414         // Mark the new end in the chain and go back, if required. It might be
8415         // required if the original stores come in reversed order, for example.
8416         if (ConsecutiveChain[I].first != E &&
8417             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8418             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8419           TriedTails.set(I);
8420           Tails.reset(ConsecutiveChain[I].first);
8421           if (Cnt < ConsecutiveChain[I].first + 2)
8422             Cnt = ConsecutiveChain[I].first + 2;
8423         }
8424         break;
8425       }
8426       // Move to the next value in the chain.
8427       I = ConsecutiveChain[I].first;
8428     }
8429     assert(!Operands.empty() && "Expected non-empty list of stores.");
8430 
8431     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8432     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8433     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8434 
8435     unsigned MinVF = R.getMinVF(EltSize);
8436     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8437                               MaxElts);
8438 
8439     // FIXME: Is division-by-2 the correct step? Should we assert that the
8440     // register size is a power-of-2?
8441     unsigned StartIdx = 0;
8442     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8443       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8444         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8445         if (!VectorizedStores.count(Slice.front()) &&
8446             !VectorizedStores.count(Slice.back()) &&
8447             vectorizeStoreChain(Slice, R, Cnt)) {
8448           // Mark the vectorized stores so that we don't vectorize them again.
8449           VectorizedStores.insert(Slice.begin(), Slice.end());
8450           Changed = true;
8451           // If we vectorized initial block, no need to try to vectorize it
8452           // again.
8453           if (Cnt == StartIdx)
8454             StartIdx += Size;
8455           Cnt += Size;
8456           continue;
8457         }
8458         ++Cnt;
8459       }
8460       // Check if the whole array was vectorized already - exit.
8461       if (StartIdx >= Operands.size())
8462         break;
8463     }
8464   }
8465 
8466   return Changed;
8467 }
8468 
8469 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8470   // Initialize the collections. We will make a single pass over the block.
8471   Stores.clear();
8472   GEPs.clear();
8473 
8474   // Visit the store and getelementptr instructions in BB and organize them in
8475   // Stores and GEPs according to the underlying objects of their pointer
8476   // operands.
8477   for (Instruction &I : *BB) {
8478     // Ignore store instructions that are volatile or have a pointer operand
8479     // that doesn't point to a scalar type.
8480     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8481       if (!SI->isSimple())
8482         continue;
8483       if (!isValidElementType(SI->getValueOperand()->getType()))
8484         continue;
8485       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8486     }
8487 
8488     // Ignore getelementptr instructions that have more than one index, a
8489     // constant index, or a pointer operand that doesn't point to a scalar
8490     // type.
8491     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8492       auto Idx = GEP->idx_begin()->get();
8493       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8494         continue;
8495       if (!isValidElementType(Idx->getType()))
8496         continue;
8497       if (GEP->getType()->isVectorTy())
8498         continue;
8499       GEPs[GEP->getPointerOperand()].push_back(GEP);
8500     }
8501   }
8502 }
8503 
8504 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8505   if (!A || !B)
8506     return false;
8507   Value *VL[] = {A, B};
8508   return tryToVectorizeList(VL, R);
8509 }
8510 
8511 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8512                                            bool LimitForRegisterSize) {
8513   if (VL.size() < 2)
8514     return false;
8515 
8516   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8517                     << VL.size() << ".\n");
8518 
8519   // Check that all of the parts are instructions of the same type,
8520   // we permit an alternate opcode via InstructionsState.
8521   InstructionsState S = getSameOpcode(VL);
8522   if (!S.getOpcode())
8523     return false;
8524 
8525   Instruction *I0 = cast<Instruction>(S.OpValue);
8526   // Make sure invalid types (including vector type) are rejected before
8527   // determining vectorization factor for scalar instructions.
8528   for (Value *V : VL) {
8529     Type *Ty = V->getType();
8530     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8531       // NOTE: the following will give user internal llvm type name, which may
8532       // not be useful.
8533       R.getORE()->emit([&]() {
8534         std::string type_str;
8535         llvm::raw_string_ostream rso(type_str);
8536         Ty->print(rso);
8537         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8538                << "Cannot SLP vectorize list: type "
8539                << rso.str() + " is unsupported by vectorizer";
8540       });
8541       return false;
8542     }
8543   }
8544 
8545   unsigned Sz = R.getVectorElementSize(I0);
8546   unsigned MinVF = R.getMinVF(Sz);
8547   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8548   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8549   if (MaxVF < 2) {
8550     R.getORE()->emit([&]() {
8551       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8552              << "Cannot SLP vectorize list: vectorization factor "
8553              << "less than 2 is not supported";
8554     });
8555     return false;
8556   }
8557 
8558   bool Changed = false;
8559   bool CandidateFound = false;
8560   InstructionCost MinCost = SLPCostThreshold.getValue();
8561   Type *ScalarTy = VL[0]->getType();
8562   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8563     ScalarTy = IE->getOperand(1)->getType();
8564 
8565   unsigned NextInst = 0, MaxInst = VL.size();
8566   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8567     // No actual vectorization should happen, if number of parts is the same as
8568     // provided vectorization factor (i.e. the scalar type is used for vector
8569     // code during codegen).
8570     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8571     if (TTI->getNumberOfParts(VecTy) == VF)
8572       continue;
8573     for (unsigned I = NextInst; I < MaxInst; ++I) {
8574       unsigned OpsWidth = 0;
8575 
8576       if (I + VF > MaxInst)
8577         OpsWidth = MaxInst - I;
8578       else
8579         OpsWidth = VF;
8580 
8581       if (!isPowerOf2_32(OpsWidth))
8582         continue;
8583 
8584       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8585           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8586         break;
8587 
8588       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8589       // Check that a previous iteration of this loop did not delete the Value.
8590       if (llvm::any_of(Ops, [&R](Value *V) {
8591             auto *I = dyn_cast<Instruction>(V);
8592             return I && R.isDeleted(I);
8593           }))
8594         continue;
8595 
8596       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8597                         << "\n");
8598 
8599       R.buildTree(Ops);
8600       if (R.isTreeTinyAndNotFullyVectorizable())
8601         continue;
8602       R.reorderTopToBottom();
8603       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
8604       R.buildExternalUses();
8605 
8606       R.computeMinimumValueSizes();
8607       InstructionCost Cost = R.getTreeCost();
8608       CandidateFound = true;
8609       MinCost = std::min(MinCost, Cost);
8610 
8611       if (Cost < -SLPCostThreshold) {
8612         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8613         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8614                                                     cast<Instruction>(Ops[0]))
8615                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8616                                  << " and with tree size "
8617                                  << ore::NV("TreeSize", R.getTreeSize()));
8618 
8619         R.vectorizeTree();
8620         // Move to the next bundle.
8621         I += VF - 1;
8622         NextInst = I + 1;
8623         Changed = true;
8624       }
8625     }
8626   }
8627 
8628   if (!Changed && CandidateFound) {
8629     R.getORE()->emit([&]() {
8630       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8631              << "List vectorization was possible but not beneficial with cost "
8632              << ore::NV("Cost", MinCost) << " >= "
8633              << ore::NV("Treshold", -SLPCostThreshold);
8634     });
8635   } else if (!Changed) {
8636     R.getORE()->emit([&]() {
8637       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8638              << "Cannot SLP vectorize list: vectorization was impossible"
8639              << " with available vectorization factors";
8640     });
8641   }
8642   return Changed;
8643 }
8644 
8645 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8646   if (!I)
8647     return false;
8648 
8649   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8650     return false;
8651 
8652   Value *P = I->getParent();
8653 
8654   // Vectorize in current basic block only.
8655   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8656   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8657   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8658     return false;
8659 
8660   // Try to vectorize V.
8661   if (tryToVectorizePair(Op0, Op1, R))
8662     return true;
8663 
8664   auto *A = dyn_cast<BinaryOperator>(Op0);
8665   auto *B = dyn_cast<BinaryOperator>(Op1);
8666   // Try to skip B.
8667   if (B && B->hasOneUse()) {
8668     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8669     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8670     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8671       return true;
8672     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8673       return true;
8674   }
8675 
8676   // Try to skip A.
8677   if (A && A->hasOneUse()) {
8678     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8679     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8680     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8681       return true;
8682     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8683       return true;
8684   }
8685   return false;
8686 }
8687 
8688 namespace {
8689 
8690 /// Model horizontal reductions.
8691 ///
8692 /// A horizontal reduction is a tree of reduction instructions that has values
8693 /// that can be put into a vector as its leaves. For example:
8694 ///
8695 /// mul mul mul mul
8696 ///  \  /    \  /
8697 ///   +       +
8698 ///    \     /
8699 ///       +
8700 /// This tree has "mul" as its leaf values and "+" as its reduction
8701 /// instructions. A reduction can feed into a store or a binary operation
8702 /// feeding a phi.
8703 ///    ...
8704 ///    \  /
8705 ///     +
8706 ///     |
8707 ///  phi +=
8708 ///
8709 ///  Or:
8710 ///    ...
8711 ///    \  /
8712 ///     +
8713 ///     |
8714 ///   *p =
8715 ///
8716 class HorizontalReduction {
8717   using ReductionOpsType = SmallVector<Value *, 16>;
8718   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8719   ReductionOpsListType ReductionOps;
8720   SmallVector<Value *, 32> ReducedVals;
8721   // Use map vector to make stable output.
8722   MapVector<Instruction *, Value *> ExtraArgs;
8723   WeakTrackingVH ReductionRoot;
8724   /// The type of reduction operation.
8725   RecurKind RdxKind;
8726 
8727   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8728 
8729   static bool isCmpSelMinMax(Instruction *I) {
8730     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8731            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8732   }
8733 
8734   // And/or are potentially poison-safe logical patterns like:
8735   // select x, y, false
8736   // select x, true, y
8737   static bool isBoolLogicOp(Instruction *I) {
8738     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8739            match(I, m_LogicalOr(m_Value(), m_Value()));
8740   }
8741 
8742   /// Checks if instruction is associative and can be vectorized.
8743   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8744     if (Kind == RecurKind::None)
8745       return false;
8746 
8747     // Integer ops that map to select instructions or intrinsics are fine.
8748     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8749         isBoolLogicOp(I))
8750       return true;
8751 
8752     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8753       // FP min/max are associative except for NaN and -0.0. We do not
8754       // have to rule out -0.0 here because the intrinsic semantics do not
8755       // specify a fixed result for it.
8756       return I->getFastMathFlags().noNaNs();
8757     }
8758 
8759     return I->isAssociative();
8760   }
8761 
8762   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8763     // Poison-safe 'or' takes the form: select X, true, Y
8764     // To make that work with the normal operand processing, we skip the
8765     // true value operand.
8766     // TODO: Change the code and data structures to handle this without a hack.
8767     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8768       return I->getOperand(2);
8769     return I->getOperand(Index);
8770   }
8771 
8772   /// Checks if the ParentStackElem.first should be marked as a reduction
8773   /// operation with an extra argument or as extra argument itself.
8774   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8775                     Value *ExtraArg) {
8776     if (ExtraArgs.count(ParentStackElem.first)) {
8777       ExtraArgs[ParentStackElem.first] = nullptr;
8778       // We ran into something like:
8779       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8780       // The whole ParentStackElem.first should be considered as an extra value
8781       // in this case.
8782       // Do not perform analysis of remaining operands of ParentStackElem.first
8783       // instruction, this whole instruction is an extra argument.
8784       ParentStackElem.second = INVALID_OPERAND_INDEX;
8785     } else {
8786       // We ran into something like:
8787       // ParentStackElem.first += ... + ExtraArg + ...
8788       ExtraArgs[ParentStackElem.first] = ExtraArg;
8789     }
8790   }
8791 
8792   /// Creates reduction operation with the current opcode.
8793   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8794                          Value *RHS, const Twine &Name, bool UseSelect) {
8795     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8796     switch (Kind) {
8797     case RecurKind::Or:
8798       if (UseSelect &&
8799           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8800         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8801       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8802                                  Name);
8803     case RecurKind::And:
8804       if (UseSelect &&
8805           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8806         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
8807       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8808                                  Name);
8809     case RecurKind::Add:
8810     case RecurKind::Mul:
8811     case RecurKind::Xor:
8812     case RecurKind::FAdd:
8813     case RecurKind::FMul:
8814       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8815                                  Name);
8816     case RecurKind::FMax:
8817       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8818     case RecurKind::FMin:
8819       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8820     case RecurKind::SMax:
8821       if (UseSelect) {
8822         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8823         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8824       }
8825       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8826     case RecurKind::SMin:
8827       if (UseSelect) {
8828         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8829         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8830       }
8831       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8832     case RecurKind::UMax:
8833       if (UseSelect) {
8834         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8835         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8836       }
8837       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8838     case RecurKind::UMin:
8839       if (UseSelect) {
8840         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8841         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8842       }
8843       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8844     default:
8845       llvm_unreachable("Unknown reduction operation.");
8846     }
8847   }
8848 
8849   /// Creates reduction operation with the current opcode with the IR flags
8850   /// from \p ReductionOps.
8851   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8852                          Value *RHS, const Twine &Name,
8853                          const ReductionOpsListType &ReductionOps) {
8854     bool UseSelect = ReductionOps.size() == 2 ||
8855                      // Logical or/and.
8856                      (ReductionOps.size() == 1 &&
8857                       isa<SelectInst>(ReductionOps.front().front()));
8858     assert((!UseSelect || ReductionOps.size() != 2 ||
8859             isa<SelectInst>(ReductionOps[1][0])) &&
8860            "Expected cmp + select pairs for reduction");
8861     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8862     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8863       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8864         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8865         propagateIRFlags(Op, ReductionOps[1]);
8866         return Op;
8867       }
8868     }
8869     propagateIRFlags(Op, ReductionOps[0]);
8870     return Op;
8871   }
8872 
8873   /// Creates reduction operation with the current opcode with the IR flags
8874   /// from \p I.
8875   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8876                          Value *RHS, const Twine &Name, Instruction *I) {
8877     auto *SelI = dyn_cast<SelectInst>(I);
8878     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8879     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8880       if (auto *Sel = dyn_cast<SelectInst>(Op))
8881         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
8882     }
8883     propagateIRFlags(Op, I);
8884     return Op;
8885   }
8886 
8887   static RecurKind getRdxKind(Instruction *I) {
8888     assert(I && "Expected instruction for reduction matching");
8889     if (match(I, m_Add(m_Value(), m_Value())))
8890       return RecurKind::Add;
8891     if (match(I, m_Mul(m_Value(), m_Value())))
8892       return RecurKind::Mul;
8893     if (match(I, m_And(m_Value(), m_Value())) ||
8894         match(I, m_LogicalAnd(m_Value(), m_Value())))
8895       return RecurKind::And;
8896     if (match(I, m_Or(m_Value(), m_Value())) ||
8897         match(I, m_LogicalOr(m_Value(), m_Value())))
8898       return RecurKind::Or;
8899     if (match(I, m_Xor(m_Value(), m_Value())))
8900       return RecurKind::Xor;
8901     if (match(I, m_FAdd(m_Value(), m_Value())))
8902       return RecurKind::FAdd;
8903     if (match(I, m_FMul(m_Value(), m_Value())))
8904       return RecurKind::FMul;
8905 
8906     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
8907       return RecurKind::FMax;
8908     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
8909       return RecurKind::FMin;
8910 
8911     // This matches either cmp+select or intrinsics. SLP is expected to handle
8912     // either form.
8913     // TODO: If we are canonicalizing to intrinsics, we can remove several
8914     //       special-case paths that deal with selects.
8915     if (match(I, m_SMax(m_Value(), m_Value())))
8916       return RecurKind::SMax;
8917     if (match(I, m_SMin(m_Value(), m_Value())))
8918       return RecurKind::SMin;
8919     if (match(I, m_UMax(m_Value(), m_Value())))
8920       return RecurKind::UMax;
8921     if (match(I, m_UMin(m_Value(), m_Value())))
8922       return RecurKind::UMin;
8923 
8924     if (auto *Select = dyn_cast<SelectInst>(I)) {
8925       // Try harder: look for min/max pattern based on instructions producing
8926       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
8927       // During the intermediate stages of SLP, it's very common to have
8928       // pattern like this (since optimizeGatherSequence is run only once
8929       // at the end):
8930       // %1 = extractelement <2 x i32> %a, i32 0
8931       // %2 = extractelement <2 x i32> %a, i32 1
8932       // %cond = icmp sgt i32 %1, %2
8933       // %3 = extractelement <2 x i32> %a, i32 0
8934       // %4 = extractelement <2 x i32> %a, i32 1
8935       // %select = select i1 %cond, i32 %3, i32 %4
8936       CmpInst::Predicate Pred;
8937       Instruction *L1;
8938       Instruction *L2;
8939 
8940       Value *LHS = Select->getTrueValue();
8941       Value *RHS = Select->getFalseValue();
8942       Value *Cond = Select->getCondition();
8943 
8944       // TODO: Support inverse predicates.
8945       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
8946         if (!isa<ExtractElementInst>(RHS) ||
8947             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8948           return RecurKind::None;
8949       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
8950         if (!isa<ExtractElementInst>(LHS) ||
8951             !L1->isIdenticalTo(cast<Instruction>(LHS)))
8952           return RecurKind::None;
8953       } else {
8954         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
8955           return RecurKind::None;
8956         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
8957             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
8958             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8959           return RecurKind::None;
8960       }
8961 
8962       switch (Pred) {
8963       default:
8964         return RecurKind::None;
8965       case CmpInst::ICMP_SGT:
8966       case CmpInst::ICMP_SGE:
8967         return RecurKind::SMax;
8968       case CmpInst::ICMP_SLT:
8969       case CmpInst::ICMP_SLE:
8970         return RecurKind::SMin;
8971       case CmpInst::ICMP_UGT:
8972       case CmpInst::ICMP_UGE:
8973         return RecurKind::UMax;
8974       case CmpInst::ICMP_ULT:
8975       case CmpInst::ICMP_ULE:
8976         return RecurKind::UMin;
8977       }
8978     }
8979     return RecurKind::None;
8980   }
8981 
8982   /// Get the index of the first operand.
8983   static unsigned getFirstOperandIndex(Instruction *I) {
8984     return isCmpSelMinMax(I) ? 1 : 0;
8985   }
8986 
8987   /// Total number of operands in the reduction operation.
8988   static unsigned getNumberOfOperands(Instruction *I) {
8989     return isCmpSelMinMax(I) ? 3 : 2;
8990   }
8991 
8992   /// Checks if the instruction is in basic block \p BB.
8993   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
8994   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
8995     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
8996       auto *Sel = cast<SelectInst>(I);
8997       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
8998       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
8999     }
9000     return I->getParent() == BB;
9001   }
9002 
9003   /// Expected number of uses for reduction operations/reduced values.
9004   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9005     if (IsCmpSelMinMax) {
9006       // SelectInst must be used twice while the condition op must have single
9007       // use only.
9008       if (auto *Sel = dyn_cast<SelectInst>(I))
9009         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9010       return I->hasNUses(2);
9011     }
9012 
9013     // Arithmetic reduction operation must be used once only.
9014     return I->hasOneUse();
9015   }
9016 
9017   /// Initializes the list of reduction operations.
9018   void initReductionOps(Instruction *I) {
9019     if (isCmpSelMinMax(I))
9020       ReductionOps.assign(2, ReductionOpsType());
9021     else
9022       ReductionOps.assign(1, ReductionOpsType());
9023   }
9024 
9025   /// Add all reduction operations for the reduction instruction \p I.
9026   void addReductionOps(Instruction *I) {
9027     if (isCmpSelMinMax(I)) {
9028       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9029       ReductionOps[1].emplace_back(I);
9030     } else {
9031       ReductionOps[0].emplace_back(I);
9032     }
9033   }
9034 
9035   static Value *getLHS(RecurKind Kind, Instruction *I) {
9036     if (Kind == RecurKind::None)
9037       return nullptr;
9038     return I->getOperand(getFirstOperandIndex(I));
9039   }
9040   static Value *getRHS(RecurKind Kind, Instruction *I) {
9041     if (Kind == RecurKind::None)
9042       return nullptr;
9043     return I->getOperand(getFirstOperandIndex(I) + 1);
9044   }
9045 
9046 public:
9047   HorizontalReduction() = default;
9048 
9049   /// Try to find a reduction tree.
9050   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9051     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9052            "Phi needs to use the binary operator");
9053     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9054             isa<IntrinsicInst>(Inst)) &&
9055            "Expected binop, select, or intrinsic for reduction matching");
9056     RdxKind = getRdxKind(Inst);
9057 
9058     // We could have a initial reductions that is not an add.
9059     //  r *= v1 + v2 + v3 + v4
9060     // In such a case start looking for a tree rooted in the first '+'.
9061     if (Phi) {
9062       if (getLHS(RdxKind, Inst) == Phi) {
9063         Phi = nullptr;
9064         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9065         if (!Inst)
9066           return false;
9067         RdxKind = getRdxKind(Inst);
9068       } else if (getRHS(RdxKind, Inst) == Phi) {
9069         Phi = nullptr;
9070         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9071         if (!Inst)
9072           return false;
9073         RdxKind = getRdxKind(Inst);
9074       }
9075     }
9076 
9077     if (!isVectorizable(RdxKind, Inst))
9078       return false;
9079 
9080     // Analyze "regular" integer/FP types for reductions - no target-specific
9081     // types or pointers.
9082     Type *Ty = Inst->getType();
9083     if (!isValidElementType(Ty) || Ty->isPointerTy())
9084       return false;
9085 
9086     // Though the ultimate reduction may have multiple uses, its condition must
9087     // have only single use.
9088     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9089       if (!Sel->getCondition()->hasOneUse())
9090         return false;
9091 
9092     ReductionRoot = Inst;
9093 
9094     // The opcode for leaf values that we perform a reduction on.
9095     // For example: load(x) + load(y) + load(z) + fptoui(w)
9096     // The leaf opcode for 'w' does not match, so we don't include it as a
9097     // potential candidate for the reduction.
9098     unsigned LeafOpcode = 0;
9099 
9100     // Post-order traverse the reduction tree starting at Inst. We only handle
9101     // true trees containing binary operators or selects.
9102     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9103     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9104     initReductionOps(Inst);
9105     while (!Stack.empty()) {
9106       Instruction *TreeN = Stack.back().first;
9107       unsigned EdgeToVisit = Stack.back().second++;
9108       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9109       bool IsReducedValue = TreeRdxKind != RdxKind;
9110 
9111       // Postorder visit.
9112       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9113         if (IsReducedValue)
9114           ReducedVals.push_back(TreeN);
9115         else {
9116           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9117           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9118             // Check if TreeN is an extra argument of its parent operation.
9119             if (Stack.size() <= 1) {
9120               // TreeN can't be an extra argument as it is a root reduction
9121               // operation.
9122               return false;
9123             }
9124             // Yes, TreeN is an extra argument, do not add it to a list of
9125             // reduction operations.
9126             // Stack[Stack.size() - 2] always points to the parent operation.
9127             markExtraArg(Stack[Stack.size() - 2], TreeN);
9128             ExtraArgs.erase(TreeN);
9129           } else
9130             addReductionOps(TreeN);
9131         }
9132         // Retract.
9133         Stack.pop_back();
9134         continue;
9135       }
9136 
9137       // Visit operands.
9138       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9139       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9140       if (!EdgeInst) {
9141         // Edge value is not a reduction instruction or a leaf instruction.
9142         // (It may be a constant, function argument, or something else.)
9143         markExtraArg(Stack.back(), EdgeVal);
9144         continue;
9145       }
9146       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9147       // Continue analysis if the next operand is a reduction operation or
9148       // (possibly) a leaf value. If the leaf value opcode is not set,
9149       // the first met operation != reduction operation is considered as the
9150       // leaf opcode.
9151       // Only handle trees in the current basic block.
9152       // Each tree node needs to have minimal number of users except for the
9153       // ultimate reduction.
9154       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9155       if (EdgeInst != Phi && EdgeInst != Inst &&
9156           hasSameParent(EdgeInst, Inst->getParent()) &&
9157           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9158           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9159         if (IsRdxInst) {
9160           // We need to be able to reassociate the reduction operations.
9161           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9162             // I is an extra argument for TreeN (its parent operation).
9163             markExtraArg(Stack.back(), EdgeInst);
9164             continue;
9165           }
9166         } else if (!LeafOpcode) {
9167           LeafOpcode = EdgeInst->getOpcode();
9168         }
9169         Stack.push_back(
9170             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9171         continue;
9172       }
9173       // I is an extra argument for TreeN (its parent operation).
9174       markExtraArg(Stack.back(), EdgeInst);
9175     }
9176     return true;
9177   }
9178 
9179   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9180   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9181     // If there are a sufficient number of reduction values, reduce
9182     // to a nearby power-of-2. We can safely generate oversized
9183     // vectors and rely on the backend to split them to legal sizes.
9184     unsigned NumReducedVals = ReducedVals.size();
9185     if (NumReducedVals < 4)
9186       return nullptr;
9187 
9188     // Intersect the fast-math-flags from all reduction operations.
9189     FastMathFlags RdxFMF;
9190     RdxFMF.set();
9191     for (ReductionOpsType &RdxOp : ReductionOps) {
9192       for (Value *RdxVal : RdxOp) {
9193         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9194           RdxFMF &= FPMO->getFastMathFlags();
9195       }
9196     }
9197 
9198     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9199     Builder.setFastMathFlags(RdxFMF);
9200 
9201     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9202     // The same extra argument may be used several times, so log each attempt
9203     // to use it.
9204     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9205       assert(Pair.first && "DebugLoc must be set.");
9206       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9207     }
9208 
9209     // The compare instruction of a min/max is the insertion point for new
9210     // instructions and may be replaced with a new compare instruction.
9211     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9212       assert(isa<SelectInst>(RdxRootInst) &&
9213              "Expected min/max reduction to have select root instruction");
9214       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9215       assert(isa<Instruction>(ScalarCond) &&
9216              "Expected min/max reduction to have compare condition");
9217       return cast<Instruction>(ScalarCond);
9218     };
9219 
9220     // The reduction root is used as the insertion point for new instructions,
9221     // so set it as externally used to prevent it from being deleted.
9222     ExternallyUsedValues[ReductionRoot];
9223     SmallVector<Value *, 16> IgnoreList;
9224     for (ReductionOpsType &RdxOp : ReductionOps)
9225       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9226 
9227     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9228     if (NumReducedVals > ReduxWidth) {
9229       // In the loop below, we are building a tree based on a window of
9230       // 'ReduxWidth' values.
9231       // If the operands of those values have common traits (compare predicate,
9232       // constant operand, etc), then we want to group those together to
9233       // minimize the cost of the reduction.
9234 
9235       // TODO: This should be extended to count common operands for
9236       //       compares and binops.
9237 
9238       // Step 1: Count the number of times each compare predicate occurs.
9239       SmallDenseMap<unsigned, unsigned> PredCountMap;
9240       for (Value *RdxVal : ReducedVals) {
9241         CmpInst::Predicate Pred;
9242         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9243           ++PredCountMap[Pred];
9244       }
9245       // Step 2: Sort the values so the most common predicates come first.
9246       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9247         CmpInst::Predicate PredA, PredB;
9248         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9249             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9250           return PredCountMap[PredA] > PredCountMap[PredB];
9251         }
9252         return false;
9253       });
9254     }
9255 
9256     Value *VectorizedTree = nullptr;
9257     unsigned i = 0;
9258     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9259       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9260       V.buildTree(VL, IgnoreList);
9261       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9262         break;
9263       if (V.isLoadCombineReductionCandidate(RdxKind))
9264         break;
9265       V.reorderTopToBottom();
9266       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9267       V.buildExternalUses(ExternallyUsedValues);
9268 
9269       // For a poison-safe boolean logic reduction, do not replace select
9270       // instructions with logic ops. All reduced values will be frozen (see
9271       // below) to prevent leaking poison.
9272       if (isa<SelectInst>(ReductionRoot) &&
9273           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9274           NumReducedVals != ReduxWidth)
9275         break;
9276 
9277       V.computeMinimumValueSizes();
9278 
9279       // Estimate cost.
9280       InstructionCost TreeCost =
9281           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9282       InstructionCost ReductionCost =
9283           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9284       InstructionCost Cost = TreeCost + ReductionCost;
9285       if (!Cost.isValid()) {
9286         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9287         return nullptr;
9288       }
9289       if (Cost >= -SLPCostThreshold) {
9290         V.getORE()->emit([&]() {
9291           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9292                                           cast<Instruction>(VL[0]))
9293                  << "Vectorizing horizontal reduction is possible"
9294                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9295                  << " and threshold "
9296                  << ore::NV("Threshold", -SLPCostThreshold);
9297         });
9298         break;
9299       }
9300 
9301       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9302                         << Cost << ". (HorRdx)\n");
9303       V.getORE()->emit([&]() {
9304         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9305                                   cast<Instruction>(VL[0]))
9306                << "Vectorized horizontal reduction with cost "
9307                << ore::NV("Cost", Cost) << " and with tree size "
9308                << ore::NV("TreeSize", V.getTreeSize());
9309       });
9310 
9311       // Vectorize a tree.
9312       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9313       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9314 
9315       // Emit a reduction. If the root is a select (min/max idiom), the insert
9316       // point is the compare condition of that select.
9317       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9318       if (isCmpSelMinMax(RdxRootInst))
9319         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9320       else
9321         Builder.SetInsertPoint(RdxRootInst);
9322 
9323       // To prevent poison from leaking across what used to be sequential, safe,
9324       // scalar boolean logic operations, the reduction operand must be frozen.
9325       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9326         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9327 
9328       Value *ReducedSubTree =
9329           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9330 
9331       if (!VectorizedTree) {
9332         // Initialize the final value in the reduction.
9333         VectorizedTree = ReducedSubTree;
9334       } else {
9335         // Update the final value in the reduction.
9336         Builder.SetCurrentDebugLocation(Loc);
9337         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9338                                   ReducedSubTree, "op.rdx", ReductionOps);
9339       }
9340       i += ReduxWidth;
9341       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9342     }
9343 
9344     if (VectorizedTree) {
9345       // Finish the reduction.
9346       for (; i < NumReducedVals; ++i) {
9347         auto *I = cast<Instruction>(ReducedVals[i]);
9348         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9349         VectorizedTree =
9350             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9351       }
9352       for (auto &Pair : ExternallyUsedValues) {
9353         // Add each externally used value to the final reduction.
9354         for (auto *I : Pair.second) {
9355           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9356           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9357                                     Pair.first, "op.extra", I);
9358         }
9359       }
9360 
9361       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9362 
9363       // Mark all scalar reduction ops for deletion, they are replaced by the
9364       // vector reductions.
9365       V.eraseInstructions(IgnoreList);
9366     }
9367     return VectorizedTree;
9368   }
9369 
9370   unsigned numReductionValues() const { return ReducedVals.size(); }
9371 
9372 private:
9373   /// Calculate the cost of a reduction.
9374   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9375                                    Value *FirstReducedVal, unsigned ReduxWidth,
9376                                    FastMathFlags FMF) {
9377     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9378     Type *ScalarTy = FirstReducedVal->getType();
9379     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9380     InstructionCost VectorCost, ScalarCost;
9381     switch (RdxKind) {
9382     case RecurKind::Add:
9383     case RecurKind::Mul:
9384     case RecurKind::Or:
9385     case RecurKind::And:
9386     case RecurKind::Xor:
9387     case RecurKind::FAdd:
9388     case RecurKind::FMul: {
9389       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9390       VectorCost =
9391           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9392       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9393       break;
9394     }
9395     case RecurKind::FMax:
9396     case RecurKind::FMin: {
9397       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9398       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9399       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9400                                                /*IsUnsigned=*/false, CostKind);
9401       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9402       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9403                                            SclCondTy, RdxPred, CostKind) +
9404                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9405                                            SclCondTy, RdxPred, CostKind);
9406       break;
9407     }
9408     case RecurKind::SMax:
9409     case RecurKind::SMin:
9410     case RecurKind::UMax:
9411     case RecurKind::UMin: {
9412       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9413       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9414       bool IsUnsigned =
9415           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9416       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9417                                                CostKind);
9418       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9419       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9420                                            SclCondTy, RdxPred, CostKind) +
9421                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9422                                            SclCondTy, RdxPred, CostKind);
9423       break;
9424     }
9425     default:
9426       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9427     }
9428 
9429     // Scalar cost is repeated for N-1 elements.
9430     ScalarCost *= (ReduxWidth - 1);
9431     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9432                       << " for reduction that starts with " << *FirstReducedVal
9433                       << " (It is a splitting reduction)\n");
9434     return VectorCost - ScalarCost;
9435   }
9436 
9437   /// Emit a horizontal reduction of the vectorized value.
9438   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9439                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9440     assert(VectorizedValue && "Need to have a vectorized tree node");
9441     assert(isPowerOf2_32(ReduxWidth) &&
9442            "We only handle power-of-two reductions for now");
9443     assert(RdxKind != RecurKind::FMulAdd &&
9444            "A call to the llvm.fmuladd intrinsic is not handled yet");
9445 
9446     ++NumVectorInstructions;
9447     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9448   }
9449 };
9450 
9451 } // end anonymous namespace
9452 
9453 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9454   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9455     return cast<FixedVectorType>(IE->getType())->getNumElements();
9456 
9457   unsigned AggregateSize = 1;
9458   auto *IV = cast<InsertValueInst>(InsertInst);
9459   Type *CurrentType = IV->getType();
9460   do {
9461     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9462       for (auto *Elt : ST->elements())
9463         if (Elt != ST->getElementType(0)) // check homogeneity
9464           return None;
9465       AggregateSize *= ST->getNumElements();
9466       CurrentType = ST->getElementType(0);
9467     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9468       AggregateSize *= AT->getNumElements();
9469       CurrentType = AT->getElementType();
9470     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9471       AggregateSize *= VT->getNumElements();
9472       return AggregateSize;
9473     } else if (CurrentType->isSingleValueType()) {
9474       return AggregateSize;
9475     } else {
9476       return None;
9477     }
9478   } while (true);
9479 }
9480 
9481 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
9482                                    TargetTransformInfo *TTI,
9483                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9484                                    SmallVectorImpl<Value *> &InsertElts,
9485                                    unsigned OperandOffset) {
9486   do {
9487     Value *InsertedOperand = LastInsertInst->getOperand(1);
9488     Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
9489     if (!OperandIndex)
9490       return false;
9491     if (isa<InsertElementInst>(InsertedOperand) ||
9492         isa<InsertValueInst>(InsertedOperand)) {
9493       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9494                                   BuildVectorOpds, InsertElts, *OperandIndex))
9495         return false;
9496     } else {
9497       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9498       InsertElts[*OperandIndex] = LastInsertInst;
9499     }
9500     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9501   } while (LastInsertInst != nullptr &&
9502            (isa<InsertValueInst>(LastInsertInst) ||
9503             isa<InsertElementInst>(LastInsertInst)) &&
9504            LastInsertInst->hasOneUse());
9505   return true;
9506 }
9507 
9508 /// Recognize construction of vectors like
9509 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9510 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9511 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9512 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9513 ///  starting from the last insertelement or insertvalue instruction.
9514 ///
9515 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9516 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9517 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9518 ///
9519 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9520 ///
9521 /// \return true if it matches.
9522 static bool findBuildAggregate(Instruction *LastInsertInst,
9523                                TargetTransformInfo *TTI,
9524                                SmallVectorImpl<Value *> &BuildVectorOpds,
9525                                SmallVectorImpl<Value *> &InsertElts) {
9526 
9527   assert((isa<InsertElementInst>(LastInsertInst) ||
9528           isa<InsertValueInst>(LastInsertInst)) &&
9529          "Expected insertelement or insertvalue instruction!");
9530 
9531   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9532          "Expected empty result vectors!");
9533 
9534   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9535   if (!AggregateSize)
9536     return false;
9537   BuildVectorOpds.resize(*AggregateSize);
9538   InsertElts.resize(*AggregateSize);
9539 
9540   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
9541                              0)) {
9542     llvm::erase_value(BuildVectorOpds, nullptr);
9543     llvm::erase_value(InsertElts, nullptr);
9544     if (BuildVectorOpds.size() >= 2)
9545       return true;
9546   }
9547 
9548   return false;
9549 }
9550 
9551 /// Try and get a reduction value from a phi node.
9552 ///
9553 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9554 /// if they come from either \p ParentBB or a containing loop latch.
9555 ///
9556 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9557 /// if not possible.
9558 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9559                                 BasicBlock *ParentBB, LoopInfo *LI) {
9560   // There are situations where the reduction value is not dominated by the
9561   // reduction phi. Vectorizing such cases has been reported to cause
9562   // miscompiles. See PR25787.
9563   auto DominatedReduxValue = [&](Value *R) {
9564     return isa<Instruction>(R) &&
9565            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9566   };
9567 
9568   Value *Rdx = nullptr;
9569 
9570   // Return the incoming value if it comes from the same BB as the phi node.
9571   if (P->getIncomingBlock(0) == ParentBB) {
9572     Rdx = P->getIncomingValue(0);
9573   } else if (P->getIncomingBlock(1) == ParentBB) {
9574     Rdx = P->getIncomingValue(1);
9575   }
9576 
9577   if (Rdx && DominatedReduxValue(Rdx))
9578     return Rdx;
9579 
9580   // Otherwise, check whether we have a loop latch to look at.
9581   Loop *BBL = LI->getLoopFor(ParentBB);
9582   if (!BBL)
9583     return nullptr;
9584   BasicBlock *BBLatch = BBL->getLoopLatch();
9585   if (!BBLatch)
9586     return nullptr;
9587 
9588   // There is a loop latch, return the incoming value if it comes from
9589   // that. This reduction pattern occasionally turns up.
9590   if (P->getIncomingBlock(0) == BBLatch) {
9591     Rdx = P->getIncomingValue(0);
9592   } else if (P->getIncomingBlock(1) == BBLatch) {
9593     Rdx = P->getIncomingValue(1);
9594   }
9595 
9596   if (Rdx && DominatedReduxValue(Rdx))
9597     return Rdx;
9598 
9599   return nullptr;
9600 }
9601 
9602 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9603   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9604     return true;
9605   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9606     return true;
9607   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9608     return true;
9609   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9610     return true;
9611   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9612     return true;
9613   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9614     return true;
9615   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9616     return true;
9617   return false;
9618 }
9619 
9620 /// Attempt to reduce a horizontal reduction.
9621 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9622 /// with reduction operators \a Root (or one of its operands) in a basic block
9623 /// \a BB, then check if it can be done. If horizontal reduction is not found
9624 /// and root instruction is a binary operation, vectorization of the operands is
9625 /// attempted.
9626 /// \returns true if a horizontal reduction was matched and reduced or operands
9627 /// of one of the binary instruction were vectorized.
9628 /// \returns false if a horizontal reduction was not matched (or not possible)
9629 /// or no vectorization of any binary operation feeding \a Root instruction was
9630 /// performed.
9631 static bool tryToVectorizeHorReductionOrInstOperands(
9632     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9633     TargetTransformInfo *TTI,
9634     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9635   if (!ShouldVectorizeHor)
9636     return false;
9637 
9638   if (!Root)
9639     return false;
9640 
9641   if (Root->getParent() != BB || isa<PHINode>(Root))
9642     return false;
9643   // Start analysis starting from Root instruction. If horizontal reduction is
9644   // found, try to vectorize it. If it is not a horizontal reduction or
9645   // vectorization is not possible or not effective, and currently analyzed
9646   // instruction is a binary operation, try to vectorize the operands, using
9647   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9648   // the same procedure considering each operand as a possible root of the
9649   // horizontal reduction.
9650   // Interrupt the process if the Root instruction itself was vectorized or all
9651   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9652   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9653   // CmpInsts so we can skip extra attempts in
9654   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9655   std::queue<std::pair<Instruction *, unsigned>> Stack;
9656   Stack.emplace(Root, 0);
9657   SmallPtrSet<Value *, 8> VisitedInstrs;
9658   SmallVector<WeakTrackingVH> PostponedInsts;
9659   bool Res = false;
9660   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9661                                      Value *&B1) -> Value * {
9662     bool IsBinop = matchRdxBop(Inst, B0, B1);
9663     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9664     if (IsBinop || IsSelect) {
9665       HorizontalReduction HorRdx;
9666       if (HorRdx.matchAssociativeReduction(P, Inst))
9667         return HorRdx.tryToReduce(R, TTI);
9668     }
9669     return nullptr;
9670   };
9671   while (!Stack.empty()) {
9672     Instruction *Inst;
9673     unsigned Level;
9674     std::tie(Inst, Level) = Stack.front();
9675     Stack.pop();
9676     // Do not try to analyze instruction that has already been vectorized.
9677     // This may happen when we vectorize instruction operands on a previous
9678     // iteration while stack was populated before that happened.
9679     if (R.isDeleted(Inst))
9680       continue;
9681     Value *B0 = nullptr, *B1 = nullptr;
9682     if (Value *V = TryToReduce(Inst, B0, B1)) {
9683       Res = true;
9684       // Set P to nullptr to avoid re-analysis of phi node in
9685       // matchAssociativeReduction function unless this is the root node.
9686       P = nullptr;
9687       if (auto *I = dyn_cast<Instruction>(V)) {
9688         // Try to find another reduction.
9689         Stack.emplace(I, Level);
9690         continue;
9691       }
9692     } else {
9693       bool IsBinop = B0 && B1;
9694       if (P && IsBinop) {
9695         Inst = dyn_cast<Instruction>(B0);
9696         if (Inst == P)
9697           Inst = dyn_cast<Instruction>(B1);
9698         if (!Inst) {
9699           // Set P to nullptr to avoid re-analysis of phi node in
9700           // matchAssociativeReduction function unless this is the root node.
9701           P = nullptr;
9702           continue;
9703         }
9704       }
9705       // Set P to nullptr to avoid re-analysis of phi node in
9706       // matchAssociativeReduction function unless this is the root node.
9707       P = nullptr;
9708       // Do not try to vectorize CmpInst operands, this is done separately.
9709       // Final attempt for binop args vectorization should happen after the loop
9710       // to try to find reductions.
9711       if (!isa<CmpInst>(Inst))
9712         PostponedInsts.push_back(Inst);
9713     }
9714 
9715     // Try to vectorize operands.
9716     // Continue analysis for the instruction from the same basic block only to
9717     // save compile time.
9718     if (++Level < RecursionMaxDepth)
9719       for (auto *Op : Inst->operand_values())
9720         if (VisitedInstrs.insert(Op).second)
9721           if (auto *I = dyn_cast<Instruction>(Op))
9722             // Do not try to vectorize CmpInst operands,  this is done
9723             // separately.
9724             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9725                 I->getParent() == BB)
9726               Stack.emplace(I, Level);
9727   }
9728   // Try to vectorized binops where reductions were not found.
9729   for (Value *V : PostponedInsts)
9730     if (auto *Inst = dyn_cast<Instruction>(V))
9731       if (!R.isDeleted(Inst))
9732         Res |= Vectorize(Inst, R);
9733   return Res;
9734 }
9735 
9736 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9737                                                  BasicBlock *BB, BoUpSLP &R,
9738                                                  TargetTransformInfo *TTI) {
9739   auto *I = dyn_cast_or_null<Instruction>(V);
9740   if (!I)
9741     return false;
9742 
9743   if (!isa<BinaryOperator>(I))
9744     P = nullptr;
9745   // Try to match and vectorize a horizontal reduction.
9746   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9747     return tryToVectorize(I, R);
9748   };
9749   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9750                                                   ExtraVectorization);
9751 }
9752 
9753 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9754                                                  BasicBlock *BB, BoUpSLP &R) {
9755   const DataLayout &DL = BB->getModule()->getDataLayout();
9756   if (!R.canMapToVector(IVI->getType(), DL))
9757     return false;
9758 
9759   SmallVector<Value *, 16> BuildVectorOpds;
9760   SmallVector<Value *, 16> BuildVectorInsts;
9761   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9762     return false;
9763 
9764   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9765   // Aggregate value is unlikely to be processed in vector register.
9766   return tryToVectorizeList(BuildVectorOpds, R);
9767 }
9768 
9769 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9770                                                    BasicBlock *BB, BoUpSLP &R) {
9771   SmallVector<Value *, 16> BuildVectorInsts;
9772   SmallVector<Value *, 16> BuildVectorOpds;
9773   SmallVector<int> Mask;
9774   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9775       (llvm::all_of(
9776            BuildVectorOpds,
9777            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9778        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9779     return false;
9780 
9781   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9782   return tryToVectorizeList(BuildVectorInsts, R);
9783 }
9784 
9785 template <typename T>
9786 static bool
9787 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9788                        function_ref<unsigned(T *)> Limit,
9789                        function_ref<bool(T *, T *)> Comparator,
9790                        function_ref<bool(T *, T *)> AreCompatible,
9791                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
9792                        bool LimitForRegisterSize) {
9793   bool Changed = false;
9794   // Sort by type, parent, operands.
9795   stable_sort(Incoming, Comparator);
9796 
9797   // Try to vectorize elements base on their type.
9798   SmallVector<T *> Candidates;
9799   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9800     // Look for the next elements with the same type, parent and operand
9801     // kinds.
9802     auto *SameTypeIt = IncIt;
9803     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9804       ++SameTypeIt;
9805 
9806     // Try to vectorize them.
9807     unsigned NumElts = (SameTypeIt - IncIt);
9808     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9809                       << NumElts << ")\n");
9810     // The vectorization is a 3-state attempt:
9811     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9812     // size of maximal register at first.
9813     // 2. Try to vectorize remaining instructions with the same type, if
9814     // possible. This may result in the better vectorization results rather than
9815     // if we try just to vectorize instructions with the same/alternate opcodes.
9816     // 3. Final attempt to try to vectorize all instructions with the
9817     // same/alternate ops only, this may result in some extra final
9818     // vectorization.
9819     if (NumElts > 1 &&
9820         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9821       // Success start over because instructions might have been changed.
9822       Changed = true;
9823     } else if (NumElts < Limit(*IncIt) &&
9824                (Candidates.empty() ||
9825                 Candidates.front()->getType() == (*IncIt)->getType())) {
9826       Candidates.append(IncIt, std::next(IncIt, NumElts));
9827     }
9828     // Final attempt to vectorize instructions with the same types.
9829     if (Candidates.size() > 1 &&
9830         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9831       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
9832         // Success start over because instructions might have been changed.
9833         Changed = true;
9834       } else if (LimitForRegisterSize) {
9835         // Try to vectorize using small vectors.
9836         for (auto *It = Candidates.begin(), *End = Candidates.end();
9837              It != End;) {
9838           auto *SameTypeIt = It;
9839           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9840             ++SameTypeIt;
9841           unsigned NumElts = (SameTypeIt - It);
9842           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
9843                                             /*LimitForRegisterSize=*/false))
9844             Changed = true;
9845           It = SameTypeIt;
9846         }
9847       }
9848       Candidates.clear();
9849     }
9850 
9851     // Start over at the next instruction of a different type (or the end).
9852     IncIt = SameTypeIt;
9853   }
9854   return Changed;
9855 }
9856 
9857 /// Compare two cmp instructions. If IsCompatibility is true, function returns
9858 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
9859 /// operands. If IsCompatibility is false, function implements strict weak
9860 /// ordering relation between two cmp instructions, returning true if the first
9861 /// instruction is "less" than the second, i.e. its predicate is less than the
9862 /// predicate of the second or the operands IDs are less than the operands IDs
9863 /// of the second cmp instruction.
9864 template <bool IsCompatibility>
9865 static bool compareCmp(Value *V, Value *V2,
9866                        function_ref<bool(Instruction *)> IsDeleted) {
9867   auto *CI1 = cast<CmpInst>(V);
9868   auto *CI2 = cast<CmpInst>(V2);
9869   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
9870     return false;
9871   if (CI1->getOperand(0)->getType()->getTypeID() <
9872       CI2->getOperand(0)->getType()->getTypeID())
9873     return !IsCompatibility;
9874   if (CI1->getOperand(0)->getType()->getTypeID() >
9875       CI2->getOperand(0)->getType()->getTypeID())
9876     return false;
9877   CmpInst::Predicate Pred1 = CI1->getPredicate();
9878   CmpInst::Predicate Pred2 = CI2->getPredicate();
9879   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
9880   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
9881   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
9882   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
9883   if (BasePred1 < BasePred2)
9884     return !IsCompatibility;
9885   if (BasePred1 > BasePred2)
9886     return false;
9887   // Compare operands.
9888   bool LEPreds = Pred1 <= Pred2;
9889   bool GEPreds = Pred1 >= Pred2;
9890   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
9891     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
9892     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
9893     if (Op1->getValueID() < Op2->getValueID())
9894       return !IsCompatibility;
9895     if (Op1->getValueID() > Op2->getValueID())
9896       return false;
9897     if (auto *I1 = dyn_cast<Instruction>(Op1))
9898       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
9899         if (I1->getParent() != I2->getParent())
9900           return false;
9901         InstructionsState S = getSameOpcode({I1, I2});
9902         if (S.getOpcode())
9903           continue;
9904         return false;
9905       }
9906   }
9907   return IsCompatibility;
9908 }
9909 
9910 bool SLPVectorizerPass::vectorizeSimpleInstructions(
9911     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
9912     bool AtTerminator) {
9913   bool OpsChanged = false;
9914   SmallVector<Instruction *, 4> PostponedCmps;
9915   for (auto *I : reverse(Instructions)) {
9916     if (R.isDeleted(I))
9917       continue;
9918     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
9919       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
9920     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
9921       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
9922     else if (isa<CmpInst>(I))
9923       PostponedCmps.push_back(I);
9924   }
9925   if (AtTerminator) {
9926     // Try to find reductions first.
9927     for (Instruction *I : PostponedCmps) {
9928       if (R.isDeleted(I))
9929         continue;
9930       for (Value *Op : I->operands())
9931         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
9932     }
9933     // Try to vectorize operands as vector bundles.
9934     for (Instruction *I : PostponedCmps) {
9935       if (R.isDeleted(I))
9936         continue;
9937       OpsChanged |= tryToVectorize(I, R);
9938     }
9939     // Try to vectorize list of compares.
9940     // Sort by type, compare predicate, etc.
9941     auto &&CompareSorter = [&R](Value *V, Value *V2) {
9942       return compareCmp<false>(V, V2,
9943                                [&R](Instruction *I) { return R.isDeleted(I); });
9944     };
9945 
9946     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
9947       if (V1 == V2)
9948         return true;
9949       return compareCmp<true>(V1, V2,
9950                               [&R](Instruction *I) { return R.isDeleted(I); });
9951     };
9952     auto Limit = [&R](Value *V) {
9953       unsigned EltSize = R.getVectorElementSize(V);
9954       return std::max(2U, R.getMaxVecRegSize() / EltSize);
9955     };
9956 
9957     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
9958     OpsChanged |= tryToVectorizeSequence<Value>(
9959         Vals, Limit, CompareSorter, AreCompatibleCompares,
9960         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9961           // Exclude possible reductions from other blocks.
9962           bool ArePossiblyReducedInOtherBlock =
9963               any_of(Candidates, [](Value *V) {
9964                 return any_of(V->users(), [V](User *U) {
9965                   return isa<SelectInst>(U) &&
9966                          cast<SelectInst>(U)->getParent() !=
9967                              cast<Instruction>(V)->getParent();
9968                 });
9969               });
9970           if (ArePossiblyReducedInOtherBlock)
9971             return false;
9972           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9973         },
9974         /*LimitForRegisterSize=*/true);
9975     Instructions.clear();
9976   } else {
9977     // Insert in reverse order since the PostponedCmps vector was filled in
9978     // reverse order.
9979     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
9980   }
9981   return OpsChanged;
9982 }
9983 
9984 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
9985   bool Changed = false;
9986   SmallVector<Value *, 4> Incoming;
9987   SmallPtrSet<Value *, 16> VisitedInstrs;
9988   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
9989   // node. Allows better to identify the chains that can be vectorized in the
9990   // better way.
9991   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
9992   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
9993     assert(isValidElementType(V1->getType()) &&
9994            isValidElementType(V2->getType()) &&
9995            "Expected vectorizable types only.");
9996     // It is fine to compare type IDs here, since we expect only vectorizable
9997     // types, like ints, floats and pointers, we don't care about other type.
9998     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
9999       return true;
10000     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10001       return false;
10002     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10003     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10004     if (Opcodes1.size() < Opcodes2.size())
10005       return true;
10006     if (Opcodes1.size() > Opcodes2.size())
10007       return false;
10008     Optional<bool> ConstOrder;
10009     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10010       // Undefs are compatible with any other value.
10011       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10012         if (!ConstOrder)
10013           ConstOrder =
10014               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10015         continue;
10016       }
10017       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10018         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10019           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10020           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10021           if (!NodeI1)
10022             return NodeI2 != nullptr;
10023           if (!NodeI2)
10024             return false;
10025           assert((NodeI1 == NodeI2) ==
10026                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10027                  "Different nodes should have different DFS numbers");
10028           if (NodeI1 != NodeI2)
10029             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10030           InstructionsState S = getSameOpcode({I1, I2});
10031           if (S.getOpcode())
10032             continue;
10033           return I1->getOpcode() < I2->getOpcode();
10034         }
10035       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10036         if (!ConstOrder)
10037           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10038         continue;
10039       }
10040       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10041         return true;
10042       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10043         return false;
10044     }
10045     return ConstOrder && *ConstOrder;
10046   };
10047   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10048     if (V1 == V2)
10049       return true;
10050     if (V1->getType() != V2->getType())
10051       return false;
10052     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10053     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10054     if (Opcodes1.size() != Opcodes2.size())
10055       return false;
10056     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10057       // Undefs are compatible with any other value.
10058       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10059         continue;
10060       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10061         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10062           if (I1->getParent() != I2->getParent())
10063             return false;
10064           InstructionsState S = getSameOpcode({I1, I2});
10065           if (S.getOpcode())
10066             continue;
10067           return false;
10068         }
10069       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10070         continue;
10071       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10072         return false;
10073     }
10074     return true;
10075   };
10076   auto Limit = [&R](Value *V) {
10077     unsigned EltSize = R.getVectorElementSize(V);
10078     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10079   };
10080 
10081   bool HaveVectorizedPhiNodes = false;
10082   do {
10083     // Collect the incoming values from the PHIs.
10084     Incoming.clear();
10085     for (Instruction &I : *BB) {
10086       PHINode *P = dyn_cast<PHINode>(&I);
10087       if (!P)
10088         break;
10089 
10090       // No need to analyze deleted, vectorized and non-vectorizable
10091       // instructions.
10092       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10093           isValidElementType(P->getType()))
10094         Incoming.push_back(P);
10095     }
10096 
10097     // Find the corresponding non-phi nodes for better matching when trying to
10098     // build the tree.
10099     for (Value *V : Incoming) {
10100       SmallVectorImpl<Value *> &Opcodes =
10101           PHIToOpcodes.try_emplace(V).first->getSecond();
10102       if (!Opcodes.empty())
10103         continue;
10104       SmallVector<Value *, 4> Nodes(1, V);
10105       SmallPtrSet<Value *, 4> Visited;
10106       while (!Nodes.empty()) {
10107         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10108         if (!Visited.insert(PHI).second)
10109           continue;
10110         for (Value *V : PHI->incoming_values()) {
10111           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10112             Nodes.push_back(PHI1);
10113             continue;
10114           }
10115           Opcodes.emplace_back(V);
10116         }
10117       }
10118     }
10119 
10120     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10121         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10122         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10123           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10124         },
10125         /*LimitForRegisterSize=*/true);
10126     Changed |= HaveVectorizedPhiNodes;
10127     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10128   } while (HaveVectorizedPhiNodes);
10129 
10130   VisitedInstrs.clear();
10131 
10132   SmallVector<Instruction *, 8> PostProcessInstructions;
10133   SmallDenseSet<Instruction *, 4> KeyNodes;
10134   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10135     // Skip instructions with scalable type. The num of elements is unknown at
10136     // compile-time for scalable type.
10137     if (isa<ScalableVectorType>(it->getType()))
10138       continue;
10139 
10140     // Skip instructions marked for the deletion.
10141     if (R.isDeleted(&*it))
10142       continue;
10143     // We may go through BB multiple times so skip the one we have checked.
10144     if (!VisitedInstrs.insert(&*it).second) {
10145       if (it->use_empty() && KeyNodes.contains(&*it) &&
10146           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10147                                       it->isTerminator())) {
10148         // We would like to start over since some instructions are deleted
10149         // and the iterator may become invalid value.
10150         Changed = true;
10151         it = BB->begin();
10152         e = BB->end();
10153       }
10154       continue;
10155     }
10156 
10157     if (isa<DbgInfoIntrinsic>(it))
10158       continue;
10159 
10160     // Try to vectorize reductions that use PHINodes.
10161     if (PHINode *P = dyn_cast<PHINode>(it)) {
10162       // Check that the PHI is a reduction PHI.
10163       if (P->getNumIncomingValues() == 2) {
10164         // Try to match and vectorize a horizontal reduction.
10165         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10166                                      TTI)) {
10167           Changed = true;
10168           it = BB->begin();
10169           e = BB->end();
10170           continue;
10171         }
10172       }
10173       // Try to vectorize the incoming values of the PHI, to catch reductions
10174       // that feed into PHIs.
10175       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10176         // Skip if the incoming block is the current BB for now. Also, bypass
10177         // unreachable IR for efficiency and to avoid crashing.
10178         // TODO: Collect the skipped incoming values and try to vectorize them
10179         // after processing BB.
10180         if (BB == P->getIncomingBlock(I) ||
10181             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10182           continue;
10183 
10184         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10185                                             P->getIncomingBlock(I), R, TTI);
10186       }
10187       continue;
10188     }
10189 
10190     // Ran into an instruction without users, like terminator, or function call
10191     // with ignored return value, store. Ignore unused instructions (basing on
10192     // instruction type, except for CallInst and InvokeInst).
10193     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10194                             isa<InvokeInst>(it))) {
10195       KeyNodes.insert(&*it);
10196       bool OpsChanged = false;
10197       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10198         for (auto *V : it->operand_values()) {
10199           // Try to match and vectorize a horizontal reduction.
10200           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10201         }
10202       }
10203       // Start vectorization of post-process list of instructions from the
10204       // top-tree instructions to try to vectorize as many instructions as
10205       // possible.
10206       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10207                                                 it->isTerminator());
10208       if (OpsChanged) {
10209         // We would like to start over since some instructions are deleted
10210         // and the iterator may become invalid value.
10211         Changed = true;
10212         it = BB->begin();
10213         e = BB->end();
10214         continue;
10215       }
10216     }
10217 
10218     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10219         isa<InsertValueInst>(it))
10220       PostProcessInstructions.push_back(&*it);
10221   }
10222 
10223   return Changed;
10224 }
10225 
10226 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10227   auto Changed = false;
10228   for (auto &Entry : GEPs) {
10229     // If the getelementptr list has fewer than two elements, there's nothing
10230     // to do.
10231     if (Entry.second.size() < 2)
10232       continue;
10233 
10234     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10235                       << Entry.second.size() << ".\n");
10236 
10237     // Process the GEP list in chunks suitable for the target's supported
10238     // vector size. If a vector register can't hold 1 element, we are done. We
10239     // are trying to vectorize the index computations, so the maximum number of
10240     // elements is based on the size of the index expression, rather than the
10241     // size of the GEP itself (the target's pointer size).
10242     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10243     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10244     if (MaxVecRegSize < EltSize)
10245       continue;
10246 
10247     unsigned MaxElts = MaxVecRegSize / EltSize;
10248     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10249       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10250       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10251 
10252       // Initialize a set a candidate getelementptrs. Note that we use a
10253       // SetVector here to preserve program order. If the index computations
10254       // are vectorizable and begin with loads, we want to minimize the chance
10255       // of having to reorder them later.
10256       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10257 
10258       // Some of the candidates may have already been vectorized after we
10259       // initially collected them. If so, they are marked as deleted, so remove
10260       // them from the set of candidates.
10261       Candidates.remove_if(
10262           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10263 
10264       // Remove from the set of candidates all pairs of getelementptrs with
10265       // constant differences. Such getelementptrs are likely not good
10266       // candidates for vectorization in a bottom-up phase since one can be
10267       // computed from the other. We also ensure all candidate getelementptr
10268       // indices are unique.
10269       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10270         auto *GEPI = GEPList[I];
10271         if (!Candidates.count(GEPI))
10272           continue;
10273         auto *SCEVI = SE->getSCEV(GEPList[I]);
10274         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10275           auto *GEPJ = GEPList[J];
10276           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10277           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10278             Candidates.remove(GEPI);
10279             Candidates.remove(GEPJ);
10280           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10281             Candidates.remove(GEPJ);
10282           }
10283         }
10284       }
10285 
10286       // We break out of the above computation as soon as we know there are
10287       // fewer than two candidates remaining.
10288       if (Candidates.size() < 2)
10289         continue;
10290 
10291       // Add the single, non-constant index of each candidate to the bundle. We
10292       // ensured the indices met these constraints when we originally collected
10293       // the getelementptrs.
10294       SmallVector<Value *, 16> Bundle(Candidates.size());
10295       auto BundleIndex = 0u;
10296       for (auto *V : Candidates) {
10297         auto *GEP = cast<GetElementPtrInst>(V);
10298         auto *GEPIdx = GEP->idx_begin()->get();
10299         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10300         Bundle[BundleIndex++] = GEPIdx;
10301       }
10302 
10303       // Try and vectorize the indices. We are currently only interested in
10304       // gather-like cases of the form:
10305       //
10306       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10307       //
10308       // where the loads of "a", the loads of "b", and the subtractions can be
10309       // performed in parallel. It's likely that detecting this pattern in a
10310       // bottom-up phase will be simpler and less costly than building a
10311       // full-blown top-down phase beginning at the consecutive loads.
10312       Changed |= tryToVectorizeList(Bundle, R);
10313     }
10314   }
10315   return Changed;
10316 }
10317 
10318 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10319   bool Changed = false;
10320   // Sort by type, base pointers and values operand. Value operands must be
10321   // compatible (have the same opcode, same parent), otherwise it is
10322   // definitely not profitable to try to vectorize them.
10323   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10324     if (V->getPointerOperandType()->getTypeID() <
10325         V2->getPointerOperandType()->getTypeID())
10326       return true;
10327     if (V->getPointerOperandType()->getTypeID() >
10328         V2->getPointerOperandType()->getTypeID())
10329       return false;
10330     // UndefValues are compatible with all other values.
10331     if (isa<UndefValue>(V->getValueOperand()) ||
10332         isa<UndefValue>(V2->getValueOperand()))
10333       return false;
10334     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10335       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10336         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10337             DT->getNode(I1->getParent());
10338         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10339             DT->getNode(I2->getParent());
10340         assert(NodeI1 && "Should only process reachable instructions");
10341         assert(NodeI1 && "Should only process reachable instructions");
10342         assert((NodeI1 == NodeI2) ==
10343                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10344                "Different nodes should have different DFS numbers");
10345         if (NodeI1 != NodeI2)
10346           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10347         InstructionsState S = getSameOpcode({I1, I2});
10348         if (S.getOpcode())
10349           return false;
10350         return I1->getOpcode() < I2->getOpcode();
10351       }
10352     if (isa<Constant>(V->getValueOperand()) &&
10353         isa<Constant>(V2->getValueOperand()))
10354       return false;
10355     return V->getValueOperand()->getValueID() <
10356            V2->getValueOperand()->getValueID();
10357   };
10358 
10359   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10360     if (V1 == V2)
10361       return true;
10362     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10363       return false;
10364     // Undefs are compatible with any other value.
10365     if (isa<UndefValue>(V1->getValueOperand()) ||
10366         isa<UndefValue>(V2->getValueOperand()))
10367       return true;
10368     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10369       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10370         if (I1->getParent() != I2->getParent())
10371           return false;
10372         InstructionsState S = getSameOpcode({I1, I2});
10373         return S.getOpcode() > 0;
10374       }
10375     if (isa<Constant>(V1->getValueOperand()) &&
10376         isa<Constant>(V2->getValueOperand()))
10377       return true;
10378     return V1->getValueOperand()->getValueID() ==
10379            V2->getValueOperand()->getValueID();
10380   };
10381   auto Limit = [&R, this](StoreInst *SI) {
10382     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10383     return R.getMinVF(EltSize);
10384   };
10385 
10386   // Attempt to sort and vectorize each of the store-groups.
10387   for (auto &Pair : Stores) {
10388     if (Pair.second.size() < 2)
10389       continue;
10390 
10391     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10392                       << Pair.second.size() << ".\n");
10393 
10394     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10395       continue;
10396 
10397     Changed |= tryToVectorizeSequence<StoreInst>(
10398         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10399         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10400           return vectorizeStores(Candidates, R);
10401         },
10402         /*LimitForRegisterSize=*/false);
10403   }
10404   return Changed;
10405 }
10406 
10407 char SLPVectorizer::ID = 0;
10408 
10409 static const char lv_name[] = "SLP Vectorizer";
10410 
10411 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10412 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10413 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10414 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10415 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10416 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10417 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10418 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10419 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10420 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10421 
10422 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10423