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/MemorySSA.h"
45 #include "llvm/Analysis/MemorySSAUpdater.h"
46 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
47 #include "llvm/Analysis/ScalarEvolution.h"
48 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
49 #include "llvm/Analysis/TargetLibraryInfo.h"
50 #include "llvm/Analysis/TargetTransformInfo.h"
51 #include "llvm/Analysis/ValueTracking.h"
52 #include "llvm/Analysis/VectorUtils.h"
53 #include "llvm/IR/Attributes.h"
54 #include "llvm/IR/BasicBlock.h"
55 #include "llvm/IR/Constant.h"
56 #include "llvm/IR/Constants.h"
57 #include "llvm/IR/DataLayout.h"
58 #include "llvm/IR/DebugLoc.h"
59 #include "llvm/IR/DerivedTypes.h"
60 #include "llvm/IR/Dominators.h"
61 #include "llvm/IR/Function.h"
62 #include "llvm/IR/IRBuilder.h"
63 #include "llvm/IR/InstrTypes.h"
64 #include "llvm/IR/Instruction.h"
65 #include "llvm/IR/Instructions.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/Intrinsics.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/Operator.h"
70 #include "llvm/IR/PatternMatch.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/User.h"
74 #include "llvm/IR/Value.h"
75 #include "llvm/IR/ValueHandle.h"
76 #include "llvm/IR/Verifier.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 static cl::opt<bool> EnableMSSAInSLPVectorizer(
172     "enable-mssa-in-slp-vectorizer", cl::Hidden, cl::init(false),
173     cl::desc("Enable MemorySSA for SLPVectorizer in new pass manager"));
174 
175 // Limit the number of alias checks. The limit is chosen so that
176 // it has no negative effect on the llvm benchmarks.
177 static const unsigned AliasedCheckLimit = 10;
178 
179 // Another limit for the alias checks: The maximum distance between load/store
180 // instructions where alias checks are done.
181 // This limit is useful for very large basic blocks.
182 static const unsigned MaxMemDepDistance = 160;
183 
184 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
185 /// regions to be handled.
186 static const int MinScheduleRegionSize = 16;
187 
188 /// Predicate for the element types that the SLP vectorizer supports.
189 ///
190 /// The most important thing to filter here are types which are invalid in LLVM
191 /// vectors. We also filter target specific types which have absolutely no
192 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
193 /// avoids spending time checking the cost model and realizing that they will
194 /// be inevitably scalarized.
195 static bool isValidElementType(Type *Ty) {
196   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
197          !Ty->isPPC_FP128Ty();
198 }
199 
200 /// \returns True if the value is a constant (but not globals/constant
201 /// expressions).
202 static bool isConstant(Value *V) {
203   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
204 }
205 
206 /// Checks if \p V is one of vector-like instructions, i.e. undef,
207 /// insertelement/extractelement with constant indices for fixed vector type or
208 /// extractvalue instruction.
209 static bool isVectorLikeInstWithConstOps(Value *V) {
210   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
211       !isa<ExtractValueInst, UndefValue>(V))
212     return false;
213   auto *I = dyn_cast<Instruction>(V);
214   if (!I || isa<ExtractValueInst>(I))
215     return true;
216   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
217     return false;
218   if (isa<ExtractElementInst>(I))
219     return isConstant(I->getOperand(1));
220   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
221   return isConstant(I->getOperand(2));
222 }
223 
224 /// \returns true if all of the instructions in \p VL are in the same block or
225 /// false otherwise.
226 static bool allSameBlock(ArrayRef<Value *> VL) {
227   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
228   if (!I0)
229     return false;
230   if (all_of(VL, isVectorLikeInstWithConstOps))
231     return true;
232 
233   BasicBlock *BB = I0->getParent();
234   for (int I = 1, E = VL.size(); I < E; I++) {
235     auto *II = dyn_cast<Instruction>(VL[I]);
236     if (!II)
237       return false;
238 
239     if (BB != II->getParent())
240       return false;
241   }
242   return true;
243 }
244 
245 /// \returns True if all of the values in \p VL are constants (but not
246 /// globals/constant expressions).
247 static bool allConstant(ArrayRef<Value *> VL) {
248   // Constant expressions and globals can't be vectorized like normal integer/FP
249   // constants.
250   return all_of(VL, isConstant);
251 }
252 
253 /// \returns True if all of the values in \p VL are identical or some of them
254 /// are UndefValue.
255 static bool isSplat(ArrayRef<Value *> VL) {
256   Value *FirstNonUndef = nullptr;
257   for (Value *V : VL) {
258     if (isa<UndefValue>(V))
259       continue;
260     if (!FirstNonUndef) {
261       FirstNonUndef = V;
262       continue;
263     }
264     if (V != FirstNonUndef)
265       return false;
266   }
267   return FirstNonUndef != nullptr;
268 }
269 
270 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
271 static bool isCommutative(Instruction *I) {
272   if (auto *Cmp = dyn_cast<CmpInst>(I))
273     return Cmp->isCommutative();
274   if (auto *BO = dyn_cast<BinaryOperator>(I))
275     return BO->isCommutative();
276   // TODO: This should check for generic Instruction::isCommutative(), but
277   //       we need to confirm that the caller code correctly handles Intrinsics
278   //       for example (does not have 2 operands).
279   return false;
280 }
281 
282 /// Checks if the given value is actually an undefined constant vector.
283 static bool isUndefVector(const Value *V) {
284   if (isa<UndefValue>(V))
285     return true;
286   auto *C = dyn_cast<Constant>(V);
287   if (!C)
288     return false;
289   if (!C->containsUndefOrPoisonElement())
290     return false;
291   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
292   if (!VecTy)
293     return false;
294   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
295     if (Constant *Elem = C->getAggregateElement(I))
296       if (!isa<UndefValue>(Elem))
297         return false;
298   }
299   return true;
300 }
301 
302 /// Checks if the vector of instructions can be represented as a shuffle, like:
303 /// %x0 = extractelement <4 x i8> %x, i32 0
304 /// %x3 = extractelement <4 x i8> %x, i32 3
305 /// %y1 = extractelement <4 x i8> %y, i32 1
306 /// %y2 = extractelement <4 x i8> %y, i32 2
307 /// %x0x0 = mul i8 %x0, %x0
308 /// %x3x3 = mul i8 %x3, %x3
309 /// %y1y1 = mul i8 %y1, %y1
310 /// %y2y2 = mul i8 %y2, %y2
311 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
312 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
313 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
314 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
315 /// ret <4 x i8> %ins4
316 /// can be transformed into:
317 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
318 ///                                                         i32 6>
319 /// %2 = mul <4 x i8> %1, %1
320 /// ret <4 x i8> %2
321 /// We convert this initially to something like:
322 /// %x0 = extractelement <4 x i8> %x, i32 0
323 /// %x3 = extractelement <4 x i8> %x, i32 3
324 /// %y1 = extractelement <4 x i8> %y, i32 1
325 /// %y2 = extractelement <4 x i8> %y, i32 2
326 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
327 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
328 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
329 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
330 /// %5 = mul <4 x i8> %4, %4
331 /// %6 = extractelement <4 x i8> %5, i32 0
332 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
333 /// %7 = extractelement <4 x i8> %5, i32 1
334 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
335 /// %8 = extractelement <4 x i8> %5, i32 2
336 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
337 /// %9 = extractelement <4 x i8> %5, i32 3
338 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
339 /// ret <4 x i8> %ins4
340 /// InstCombiner transforms this into a shuffle and vector mul
341 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
342 /// TODO: Can we split off and reuse the shuffle mask detection from
343 /// TargetTransformInfo::getInstructionThroughput?
344 static Optional<TargetTransformInfo::ShuffleKind>
345 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
346   const auto *It =
347       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
348   if (It == VL.end())
349     return None;
350   auto *EI0 = cast<ExtractElementInst>(*It);
351   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
352     return None;
353   unsigned Size =
354       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
355   Value *Vec1 = nullptr;
356   Value *Vec2 = nullptr;
357   enum ShuffleMode { Unknown, Select, Permute };
358   ShuffleMode CommonShuffleMode = Unknown;
359   Mask.assign(VL.size(), UndefMaskElem);
360   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
361     // Undef can be represented as an undef element in a vector.
362     if (isa<UndefValue>(VL[I]))
363       continue;
364     auto *EI = cast<ExtractElementInst>(VL[I]);
365     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
366       return None;
367     auto *Vec = EI->getVectorOperand();
368     // We can extractelement from undef or poison vector.
369     if (isUndefVector(Vec))
370       continue;
371     // All vector operands must have the same number of vector elements.
372     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
373       return None;
374     if (isa<UndefValue>(EI->getIndexOperand()))
375       continue;
376     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
377     if (!Idx)
378       return None;
379     // Undefined behavior if Idx is negative or >= Size.
380     if (Idx->getValue().uge(Size))
381       continue;
382     unsigned IntIdx = Idx->getValue().getZExtValue();
383     Mask[I] = IntIdx;
384     // For correct shuffling we have to have at most 2 different vector operands
385     // in all extractelement instructions.
386     if (!Vec1 || Vec1 == Vec) {
387       Vec1 = Vec;
388     } else if (!Vec2 || Vec2 == Vec) {
389       Vec2 = Vec;
390       Mask[I] += Size;
391     } else {
392       return None;
393     }
394     if (CommonShuffleMode == Permute)
395       continue;
396     // If the extract index is not the same as the operation number, it is a
397     // permutation.
398     if (IntIdx != I) {
399       CommonShuffleMode = Permute;
400       continue;
401     }
402     CommonShuffleMode = Select;
403   }
404   // If we're not crossing lanes in different vectors, consider it as blending.
405   if (CommonShuffleMode == Select && Vec2)
406     return TargetTransformInfo::SK_Select;
407   // If Vec2 was never used, we have a permutation of a single vector, otherwise
408   // we have permutation of 2 vectors.
409   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
410               : TargetTransformInfo::SK_PermuteSingleSrc;
411 }
412 
413 namespace {
414 
415 /// Main data required for vectorization of instructions.
416 struct InstructionsState {
417   /// The very first instruction in the list with the main opcode.
418   Value *OpValue = nullptr;
419 
420   /// The main/alternate instruction.
421   Instruction *MainOp = nullptr;
422   Instruction *AltOp = nullptr;
423 
424   /// The main/alternate opcodes for the list of instructions.
425   unsigned getOpcode() const {
426     return MainOp ? MainOp->getOpcode() : 0;
427   }
428 
429   unsigned getAltOpcode() const {
430     return AltOp ? AltOp->getOpcode() : 0;
431   }
432 
433   /// Some of the instructions in the list have alternate opcodes.
434   bool isAltShuffle() const { return AltOp != MainOp; }
435 
436   bool isOpcodeOrAlt(Instruction *I) const {
437     unsigned CheckedOpcode = I->getOpcode();
438     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
439   }
440 
441   InstructionsState() = delete;
442   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
443       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
444 };
445 
446 } // end anonymous namespace
447 
448 /// Chooses the correct key for scheduling data. If \p Op has the same (or
449 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
450 /// OpValue.
451 static Value *isOneOf(const InstructionsState &S, Value *Op) {
452   auto *I = dyn_cast<Instruction>(Op);
453   if (I && S.isOpcodeOrAlt(I))
454     return Op;
455   return S.OpValue;
456 }
457 
458 /// \returns true if \p Opcode is allowed as part of of the main/alternate
459 /// instruction for SLP vectorization.
460 ///
461 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
462 /// "shuffled out" lane would result in division by zero.
463 static bool isValidForAlternation(unsigned Opcode) {
464   if (Instruction::isIntDivRem(Opcode))
465     return false;
466 
467   return true;
468 }
469 
470 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
471                                        unsigned BaseIndex = 0);
472 
473 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
474 /// compatible instructions or constants, or just some other regular values.
475 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
476                                 Value *Op1) {
477   return (isConstant(BaseOp0) && isConstant(Op0)) ||
478          (isConstant(BaseOp1) && isConstant(Op1)) ||
479          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
480           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
481          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
482          getSameOpcode({BaseOp1, Op1}).getOpcode();
483 }
484 
485 /// \returns analysis of the Instructions in \p VL described in
486 /// InstructionsState, the Opcode that we suppose the whole list
487 /// could be vectorized even if its structure is diverse.
488 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
489                                        unsigned BaseIndex) {
490   // Make sure these are all Instructions.
491   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
492     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
493 
494   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
495   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
496   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
497   CmpInst::Predicate BasePred =
498       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
499               : CmpInst::BAD_ICMP_PREDICATE;
500   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
501   unsigned AltOpcode = Opcode;
502   unsigned AltIndex = BaseIndex;
503 
504   // Check for one alternate opcode from another BinaryOperator.
505   // TODO - generalize to support all operators (types, calls etc.).
506   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
507     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
508     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
509       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
510         continue;
511       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
512           isValidForAlternation(Opcode)) {
513         AltOpcode = InstOpcode;
514         AltIndex = Cnt;
515         continue;
516       }
517     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
518       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
519       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
520       if (Ty0 == Ty1) {
521         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
522           continue;
523         if (Opcode == AltOpcode) {
524           assert(isValidForAlternation(Opcode) &&
525                  isValidForAlternation(InstOpcode) &&
526                  "Cast isn't safe for alternation, logic needs to be updated!");
527           AltOpcode = InstOpcode;
528           AltIndex = Cnt;
529           continue;
530         }
531       }
532     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
533       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
534       auto *Inst = cast<Instruction>(VL[Cnt]);
535       Type *Ty0 = BaseInst->getOperand(0)->getType();
536       Type *Ty1 = Inst->getOperand(0)->getType();
537       if (Ty0 == Ty1) {
538         Value *BaseOp0 = BaseInst->getOperand(0);
539         Value *BaseOp1 = BaseInst->getOperand(1);
540         Value *Op0 = Inst->getOperand(0);
541         Value *Op1 = Inst->getOperand(1);
542         CmpInst::Predicate CurrentPred =
543             cast<CmpInst>(VL[Cnt])->getPredicate();
544         CmpInst::Predicate SwappedCurrentPred =
545             CmpInst::getSwappedPredicate(CurrentPred);
546         // Check for compatible operands. If the corresponding operands are not
547         // compatible - need to perform alternate vectorization.
548         if (InstOpcode == Opcode) {
549           if (BasePred == CurrentPred &&
550               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
551             continue;
552           if (BasePred == SwappedCurrentPred &&
553               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
554             continue;
555           if (E == 2 &&
556               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
557             continue;
558           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
559           CmpInst::Predicate AltPred = AltInst->getPredicate();
560           Value *AltOp0 = AltInst->getOperand(0);
561           Value *AltOp1 = AltInst->getOperand(1);
562           // Check if operands are compatible with alternate operands.
563           if (AltPred == CurrentPred &&
564               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
565             continue;
566           if (AltPred == SwappedCurrentPred &&
567               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
568             continue;
569         }
570         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
571           assert(isValidForAlternation(Opcode) &&
572                  isValidForAlternation(InstOpcode) &&
573                  "Cast isn't safe for alternation, logic needs to be updated!");
574           AltIndex = Cnt;
575           continue;
576         }
577         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
578         CmpInst::Predicate AltPred = AltInst->getPredicate();
579         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
580             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
581           continue;
582       }
583     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
584       continue;
585     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
586   }
587 
588   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
589                            cast<Instruction>(VL[AltIndex]));
590 }
591 
592 /// \returns true if all of the values in \p VL have the same type or false
593 /// otherwise.
594 static bool allSameType(ArrayRef<Value *> VL) {
595   Type *Ty = VL[0]->getType();
596   for (int i = 1, e = VL.size(); i < e; i++)
597     if (VL[i]->getType() != Ty)
598       return false;
599 
600   return true;
601 }
602 
603 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
604 static Optional<unsigned> getExtractIndex(Instruction *E) {
605   unsigned Opcode = E->getOpcode();
606   assert((Opcode == Instruction::ExtractElement ||
607           Opcode == Instruction::ExtractValue) &&
608          "Expected extractelement or extractvalue instruction.");
609   if (Opcode == Instruction::ExtractElement) {
610     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
611     if (!CI)
612       return None;
613     return CI->getZExtValue();
614   }
615   ExtractValueInst *EI = cast<ExtractValueInst>(E);
616   if (EI->getNumIndices() != 1)
617     return None;
618   return *EI->idx_begin();
619 }
620 
621 /// \returns True if in-tree use also needs extract. This refers to
622 /// possible scalar operand in vectorized instruction.
623 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
624                                     TargetLibraryInfo *TLI) {
625   unsigned Opcode = UserInst->getOpcode();
626   switch (Opcode) {
627   case Instruction::Load: {
628     LoadInst *LI = cast<LoadInst>(UserInst);
629     return (LI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Store: {
632     StoreInst *SI = cast<StoreInst>(UserInst);
633     return (SI->getPointerOperand() == Scalar);
634   }
635   case Instruction::Call: {
636     CallInst *CI = cast<CallInst>(UserInst);
637     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
638     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
639       if (hasVectorInstrinsicScalarOpd(ID, i))
640         return (CI->getArgOperand(i) == Scalar);
641     }
642     LLVM_FALLTHROUGH;
643   }
644   default:
645     return false;
646   }
647 }
648 
649 /// \returns the AA location that is being access by the instruction.
650 static MemoryLocation getLocation(Instruction *I) {
651   if (StoreInst *SI = dyn_cast<StoreInst>(I))
652     return MemoryLocation::get(SI);
653   if (LoadInst *LI = dyn_cast<LoadInst>(I))
654     return MemoryLocation::get(LI);
655   return MemoryLocation();
656 }
657 
658 /// \returns True if the instruction is not a volatile or atomic load/store.
659 static bool isSimple(Instruction *I) {
660   if (LoadInst *LI = dyn_cast<LoadInst>(I))
661     return LI->isSimple();
662   if (StoreInst *SI = dyn_cast<StoreInst>(I))
663     return SI->isSimple();
664   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
665     return !MI->isVolatile();
666   return true;
667 }
668 
669 /// Shuffles \p Mask in accordance with the given \p SubMask.
670 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
671   if (SubMask.empty())
672     return;
673   if (Mask.empty()) {
674     Mask.append(SubMask.begin(), SubMask.end());
675     return;
676   }
677   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
678   int TermValue = std::min(Mask.size(), SubMask.size());
679   for (int I = 0, E = SubMask.size(); I < E; ++I) {
680     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
681         Mask[SubMask[I]] >= TermValue)
682       continue;
683     NewMask[I] = Mask[SubMask[I]];
684   }
685   Mask.swap(NewMask);
686 }
687 
688 /// Order may have elements assigned special value (size) which is out of
689 /// bounds. Such indices only appear on places which correspond to undef values
690 /// (see canReuseExtract for details) and used in order to avoid undef values
691 /// have effect on operands ordering.
692 /// The first loop below simply finds all unused indices and then the next loop
693 /// nest assigns these indices for undef values positions.
694 /// As an example below Order has two undef positions and they have assigned
695 /// values 3 and 7 respectively:
696 /// before:  6 9 5 4 9 2 1 0
697 /// after:   6 3 5 4 7 2 1 0
698 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
699   const unsigned Sz = Order.size();
700   SmallBitVector UnusedIndices(Sz, /*t=*/true);
701   SmallBitVector MaskedIndices(Sz);
702   for (unsigned I = 0; I < Sz; ++I) {
703     if (Order[I] < Sz)
704       UnusedIndices.reset(Order[I]);
705     else
706       MaskedIndices.set(I);
707   }
708   if (MaskedIndices.none())
709     return;
710   assert(UnusedIndices.count() == MaskedIndices.count() &&
711          "Non-synced masked/available indices.");
712   int Idx = UnusedIndices.find_first();
713   int MIdx = MaskedIndices.find_first();
714   while (MIdx >= 0) {
715     assert(Idx >= 0 && "Indices must be synced.");
716     Order[MIdx] = Idx;
717     Idx = UnusedIndices.find_next(Idx);
718     MIdx = MaskedIndices.find_next(MIdx);
719   }
720 }
721 
722 namespace llvm {
723 
724 static void inversePermutation(ArrayRef<unsigned> Indices,
725                                SmallVectorImpl<int> &Mask) {
726   Mask.clear();
727   const unsigned E = Indices.size();
728   Mask.resize(E, UndefMaskElem);
729   for (unsigned I = 0; I < E; ++I)
730     Mask[Indices[I]] = I;
731 }
732 
733 /// \returns inserting index of InsertElement or InsertValue instruction,
734 /// using Offset as base offset for index.
735 static Optional<unsigned> getInsertIndex(Value *InsertInst,
736                                          unsigned Offset = 0) {
737   int Index = Offset;
738   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
739     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
740       auto *VT = cast<FixedVectorType>(IE->getType());
741       if (CI->getValue().uge(VT->getNumElements()))
742         return None;
743       Index *= VT->getNumElements();
744       Index += CI->getZExtValue();
745       return Index;
746     }
747     return None;
748   }
749 
750   auto *IV = cast<InsertValueInst>(InsertInst);
751   Type *CurrentType = IV->getType();
752   for (unsigned I : IV->indices()) {
753     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
754       Index *= ST->getNumElements();
755       CurrentType = ST->getElementType(I);
756     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
757       Index *= AT->getNumElements();
758       CurrentType = AT->getElementType();
759     } else {
760       return None;
761     }
762     Index += I;
763   }
764   return Index;
765 }
766 
767 /// Reorders the list of scalars in accordance with the given \p Mask.
768 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
769                            ArrayRef<int> Mask) {
770   assert(!Mask.empty() && "Expected non-empty mask.");
771   SmallVector<Value *> Prev(Scalars.size(),
772                             UndefValue::get(Scalars.front()->getType()));
773   Prev.swap(Scalars);
774   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
775     if (Mask[I] != UndefMaskElem)
776       Scalars[Mask[I]] = Prev[I];
777 }
778 
779 namespace slpvectorizer {
780 
781 /// Bottom Up SLP Vectorizer.
782 class BoUpSLP {
783   struct TreeEntry;
784   struct ScheduleData;
785 
786 public:
787   using ValueList = SmallVector<Value *, 8>;
788   using InstrList = SmallVector<Instruction *, 16>;
789   using ValueSet = SmallPtrSet<Value *, 16>;
790   using StoreList = SmallVector<StoreInst *, 8>;
791   using ExtraValueToDebugLocsMap =
792       MapVector<Value *, SmallVector<Instruction *, 2>>;
793   using OrdersType = SmallVector<unsigned, 4>;
794 
795   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
796           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
797           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
798           MemorySSA *MSSA, const DataLayout *DL, OptimizationRemarkEmitter *ORE)
799       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
800         DT(Dt), AC(AC), DB(DB), MSSA(MSSA), DL(DL), ORE(ORE),
801         Builder(Se->getContext()) {
802     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
803     // Use the vector register size specified by the target unless overridden
804     // by a command-line option.
805     // TODO: It would be better to limit the vectorization factor based on
806     //       data type rather than just register size. For example, x86 AVX has
807     //       256-bit registers, but it does not support integer operations
808     //       at that width (that requires AVX2).
809     if (MaxVectorRegSizeOption.getNumOccurrences())
810       MaxVecRegSize = MaxVectorRegSizeOption;
811     else
812       MaxVecRegSize =
813           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
814               .getFixedSize();
815 
816     if (MinVectorRegSizeOption.getNumOccurrences())
817       MinVecRegSize = MinVectorRegSizeOption;
818     else
819       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
820   }
821 
822   /// Vectorize the tree that starts with the elements in \p VL.
823   /// Returns the vectorized root.
824   Value *vectorizeTree();
825 
826   /// Vectorize the tree but with the list of externally used values \p
827   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
828   /// generated extractvalue instructions.
829   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
830 
831   /// \returns the cost incurred by unwanted spills and fills, caused by
832   /// holding live values over call sites.
833   InstructionCost getSpillCost() const;
834 
835   /// \returns the vectorization cost of the subtree that starts at \p VL.
836   /// A negative number means that this is profitable.
837   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
838 
839   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
840   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
841   void buildTree(ArrayRef<Value *> Roots,
842                  ArrayRef<Value *> UserIgnoreLst = None);
843 
844   /// Builds external uses of the vectorized scalars, i.e. the list of
845   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
846   /// ExternallyUsedValues contains additional list of external uses to handle
847   /// vectorization of reductions.
848   void
849   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
850 
851   /// Clear the internal data structures that are created by 'buildTree'.
852   void deleteTree() {
853     VectorizableTree.clear();
854     ScalarToTreeEntry.clear();
855     MustGather.clear();
856     ExternalUses.clear();
857     for (auto &Iter : BlocksSchedules) {
858       BlockScheduling *BS = Iter.second.get();
859       BS->clear();
860     }
861     MinBWs.clear();
862     InstrElementSize.clear();
863   }
864 
865   unsigned getTreeSize() const { return VectorizableTree.size(); }
866 
867   /// Perform LICM and CSE on the newly generated gather sequences.
868   void optimizeGatherSequence();
869 
870   /// Checks if the specified gather tree entry \p TE can be represented as a
871   /// shuffled vector entry + (possibly) permutation with other gathers. It
872   /// implements the checks only for possibly ordered scalars (Loads,
873   /// ExtractElement, ExtractValue), which can be part of the graph.
874   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
875 
876   /// Gets reordering data for the given tree entry. If the entry is vectorized
877   /// - just return ReorderIndices, otherwise check if the scalars can be
878   /// reordered and return the most optimal order.
879   /// \param TopToBottom If true, include the order of vectorized stores and
880   /// insertelement nodes, otherwise skip them.
881   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
882 
883   /// Reorders the current graph to the most profitable order starting from the
884   /// root node to the leaf nodes. The best order is chosen only from the nodes
885   /// of the same size (vectorization factor). Smaller nodes are considered
886   /// parts of subgraph with smaller VF and they are reordered independently. We
887   /// can make it because we still need to extend smaller nodes to the wider VF
888   /// and we can merge reordering shuffles with the widening shuffles.
889   void reorderTopToBottom();
890 
891   /// Reorders the current graph to the most profitable order starting from
892   /// leaves to the root. It allows to rotate small subgraphs and reduce the
893   /// number of reshuffles if the leaf nodes use the same order. In this case we
894   /// can merge the orders and just shuffle user node instead of shuffling its
895   /// operands. Plus, even the leaf nodes have different orders, it allows to
896   /// sink reordering in the graph closer to the root node and merge it later
897   /// during analysis.
898   void reorderBottomToTop(bool IgnoreReorder = false);
899 
900   /// \return The vector element size in bits to use when vectorizing the
901   /// expression tree ending at \p V. If V is a store, the size is the width of
902   /// the stored value. Otherwise, the size is the width of the largest loaded
903   /// value reaching V. This method is used by the vectorizer to calculate
904   /// vectorization factors.
905   unsigned getVectorElementSize(Value *V);
906 
907   /// Compute the minimum type sizes required to represent the entries in a
908   /// vectorizable tree.
909   void computeMinimumValueSizes();
910 
911   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
912   unsigned getMaxVecRegSize() const {
913     return MaxVecRegSize;
914   }
915 
916   // \returns minimum vector register size as set by cl::opt.
917   unsigned getMinVecRegSize() const {
918     return MinVecRegSize;
919   }
920 
921   unsigned getMinVF(unsigned Sz) const {
922     return std::max(2U, getMinVecRegSize() / Sz);
923   }
924 
925   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
926     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
927       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
928     return MaxVF ? MaxVF : UINT_MAX;
929   }
930 
931   /// Check if homogeneous aggregate is isomorphic to some VectorType.
932   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
933   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
934   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
935   ///
936   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
937   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
938 
939   /// \returns True if the VectorizableTree is both tiny and not fully
940   /// vectorizable. We do not vectorize such trees.
941   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
942 
943   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
944   /// can be load combined in the backend. Load combining may not be allowed in
945   /// the IR optimizer, so we do not want to alter the pattern. For example,
946   /// partially transforming a scalar bswap() pattern into vector code is
947   /// effectively impossible for the backend to undo.
948   /// TODO: If load combining is allowed in the IR optimizer, this analysis
949   ///       may not be necessary.
950   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
951 
952   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
953   /// can be load combined in the backend. Load combining may not be allowed in
954   /// the IR optimizer, so we do not want to alter the pattern. For example,
955   /// partially transforming a scalar bswap() pattern into vector code is
956   /// effectively impossible for the backend to undo.
957   /// TODO: If load combining is allowed in the IR optimizer, this analysis
958   ///       may not be necessary.
959   bool isLoadCombineCandidate() const;
960 
961   OptimizationRemarkEmitter *getORE() { return ORE; }
962 
963   /// This structure holds any data we need about the edges being traversed
964   /// during buildTree_rec(). We keep track of:
965   /// (i) the user TreeEntry index, and
966   /// (ii) the index of the edge.
967   struct EdgeInfo {
968     EdgeInfo() = default;
969     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
970         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
971     /// The user TreeEntry.
972     TreeEntry *UserTE = nullptr;
973     /// The operand index of the use.
974     unsigned EdgeIdx = UINT_MAX;
975 #ifndef NDEBUG
976     friend inline raw_ostream &operator<<(raw_ostream &OS,
977                                           const BoUpSLP::EdgeInfo &EI) {
978       EI.dump(OS);
979       return OS;
980     }
981     /// Debug print.
982     void dump(raw_ostream &OS) const {
983       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
984          << " EdgeIdx:" << EdgeIdx << "}";
985     }
986     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
987 #endif
988   };
989 
990   /// A helper data structure to hold the operands of a vector of instructions.
991   /// This supports a fixed vector length for all operand vectors.
992   class VLOperands {
993     /// For each operand we need (i) the value, and (ii) the opcode that it
994     /// would be attached to if the expression was in a left-linearized form.
995     /// This is required to avoid illegal operand reordering.
996     /// For example:
997     /// \verbatim
998     ///                         0 Op1
999     ///                         |/
1000     /// Op1 Op2   Linearized    + Op2
1001     ///   \ /     ---------->   |/
1002     ///    -                    -
1003     ///
1004     /// Op1 - Op2            (0 + Op1) - Op2
1005     /// \endverbatim
1006     ///
1007     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1008     ///
1009     /// Another way to think of this is to track all the operations across the
1010     /// path from the operand all the way to the root of the tree and to
1011     /// calculate the operation that corresponds to this path. For example, the
1012     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1013     /// corresponding operation is a '-' (which matches the one in the
1014     /// linearized tree, as shown above).
1015     ///
1016     /// For lack of a better term, we refer to this operation as Accumulated
1017     /// Path Operation (APO).
1018     struct OperandData {
1019       OperandData() = default;
1020       OperandData(Value *V, bool APO, bool IsUsed)
1021           : V(V), APO(APO), IsUsed(IsUsed) {}
1022       /// The operand value.
1023       Value *V = nullptr;
1024       /// TreeEntries only allow a single opcode, or an alternate sequence of
1025       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1026       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1027       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1028       /// (e.g., Add/Mul)
1029       bool APO = false;
1030       /// Helper data for the reordering function.
1031       bool IsUsed = false;
1032     };
1033 
1034     /// During operand reordering, we are trying to select the operand at lane
1035     /// that matches best with the operand at the neighboring lane. Our
1036     /// selection is based on the type of value we are looking for. For example,
1037     /// if the neighboring lane has a load, we need to look for a load that is
1038     /// accessing a consecutive address. These strategies are summarized in the
1039     /// 'ReorderingMode' enumerator.
1040     enum class ReorderingMode {
1041       Load,     ///< Matching loads to consecutive memory addresses
1042       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1043       Constant, ///< Matching constants
1044       Splat,    ///< Matching the same instruction multiple times (broadcast)
1045       Failed,   ///< We failed to create a vectorizable group
1046     };
1047 
1048     using OperandDataVec = SmallVector<OperandData, 2>;
1049 
1050     /// A vector of operand vectors.
1051     SmallVector<OperandDataVec, 4> OpsVec;
1052 
1053     const DataLayout &DL;
1054     ScalarEvolution &SE;
1055     const BoUpSLP &R;
1056 
1057     /// \returns the operand data at \p OpIdx and \p Lane.
1058     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1059       return OpsVec[OpIdx][Lane];
1060     }
1061 
1062     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1063     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1064       return OpsVec[OpIdx][Lane];
1065     }
1066 
1067     /// Clears the used flag for all entries.
1068     void clearUsed() {
1069       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1070            OpIdx != NumOperands; ++OpIdx)
1071         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1072              ++Lane)
1073           OpsVec[OpIdx][Lane].IsUsed = false;
1074     }
1075 
1076     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1077     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1078       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1079     }
1080 
1081     // The hard-coded scores listed here are not very important, though it shall
1082     // be higher for better matches to improve the resulting cost. When
1083     // computing the scores of matching one sub-tree with another, we are
1084     // basically counting the number of values that are matching. So even if all
1085     // scores are set to 1, we would still get a decent matching result.
1086     // However, sometimes we have to break ties. For example we may have to
1087     // choose between matching loads vs matching opcodes. This is what these
1088     // scores are helping us with: they provide the order of preference. Also,
1089     // this is important if the scalar is externally used or used in another
1090     // tree entry node in the different lane.
1091 
1092     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1093     static const int ScoreConsecutiveLoads = 4;
1094     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1095     static const int ScoreReversedLoads = 3;
1096     /// ExtractElementInst from same vector and consecutive indexes.
1097     static const int ScoreConsecutiveExtracts = 4;
1098     /// ExtractElementInst from same vector and reversed indices.
1099     static const int ScoreReversedExtracts = 3;
1100     /// Constants.
1101     static const int ScoreConstants = 2;
1102     /// Instructions with the same opcode.
1103     static const int ScoreSameOpcode = 2;
1104     /// Instructions with alt opcodes (e.g, add + sub).
1105     static const int ScoreAltOpcodes = 1;
1106     /// Identical instructions (a.k.a. splat or broadcast).
1107     static const int ScoreSplat = 1;
1108     /// Matching with an undef is preferable to failing.
1109     static const int ScoreUndef = 1;
1110     /// Score for failing to find a decent match.
1111     static const int ScoreFail = 0;
1112     /// Score if all users are vectorized.
1113     static const int ScoreAllUserVectorized = 1;
1114 
1115     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1116     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1117     /// MainAltOps.
1118     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1119                                ScalarEvolution &SE, int NumLanes,
1120                                ArrayRef<Value *> MainAltOps) {
1121       if (V1 == V2)
1122         return VLOperands::ScoreSplat;
1123 
1124       auto *LI1 = dyn_cast<LoadInst>(V1);
1125       auto *LI2 = dyn_cast<LoadInst>(V2);
1126       if (LI1 && LI2) {
1127         if (LI1->getParent() != LI2->getParent())
1128           return VLOperands::ScoreFail;
1129 
1130         Optional<int> Dist = getPointersDiff(
1131             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1132             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1133         if (!Dist || *Dist == 0)
1134           return VLOperands::ScoreFail;
1135         // The distance is too large - still may be profitable to use masked
1136         // loads/gathers.
1137         if (std::abs(*Dist) > NumLanes / 2)
1138           return VLOperands::ScoreAltOpcodes;
1139         // This still will detect consecutive loads, but we might have "holes"
1140         // in some cases. It is ok for non-power-2 vectorization and may produce
1141         // better results. It should not affect current vectorization.
1142         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1143                            : VLOperands::ScoreReversedLoads;
1144       }
1145 
1146       auto *C1 = dyn_cast<Constant>(V1);
1147       auto *C2 = dyn_cast<Constant>(V2);
1148       if (C1 && C2)
1149         return VLOperands::ScoreConstants;
1150 
1151       // Extracts from consecutive indexes of the same vector better score as
1152       // the extracts could be optimized away.
1153       Value *EV1;
1154       ConstantInt *Ex1Idx;
1155       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1156         // Undefs are always profitable for extractelements.
1157         if (isa<UndefValue>(V2))
1158           return VLOperands::ScoreConsecutiveExtracts;
1159         Value *EV2 = nullptr;
1160         ConstantInt *Ex2Idx = nullptr;
1161         if (match(V2,
1162                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1163                                                          m_Undef())))) {
1164           // Undefs are always profitable for extractelements.
1165           if (!Ex2Idx)
1166             return VLOperands::ScoreConsecutiveExtracts;
1167           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1168             return VLOperands::ScoreConsecutiveExtracts;
1169           if (EV2 == EV1) {
1170             int Idx1 = Ex1Idx->getZExtValue();
1171             int Idx2 = Ex2Idx->getZExtValue();
1172             int Dist = Idx2 - Idx1;
1173             // The distance is too large - still may be profitable to use
1174             // shuffles.
1175             if (std::abs(Dist) == 0)
1176               return VLOperands::ScoreSplat;
1177             if (std::abs(Dist) > NumLanes / 2)
1178               return VLOperands::ScoreSameOpcode;
1179             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1180                               : VLOperands::ScoreReversedExtracts;
1181           }
1182           return VLOperands::ScoreAltOpcodes;
1183         }
1184         return VLOperands::ScoreFail;
1185       }
1186 
1187       auto *I1 = dyn_cast<Instruction>(V1);
1188       auto *I2 = dyn_cast<Instruction>(V2);
1189       if (I1 && I2) {
1190         if (I1->getParent() != I2->getParent())
1191           return VLOperands::ScoreFail;
1192         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1193         Ops.push_back(I1);
1194         Ops.push_back(I2);
1195         InstructionsState S = getSameOpcode(Ops);
1196         // Note: Only consider instructions with <= 2 operands to avoid
1197         // complexity explosion.
1198         if (S.getOpcode() &&
1199             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1200              !S.isAltShuffle()) &&
1201             all_of(Ops, [&S](Value *V) {
1202               return cast<Instruction>(V)->getNumOperands() ==
1203                      S.MainOp->getNumOperands();
1204             }))
1205           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1206                                   : VLOperands::ScoreSameOpcode;
1207       }
1208 
1209       if (isa<UndefValue>(V2))
1210         return VLOperands::ScoreUndef;
1211 
1212       return VLOperands::ScoreFail;
1213     }
1214 
1215     /// \param Lane lane of the operands under analysis.
1216     /// \param OpIdx operand index in \p Lane lane we're looking the best
1217     /// candidate for.
1218     /// \param Idx operand index of the current candidate value.
1219     /// \returns The additional score due to possible broadcasting of the
1220     /// elements in the lane. It is more profitable to have power-of-2 unique
1221     /// elements in the lane, it will be vectorized with higher probability
1222     /// after removing duplicates. Currently the SLP vectorizer supports only
1223     /// vectorization of the power-of-2 number of unique scalars.
1224     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1225       Value *IdxLaneV = getData(Idx, Lane).V;
1226       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1227         return 0;
1228       SmallPtrSet<Value *, 4> Uniques;
1229       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1230         if (Ln == Lane)
1231           continue;
1232         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1233         if (!isa<Instruction>(OpIdxLnV))
1234           return 0;
1235         Uniques.insert(OpIdxLnV);
1236       }
1237       int UniquesCount = Uniques.size();
1238       int UniquesCntWithIdxLaneV =
1239           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1240       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1241       int UniquesCntWithOpIdxLaneV =
1242           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1243       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1244         return 0;
1245       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1246               UniquesCntWithOpIdxLaneV) -
1247              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1248     }
1249 
1250     /// \param Lane lane of the operands under analysis.
1251     /// \param OpIdx operand index in \p Lane lane we're looking the best
1252     /// candidate for.
1253     /// \param Idx operand index of the current candidate value.
1254     /// \returns The additional score for the scalar which users are all
1255     /// vectorized.
1256     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1257       Value *IdxLaneV = getData(Idx, Lane).V;
1258       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1259       // Do not care about number of uses for vector-like instructions
1260       // (extractelement/extractvalue with constant indices), they are extracts
1261       // themselves and already externally used. Vectorization of such
1262       // instructions does not add extra extractelement instruction, just may
1263       // remove it.
1264       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1265           isVectorLikeInstWithConstOps(OpIdxLaneV))
1266         return VLOperands::ScoreAllUserVectorized;
1267       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1268       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1269         return 0;
1270       return R.areAllUsersVectorized(IdxLaneI, None)
1271                  ? VLOperands::ScoreAllUserVectorized
1272                  : 0;
1273     }
1274 
1275     /// Go through the operands of \p LHS and \p RHS recursively until \p
1276     /// MaxLevel, and return the cummulative score. For example:
1277     /// \verbatim
1278     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1279     ///     \ /         \ /         \ /        \ /
1280     ///      +           +           +          +
1281     ///     G1          G2          G3         G4
1282     /// \endverbatim
1283     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1284     /// each level recursively, accumulating the score. It starts from matching
1285     /// the additions at level 0, then moves on to the loads (level 1). The
1286     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1287     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1288     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1289     /// Please note that the order of the operands does not matter, as we
1290     /// evaluate the score of all profitable combinations of operands. In
1291     /// other words the score of G1 and G4 is the same as G1 and G2. This
1292     /// heuristic is based on ideas described in:
1293     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1294     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1295     ///   Luís F. W. Góes
1296     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1297                            ArrayRef<Value *> MainAltOps) {
1298 
1299       // Get the shallow score of V1 and V2.
1300       int ShallowScoreAtThisLevel =
1301           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1302 
1303       // If reached MaxLevel,
1304       //  or if V1 and V2 are not instructions,
1305       //  or if they are SPLAT,
1306       //  or if they are not consecutive,
1307       //  or if profitable to vectorize loads or extractelements, early return
1308       //  the current cost.
1309       auto *I1 = dyn_cast<Instruction>(LHS);
1310       auto *I2 = dyn_cast<Instruction>(RHS);
1311       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1312           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1313           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1314             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1315             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1316            ShallowScoreAtThisLevel))
1317         return ShallowScoreAtThisLevel;
1318       assert(I1 && I2 && "Should have early exited.");
1319 
1320       // Contains the I2 operand indexes that got matched with I1 operands.
1321       SmallSet<unsigned, 4> Op2Used;
1322 
1323       // Recursion towards the operands of I1 and I2. We are trying all possible
1324       // operand pairs, and keeping track of the best score.
1325       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1326            OpIdx1 != NumOperands1; ++OpIdx1) {
1327         // Try to pair op1I with the best operand of I2.
1328         int MaxTmpScore = 0;
1329         unsigned MaxOpIdx2 = 0;
1330         bool FoundBest = false;
1331         // If I2 is commutative try all combinations.
1332         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1333         unsigned ToIdx = isCommutative(I2)
1334                              ? I2->getNumOperands()
1335                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1336         assert(FromIdx <= ToIdx && "Bad index");
1337         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1338           // Skip operands already paired with OpIdx1.
1339           if (Op2Used.count(OpIdx2))
1340             continue;
1341           // Recursively calculate the cost at each level
1342           int TmpScore =
1343               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1344                                  CurrLevel + 1, MaxLevel, None);
1345           // Look for the best score.
1346           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1347             MaxTmpScore = TmpScore;
1348             MaxOpIdx2 = OpIdx2;
1349             FoundBest = true;
1350           }
1351         }
1352         if (FoundBest) {
1353           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1354           Op2Used.insert(MaxOpIdx2);
1355           ShallowScoreAtThisLevel += MaxTmpScore;
1356         }
1357       }
1358       return ShallowScoreAtThisLevel;
1359     }
1360 
1361     /// Score scaling factor for fully compatible instructions but with
1362     /// different number of external uses. Allows better selection of the
1363     /// instructions with less external uses.
1364     static const int ScoreScaleFactor = 10;
1365 
1366     /// \Returns the look-ahead score, which tells us how much the sub-trees
1367     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1368     /// score. This helps break ties in an informed way when we cannot decide on
1369     /// the order of the operands by just considering the immediate
1370     /// predecessors.
1371     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1372                           int Lane, unsigned OpIdx, unsigned Idx,
1373                           bool &IsUsed) {
1374       int Score =
1375           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1376       if (Score) {
1377         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1378         if (Score <= -SplatScore) {
1379           // Set the minimum score for splat-like sequence to avoid setting
1380           // failed state.
1381           Score = 1;
1382         } else {
1383           Score += SplatScore;
1384           // Scale score to see the difference between different operands
1385           // and similar operands but all vectorized/not all vectorized
1386           // uses. It does not affect actual selection of the best
1387           // compatible operand in general, just allows to select the
1388           // operand with all vectorized uses.
1389           Score *= ScoreScaleFactor;
1390           Score += getExternalUseScore(Lane, OpIdx, Idx);
1391           IsUsed = true;
1392         }
1393       }
1394       return Score;
1395     }
1396 
1397     /// Best defined scores per lanes between the passes. Used to choose the
1398     /// best operand (with the highest score) between the passes.
1399     /// The key - {Operand Index, Lane}.
1400     /// The value - the best score between the passes for the lane and the
1401     /// operand.
1402     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1403         BestScoresPerLanes;
1404 
1405     // Search all operands in Ops[*][Lane] for the one that matches best
1406     // Ops[OpIdx][LastLane] and return its opreand index.
1407     // If no good match can be found, return None.
1408     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1409                                       ArrayRef<ReorderingMode> ReorderingModes,
1410                                       ArrayRef<Value *> MainAltOps) {
1411       unsigned NumOperands = getNumOperands();
1412 
1413       // The operand of the previous lane at OpIdx.
1414       Value *OpLastLane = getData(OpIdx, LastLane).V;
1415 
1416       // Our strategy mode for OpIdx.
1417       ReorderingMode RMode = ReorderingModes[OpIdx];
1418       if (RMode == ReorderingMode::Failed)
1419         return None;
1420 
1421       // The linearized opcode of the operand at OpIdx, Lane.
1422       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1423 
1424       // The best operand index and its score.
1425       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1426       // are using the score to differentiate between the two.
1427       struct BestOpData {
1428         Optional<unsigned> Idx = None;
1429         unsigned Score = 0;
1430       } BestOp;
1431       BestOp.Score =
1432           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1433               .first->second;
1434 
1435       // Track if the operand must be marked as used. If the operand is set to
1436       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1437       // want to reestimate the operands again on the following iterations).
1438       bool IsUsed =
1439           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1440       // Iterate through all unused operands and look for the best.
1441       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1442         // Get the operand at Idx and Lane.
1443         OperandData &OpData = getData(Idx, Lane);
1444         Value *Op = OpData.V;
1445         bool OpAPO = OpData.APO;
1446 
1447         // Skip already selected operands.
1448         if (OpData.IsUsed)
1449           continue;
1450 
1451         // Skip if we are trying to move the operand to a position with a
1452         // different opcode in the linearized tree form. This would break the
1453         // semantics.
1454         if (OpAPO != OpIdxAPO)
1455           continue;
1456 
1457         // Look for an operand that matches the current mode.
1458         switch (RMode) {
1459         case ReorderingMode::Load:
1460         case ReorderingMode::Constant:
1461         case ReorderingMode::Opcode: {
1462           bool LeftToRight = Lane > LastLane;
1463           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1464           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1465           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1466                                         OpIdx, Idx, IsUsed);
1467           if (Score > static_cast<int>(BestOp.Score)) {
1468             BestOp.Idx = Idx;
1469             BestOp.Score = Score;
1470             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1471           }
1472           break;
1473         }
1474         case ReorderingMode::Splat:
1475           if (Op == OpLastLane)
1476             BestOp.Idx = Idx;
1477           break;
1478         case ReorderingMode::Failed:
1479           llvm_unreachable("Not expected Failed reordering mode.");
1480         }
1481       }
1482 
1483       if (BestOp.Idx) {
1484         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1485         return BestOp.Idx;
1486       }
1487       // If we could not find a good match return None.
1488       return None;
1489     }
1490 
1491     /// Helper for reorderOperandVecs.
1492     /// \returns the lane that we should start reordering from. This is the one
1493     /// which has the least number of operands that can freely move about or
1494     /// less profitable because it already has the most optimal set of operands.
1495     unsigned getBestLaneToStartReordering() const {
1496       unsigned Min = UINT_MAX;
1497       unsigned SameOpNumber = 0;
1498       // std::pair<unsigned, unsigned> is used to implement a simple voting
1499       // algorithm and choose the lane with the least number of operands that
1500       // can freely move about or less profitable because it already has the
1501       // most optimal set of operands. The first unsigned is a counter for
1502       // voting, the second unsigned is the counter of lanes with instructions
1503       // with same/alternate opcodes and same parent basic block.
1504       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1505       // Try to be closer to the original results, if we have multiple lanes
1506       // with same cost. If 2 lanes have the same cost, use the one with the
1507       // lowest index.
1508       for (int I = getNumLanes(); I > 0; --I) {
1509         unsigned Lane = I - 1;
1510         OperandsOrderData NumFreeOpsHash =
1511             getMaxNumOperandsThatCanBeReordered(Lane);
1512         // Compare the number of operands that can move and choose the one with
1513         // the least number.
1514         if (NumFreeOpsHash.NumOfAPOs < Min) {
1515           Min = NumFreeOpsHash.NumOfAPOs;
1516           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1517           HashMap.clear();
1518           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1519         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1520                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1521           // Select the most optimal lane in terms of number of operands that
1522           // should be moved around.
1523           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1524           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1525         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1526                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1527           auto It = HashMap.find(NumFreeOpsHash.Hash);
1528           if (It == HashMap.end())
1529             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1530           else
1531             ++It->second.first;
1532         }
1533       }
1534       // Select the lane with the minimum counter.
1535       unsigned BestLane = 0;
1536       unsigned CntMin = UINT_MAX;
1537       for (const auto &Data : reverse(HashMap)) {
1538         if (Data.second.first < CntMin) {
1539           CntMin = Data.second.first;
1540           BestLane = Data.second.second;
1541         }
1542       }
1543       return BestLane;
1544     }
1545 
1546     /// Data structure that helps to reorder operands.
1547     struct OperandsOrderData {
1548       /// The best number of operands with the same APOs, which can be
1549       /// reordered.
1550       unsigned NumOfAPOs = UINT_MAX;
1551       /// Number of operands with the same/alternate instruction opcode and
1552       /// parent.
1553       unsigned NumOpsWithSameOpcodeParent = 0;
1554       /// Hash for the actual operands ordering.
1555       /// Used to count operands, actually their position id and opcode
1556       /// value. It is used in the voting mechanism to find the lane with the
1557       /// least number of operands that can freely move about or less profitable
1558       /// because it already has the most optimal set of operands. Can be
1559       /// replaced with SmallVector<unsigned> instead but hash code is faster
1560       /// and requires less memory.
1561       unsigned Hash = 0;
1562     };
1563     /// \returns the maximum number of operands that are allowed to be reordered
1564     /// for \p Lane and the number of compatible instructions(with the same
1565     /// parent/opcode). This is used as a heuristic for selecting the first lane
1566     /// to start operand reordering.
1567     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1568       unsigned CntTrue = 0;
1569       unsigned NumOperands = getNumOperands();
1570       // Operands with the same APO can be reordered. We therefore need to count
1571       // how many of them we have for each APO, like this: Cnt[APO] = x.
1572       // Since we only have two APOs, namely true and false, we can avoid using
1573       // a map. Instead we can simply count the number of operands that
1574       // correspond to one of them (in this case the 'true' APO), and calculate
1575       // the other by subtracting it from the total number of operands.
1576       // Operands with the same instruction opcode and parent are more
1577       // profitable since we don't need to move them in many cases, with a high
1578       // probability such lane already can be vectorized effectively.
1579       bool AllUndefs = true;
1580       unsigned NumOpsWithSameOpcodeParent = 0;
1581       Instruction *OpcodeI = nullptr;
1582       BasicBlock *Parent = nullptr;
1583       unsigned Hash = 0;
1584       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1585         const OperandData &OpData = getData(OpIdx, Lane);
1586         if (OpData.APO)
1587           ++CntTrue;
1588         // Use Boyer-Moore majority voting for finding the majority opcode and
1589         // the number of times it occurs.
1590         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1591           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1592               I->getParent() != Parent) {
1593             if (NumOpsWithSameOpcodeParent == 0) {
1594               NumOpsWithSameOpcodeParent = 1;
1595               OpcodeI = I;
1596               Parent = I->getParent();
1597             } else {
1598               --NumOpsWithSameOpcodeParent;
1599             }
1600           } else {
1601             ++NumOpsWithSameOpcodeParent;
1602           }
1603         }
1604         Hash = hash_combine(
1605             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1606         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1607       }
1608       if (AllUndefs)
1609         return {};
1610       OperandsOrderData Data;
1611       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1612       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1613       Data.Hash = Hash;
1614       return Data;
1615     }
1616 
1617     /// Go through the instructions in VL and append their operands.
1618     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1619       assert(!VL.empty() && "Bad VL");
1620       assert((empty() || VL.size() == getNumLanes()) &&
1621              "Expected same number of lanes");
1622       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1623       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1624       OpsVec.resize(NumOperands);
1625       unsigned NumLanes = VL.size();
1626       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1627         OpsVec[OpIdx].resize(NumLanes);
1628         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1629           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1630           // Our tree has just 3 nodes: the root and two operands.
1631           // It is therefore trivial to get the APO. We only need to check the
1632           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1633           // RHS operand. The LHS operand of both add and sub is never attached
1634           // to an inversese operation in the linearized form, therefore its APO
1635           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1636 
1637           // Since operand reordering is performed on groups of commutative
1638           // operations or alternating sequences (e.g., +, -), we can safely
1639           // tell the inverse operations by checking commutativity.
1640           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1641           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1642           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1643                                  APO, false};
1644         }
1645       }
1646     }
1647 
1648     /// \returns the number of operands.
1649     unsigned getNumOperands() const { return OpsVec.size(); }
1650 
1651     /// \returns the number of lanes.
1652     unsigned getNumLanes() const { return OpsVec[0].size(); }
1653 
1654     /// \returns the operand value at \p OpIdx and \p Lane.
1655     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1656       return getData(OpIdx, Lane).V;
1657     }
1658 
1659     /// \returns true if the data structure is empty.
1660     bool empty() const { return OpsVec.empty(); }
1661 
1662     /// Clears the data.
1663     void clear() { OpsVec.clear(); }
1664 
1665     /// \Returns true if there are enough operands identical to \p Op to fill
1666     /// the whole vector.
1667     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1668     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1669       bool OpAPO = getData(OpIdx, Lane).APO;
1670       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1671         if (Ln == Lane)
1672           continue;
1673         // This is set to true if we found a candidate for broadcast at Lane.
1674         bool FoundCandidate = false;
1675         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1676           OperandData &Data = getData(OpI, Ln);
1677           if (Data.APO != OpAPO || Data.IsUsed)
1678             continue;
1679           if (Data.V == Op) {
1680             FoundCandidate = true;
1681             Data.IsUsed = true;
1682             break;
1683           }
1684         }
1685         if (!FoundCandidate)
1686           return false;
1687       }
1688       return true;
1689     }
1690 
1691   public:
1692     /// Initialize with all the operands of the instruction vector \p RootVL.
1693     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1694                ScalarEvolution &SE, const BoUpSLP &R)
1695         : DL(DL), SE(SE), R(R) {
1696       // Append all the operands of RootVL.
1697       appendOperandsOfVL(RootVL);
1698     }
1699 
1700     /// \Returns a value vector with the operands across all lanes for the
1701     /// opearnd at \p OpIdx.
1702     ValueList getVL(unsigned OpIdx) const {
1703       ValueList OpVL(OpsVec[OpIdx].size());
1704       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1705              "Expected same num of lanes across all operands");
1706       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1707         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1708       return OpVL;
1709     }
1710 
1711     // Performs operand reordering for 2 or more operands.
1712     // The original operands are in OrigOps[OpIdx][Lane].
1713     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1714     void reorder() {
1715       unsigned NumOperands = getNumOperands();
1716       unsigned NumLanes = getNumLanes();
1717       // Each operand has its own mode. We are using this mode to help us select
1718       // the instructions for each lane, so that they match best with the ones
1719       // we have selected so far.
1720       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1721 
1722       // This is a greedy single-pass algorithm. We are going over each lane
1723       // once and deciding on the best order right away with no back-tracking.
1724       // However, in order to increase its effectiveness, we start with the lane
1725       // that has operands that can move the least. For example, given the
1726       // following lanes:
1727       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1728       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1729       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1730       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1731       // we will start at Lane 1, since the operands of the subtraction cannot
1732       // be reordered. Then we will visit the rest of the lanes in a circular
1733       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1734 
1735       // Find the first lane that we will start our search from.
1736       unsigned FirstLane = getBestLaneToStartReordering();
1737 
1738       // Initialize the modes.
1739       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1740         Value *OpLane0 = getValue(OpIdx, FirstLane);
1741         // Keep track if we have instructions with all the same opcode on one
1742         // side.
1743         if (isa<LoadInst>(OpLane0))
1744           ReorderingModes[OpIdx] = ReorderingMode::Load;
1745         else if (isa<Instruction>(OpLane0)) {
1746           // Check if OpLane0 should be broadcast.
1747           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1748             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1749           else
1750             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1751         }
1752         else if (isa<Constant>(OpLane0))
1753           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1754         else if (isa<Argument>(OpLane0))
1755           // Our best hope is a Splat. It may save some cost in some cases.
1756           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1757         else
1758           // NOTE: This should be unreachable.
1759           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1760       }
1761 
1762       // Check that we don't have same operands. No need to reorder if operands
1763       // are just perfect diamond or shuffled diamond match. Do not do it only
1764       // for possible broadcasts or non-power of 2 number of scalars (just for
1765       // now).
1766       auto &&SkipReordering = [this]() {
1767         SmallPtrSet<Value *, 4> UniqueValues;
1768         ArrayRef<OperandData> Op0 = OpsVec.front();
1769         for (const OperandData &Data : Op0)
1770           UniqueValues.insert(Data.V);
1771         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1772           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1773                 return !UniqueValues.contains(Data.V);
1774               }))
1775             return false;
1776         }
1777         // TODO: Check if we can remove a check for non-power-2 number of
1778         // scalars after full support of non-power-2 vectorization.
1779         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1780       };
1781 
1782       // If the initial strategy fails for any of the operand indexes, then we
1783       // perform reordering again in a second pass. This helps avoid assigning
1784       // high priority to the failed strategy, and should improve reordering for
1785       // the non-failed operand indexes.
1786       for (int Pass = 0; Pass != 2; ++Pass) {
1787         // Check if no need to reorder operands since they're are perfect or
1788         // shuffled diamond match.
1789         // Need to to do it to avoid extra external use cost counting for
1790         // shuffled matches, which may cause regressions.
1791         if (SkipReordering())
1792           break;
1793         // Skip the second pass if the first pass did not fail.
1794         bool StrategyFailed = false;
1795         // Mark all operand data as free to use.
1796         clearUsed();
1797         // We keep the original operand order for the FirstLane, so reorder the
1798         // rest of the lanes. We are visiting the nodes in a circular fashion,
1799         // using FirstLane as the center point and increasing the radius
1800         // distance.
1801         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1802         for (unsigned I = 0; I < NumOperands; ++I)
1803           MainAltOps[I].push_back(getData(I, FirstLane).V);
1804 
1805         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1806           // Visit the lane on the right and then the lane on the left.
1807           for (int Direction : {+1, -1}) {
1808             int Lane = FirstLane + Direction * Distance;
1809             if (Lane < 0 || Lane >= (int)NumLanes)
1810               continue;
1811             int LastLane = Lane - Direction;
1812             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1813                    "Out of bounds");
1814             // Look for a good match for each operand.
1815             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1816               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1817               Optional<unsigned> BestIdx = getBestOperand(
1818                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1819               // By not selecting a value, we allow the operands that follow to
1820               // select a better matching value. We will get a non-null value in
1821               // the next run of getBestOperand().
1822               if (BestIdx) {
1823                 // Swap the current operand with the one returned by
1824                 // getBestOperand().
1825                 swap(OpIdx, BestIdx.getValue(), Lane);
1826               } else {
1827                 // We failed to find a best operand, set mode to 'Failed'.
1828                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1829                 // Enable the second pass.
1830                 StrategyFailed = true;
1831               }
1832               // Try to get the alternate opcode and follow it during analysis.
1833               if (MainAltOps[OpIdx].size() != 2) {
1834                 OperandData &AltOp = getData(OpIdx, Lane);
1835                 InstructionsState OpS =
1836                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1837                 if (OpS.getOpcode() && OpS.isAltShuffle())
1838                   MainAltOps[OpIdx].push_back(AltOp.V);
1839               }
1840             }
1841           }
1842         }
1843         // Skip second pass if the strategy did not fail.
1844         if (!StrategyFailed)
1845           break;
1846       }
1847     }
1848 
1849 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1850     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1851       switch (RMode) {
1852       case ReorderingMode::Load:
1853         return "Load";
1854       case ReorderingMode::Opcode:
1855         return "Opcode";
1856       case ReorderingMode::Constant:
1857         return "Constant";
1858       case ReorderingMode::Splat:
1859         return "Splat";
1860       case ReorderingMode::Failed:
1861         return "Failed";
1862       }
1863       llvm_unreachable("Unimplemented Reordering Type");
1864     }
1865 
1866     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1867                                                    raw_ostream &OS) {
1868       return OS << getModeStr(RMode);
1869     }
1870 
1871     /// Debug print.
1872     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1873       printMode(RMode, dbgs());
1874     }
1875 
1876     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1877       return printMode(RMode, OS);
1878     }
1879 
1880     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1881       const unsigned Indent = 2;
1882       unsigned Cnt = 0;
1883       for (const OperandDataVec &OpDataVec : OpsVec) {
1884         OS << "Operand " << Cnt++ << "\n";
1885         for (const OperandData &OpData : OpDataVec) {
1886           OS.indent(Indent) << "{";
1887           if (Value *V = OpData.V)
1888             OS << *V;
1889           else
1890             OS << "null";
1891           OS << ", APO:" << OpData.APO << "}\n";
1892         }
1893         OS << "\n";
1894       }
1895       return OS;
1896     }
1897 
1898     /// Debug print.
1899     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1900 #endif
1901   };
1902 
1903   /// Checks if the instruction is marked for deletion.
1904   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1905 
1906   /// Marks values operands for later deletion by replacing them with Undefs.
1907   void eraseInstructions(ArrayRef<Value *> AV);
1908 
1909   ~BoUpSLP();
1910 
1911 private:
1912   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1913   /// reordering (i.e. the operands can be reordered because they have only one
1914   /// user and reordarable).
1915   /// \param NonVectorized List of all gather nodes that require reordering
1916   /// (e.g., gather of extractlements or partially vectorizable loads).
1917   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1918   /// reordering, subset of \p NonVectorized.
1919   bool
1920   canReorderOperands(TreeEntry *UserTE,
1921                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1922                      ArrayRef<TreeEntry *> ReorderableGathers,
1923                      SmallVectorImpl<TreeEntry *> &GatherOps);
1924 
1925   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1926   /// if any. If it is not vectorized (gather node), returns nullptr.
1927   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1928     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1929     TreeEntry *TE = nullptr;
1930     const auto *It = find_if(VL, [this, &TE](Value *V) {
1931       TE = getTreeEntry(V);
1932       return TE;
1933     });
1934     if (It != VL.end() && TE->isSame(VL))
1935       return TE;
1936     return nullptr;
1937   }
1938 
1939   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1940   /// if any. If it is not vectorized (gather node), returns nullptr.
1941   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
1942                                         unsigned OpIdx) const {
1943     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
1944         const_cast<TreeEntry *>(UserTE), OpIdx);
1945   }
1946 
1947   /// Checks if all users of \p I are the part of the vectorization tree.
1948   bool areAllUsersVectorized(Instruction *I,
1949                              ArrayRef<Value *> VectorizedVals) const;
1950 
1951   /// \returns the cost of the vectorizable entry.
1952   InstructionCost getEntryCost(const TreeEntry *E,
1953                                ArrayRef<Value *> VectorizedVals);
1954 
1955   /// This is the recursive part of buildTree.
1956   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1957                      const EdgeInfo &EI);
1958 
1959   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1960   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1961   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1962   /// returns false, setting \p CurrentOrder to either an empty vector or a
1963   /// non-identity permutation that allows to reuse extract instructions.
1964   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1965                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1966 
1967   /// Vectorize a single entry in the tree.
1968   Value *vectorizeTree(TreeEntry *E);
1969 
1970   /// Vectorize a single entry in the tree, starting in \p VL.
1971   Value *vectorizeTree(ArrayRef<Value *> VL);
1972 
1973   /// Create a new vector from a list of scalar values.  Produces a sequence
1974   /// which exploits values reused across lanes, and arranges the inserts
1975   /// for ease of later optimization.
1976   Value *createBuildVector(ArrayRef<Value *> VL);
1977 
1978   /// \returns the scalarization cost for this type. Scalarization in this
1979   /// context means the creation of vectors from a group of scalars. If \p
1980   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1981   /// vector elements.
1982   InstructionCost getGatherCost(FixedVectorType *Ty,
1983                                 const APInt &ShuffledIndices,
1984                                 bool NeedToShuffle) const;
1985 
1986   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1987   /// tree entries.
1988   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1989   /// previous tree entries. \p Mask is filled with the shuffle mask.
1990   Optional<TargetTransformInfo::ShuffleKind>
1991   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1992                         SmallVectorImpl<const TreeEntry *> &Entries);
1993 
1994   /// \returns the scalarization cost for this list of values. Assuming that
1995   /// this subtree gets vectorized, we may need to extract the values from the
1996   /// roots. This method calculates the cost of extracting the values.
1997   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1998 
1999   /// Set the Builder insert point to one after the last instruction in
2000   /// the bundle
2001   void setInsertPointAfterBundle(const TreeEntry *E);
2002 
2003   /// \returns a vector from a collection of scalars in \p VL.
2004   Value *gather(ArrayRef<Value *> VL);
2005 
2006   /// \returns whether the VectorizableTree is fully vectorizable and will
2007   /// be beneficial even the tree height is tiny.
2008   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2009 
2010   /// Reorder commutative or alt operands to get better probability of
2011   /// generating vectorized code.
2012   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2013                                              SmallVectorImpl<Value *> &Left,
2014                                              SmallVectorImpl<Value *> &Right,
2015                                              const DataLayout &DL,
2016                                              ScalarEvolution &SE,
2017                                              const BoUpSLP &R);
2018   struct TreeEntry {
2019     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2020     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2021 
2022     /// \returns true if the scalars in VL are equal to this entry.
2023     bool isSame(ArrayRef<Value *> VL) const {
2024       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2025         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2026           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2027         return VL.size() == Mask.size() &&
2028                std::equal(VL.begin(), VL.end(), Mask.begin(),
2029                           [Scalars](Value *V, int Idx) {
2030                             return (isa<UndefValue>(V) &&
2031                                     Idx == UndefMaskElem) ||
2032                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2033                           });
2034       };
2035       if (!ReorderIndices.empty()) {
2036         // TODO: implement matching if the nodes are just reordered, still can
2037         // treat the vector as the same if the list of scalars matches VL
2038         // directly, without reordering.
2039         SmallVector<int> Mask;
2040         inversePermutation(ReorderIndices, Mask);
2041         if (VL.size() == Scalars.size())
2042           return IsSame(Scalars, Mask);
2043         if (VL.size() == ReuseShuffleIndices.size()) {
2044           ::addMask(Mask, ReuseShuffleIndices);
2045           return IsSame(Scalars, Mask);
2046         }
2047         return false;
2048       }
2049       return IsSame(Scalars, ReuseShuffleIndices);
2050     }
2051 
2052     /// \returns true if current entry has same operands as \p TE.
2053     bool hasEqualOperands(const TreeEntry &TE) const {
2054       if (TE.getNumOperands() != getNumOperands())
2055         return false;
2056       SmallBitVector Used(getNumOperands());
2057       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2058         unsigned PrevCount = Used.count();
2059         for (unsigned K = 0; K < E; ++K) {
2060           if (Used.test(K))
2061             continue;
2062           if (getOperand(K) == TE.getOperand(I)) {
2063             Used.set(K);
2064             break;
2065           }
2066         }
2067         // Check if we actually found the matching operand.
2068         if (PrevCount == Used.count())
2069           return false;
2070       }
2071       return true;
2072     }
2073 
2074     /// \return Final vectorization factor for the node. Defined by the total
2075     /// number of vectorized scalars, including those, used several times in the
2076     /// entry and counted in the \a ReuseShuffleIndices, if any.
2077     unsigned getVectorFactor() const {
2078       if (!ReuseShuffleIndices.empty())
2079         return ReuseShuffleIndices.size();
2080       return Scalars.size();
2081     };
2082 
2083     /// A vector of scalars.
2084     ValueList Scalars;
2085 
2086     /// The Scalars are vectorized into this value. It is initialized to Null.
2087     Value *VectorizedValue = nullptr;
2088 
2089     /// Do we need to gather this sequence or vectorize it
2090     /// (either with vector instruction or with scatter/gather
2091     /// intrinsics for store/load)?
2092     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2093     EntryState State;
2094 
2095     /// Does this sequence require some shuffling?
2096     SmallVector<int, 4> ReuseShuffleIndices;
2097 
2098     /// Does this entry require reordering?
2099     SmallVector<unsigned, 4> ReorderIndices;
2100 
2101     /// Points back to the VectorizableTree.
2102     ///
2103     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2104     /// to be a pointer and needs to be able to initialize the child iterator.
2105     /// Thus we need a reference back to the container to translate the indices
2106     /// to entries.
2107     VecTreeTy &Container;
2108 
2109     /// The TreeEntry index containing the user of this entry.  We can actually
2110     /// have multiple users so the data structure is not truly a tree.
2111     SmallVector<EdgeInfo, 1> UserTreeIndices;
2112 
2113     /// The index of this treeEntry in VectorizableTree.
2114     int Idx = -1;
2115 
2116   private:
2117     /// The operands of each instruction in each lane Operands[op_index][lane].
2118     /// Note: This helps avoid the replication of the code that performs the
2119     /// reordering of operands during buildTree_rec() and vectorizeTree().
2120     SmallVector<ValueList, 2> Operands;
2121 
2122     /// The main/alternate instruction.
2123     Instruction *MainOp = nullptr;
2124     Instruction *AltOp = nullptr;
2125 
2126   public:
2127     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2128     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2129       if (Operands.size() < OpIdx + 1)
2130         Operands.resize(OpIdx + 1);
2131       assert(Operands[OpIdx].empty() && "Already resized?");
2132       assert(OpVL.size() <= Scalars.size() &&
2133              "Number of operands is greater than the number of scalars.");
2134       Operands[OpIdx].resize(OpVL.size());
2135       copy(OpVL, Operands[OpIdx].begin());
2136     }
2137 
2138     /// Set the operands of this bundle in their original order.
2139     void setOperandsInOrder() {
2140       assert(Operands.empty() && "Already initialized?");
2141       auto *I0 = cast<Instruction>(Scalars[0]);
2142       Operands.resize(I0->getNumOperands());
2143       unsigned NumLanes = Scalars.size();
2144       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2145            OpIdx != NumOperands; ++OpIdx) {
2146         Operands[OpIdx].resize(NumLanes);
2147         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2148           auto *I = cast<Instruction>(Scalars[Lane]);
2149           assert(I->getNumOperands() == NumOperands &&
2150                  "Expected same number of operands");
2151           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2152         }
2153       }
2154     }
2155 
2156     /// Reorders operands of the node to the given mask \p Mask.
2157     void reorderOperands(ArrayRef<int> Mask) {
2158       for (ValueList &Operand : Operands)
2159         reorderScalars(Operand, Mask);
2160     }
2161 
2162     /// \returns the \p OpIdx operand of this TreeEntry.
2163     ValueList &getOperand(unsigned OpIdx) {
2164       assert(OpIdx < Operands.size() && "Off bounds");
2165       return Operands[OpIdx];
2166     }
2167 
2168     /// \returns the \p OpIdx operand of this TreeEntry.
2169     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2170       assert(OpIdx < Operands.size() && "Off bounds");
2171       return Operands[OpIdx];
2172     }
2173 
2174     /// \returns the number of operands.
2175     unsigned getNumOperands() const { return Operands.size(); }
2176 
2177     /// \return the single \p OpIdx operand.
2178     Value *getSingleOperand(unsigned OpIdx) const {
2179       assert(OpIdx < Operands.size() && "Off bounds");
2180       assert(!Operands[OpIdx].empty() && "No operand available");
2181       return Operands[OpIdx][0];
2182     }
2183 
2184     /// Some of the instructions in the list have alternate opcodes.
2185     bool isAltShuffle() const { return MainOp != AltOp; }
2186 
2187     bool isOpcodeOrAlt(Instruction *I) const {
2188       unsigned CheckedOpcode = I->getOpcode();
2189       return (getOpcode() == CheckedOpcode ||
2190               getAltOpcode() == CheckedOpcode);
2191     }
2192 
2193     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2194     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2195     /// \p OpValue.
2196     Value *isOneOf(Value *Op) const {
2197       auto *I = dyn_cast<Instruction>(Op);
2198       if (I && isOpcodeOrAlt(I))
2199         return Op;
2200       return MainOp;
2201     }
2202 
2203     void setOperations(const InstructionsState &S) {
2204       MainOp = S.MainOp;
2205       AltOp = S.AltOp;
2206     }
2207 
2208     Instruction *getMainOp() const {
2209       return MainOp;
2210     }
2211 
2212     Instruction *getAltOp() const {
2213       return AltOp;
2214     }
2215 
2216     /// The main/alternate opcodes for the list of instructions.
2217     unsigned getOpcode() const {
2218       return MainOp ? MainOp->getOpcode() : 0;
2219     }
2220 
2221     unsigned getAltOpcode() const {
2222       return AltOp ? AltOp->getOpcode() : 0;
2223     }
2224 
2225     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2226     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2227     int findLaneForValue(Value *V) const {
2228       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2229       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2230       if (!ReorderIndices.empty())
2231         FoundLane = ReorderIndices[FoundLane];
2232       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2233       if (!ReuseShuffleIndices.empty()) {
2234         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2235                                   find(ReuseShuffleIndices, FoundLane));
2236       }
2237       return FoundLane;
2238     }
2239 
2240 #ifndef NDEBUG
2241     /// Debug printer.
2242     LLVM_DUMP_METHOD void dump() const {
2243       dbgs() << Idx << ".\n";
2244       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2245         dbgs() << "Operand " << OpI << ":\n";
2246         for (const Value *V : Operands[OpI])
2247           dbgs().indent(2) << *V << "\n";
2248       }
2249       dbgs() << "Scalars: \n";
2250       for (Value *V : Scalars)
2251         dbgs().indent(2) << *V << "\n";
2252       dbgs() << "State: ";
2253       switch (State) {
2254       case Vectorize:
2255         dbgs() << "Vectorize\n";
2256         break;
2257       case ScatterVectorize:
2258         dbgs() << "ScatterVectorize\n";
2259         break;
2260       case NeedToGather:
2261         dbgs() << "NeedToGather\n";
2262         break;
2263       }
2264       dbgs() << "MainOp: ";
2265       if (MainOp)
2266         dbgs() << *MainOp << "\n";
2267       else
2268         dbgs() << "NULL\n";
2269       dbgs() << "AltOp: ";
2270       if (AltOp)
2271         dbgs() << *AltOp << "\n";
2272       else
2273         dbgs() << "NULL\n";
2274       dbgs() << "VectorizedValue: ";
2275       if (VectorizedValue)
2276         dbgs() << *VectorizedValue << "\n";
2277       else
2278         dbgs() << "NULL\n";
2279       dbgs() << "ReuseShuffleIndices: ";
2280       if (ReuseShuffleIndices.empty())
2281         dbgs() << "Empty";
2282       else
2283         for (int ReuseIdx : ReuseShuffleIndices)
2284           dbgs() << ReuseIdx << ", ";
2285       dbgs() << "\n";
2286       dbgs() << "ReorderIndices: ";
2287       for (unsigned ReorderIdx : ReorderIndices)
2288         dbgs() << ReorderIdx << ", ";
2289       dbgs() << "\n";
2290       dbgs() << "UserTreeIndices: ";
2291       for (const auto &EInfo : UserTreeIndices)
2292         dbgs() << EInfo << ", ";
2293       dbgs() << "\n";
2294     }
2295 #endif
2296   };
2297 
2298 #ifndef NDEBUG
2299   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2300                      InstructionCost VecCost,
2301                      InstructionCost ScalarCost) const {
2302     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2303     dbgs() << "SLP: Costs:\n";
2304     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2305     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2306     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2307     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2308                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2309   }
2310 #endif
2311 
2312   /// Create a new VectorizableTree entry.
2313   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2314                           const InstructionsState &S,
2315                           const EdgeInfo &UserTreeIdx,
2316                           ArrayRef<int> ReuseShuffleIndices = None,
2317                           ArrayRef<unsigned> ReorderIndices = None) {
2318     TreeEntry::EntryState EntryState =
2319         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2320     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2321                         ReuseShuffleIndices, ReorderIndices);
2322   }
2323 
2324   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2325                           TreeEntry::EntryState EntryState,
2326                           Optional<ScheduleData *> Bundle,
2327                           const InstructionsState &S,
2328                           const EdgeInfo &UserTreeIdx,
2329                           ArrayRef<int> ReuseShuffleIndices = None,
2330                           ArrayRef<unsigned> ReorderIndices = None) {
2331     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2332             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2333            "Need to vectorize gather entry?");
2334     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2335     TreeEntry *Last = VectorizableTree.back().get();
2336     Last->Idx = VectorizableTree.size() - 1;
2337     Last->State = EntryState;
2338     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2339                                      ReuseShuffleIndices.end());
2340     if (ReorderIndices.empty()) {
2341       Last->Scalars.assign(VL.begin(), VL.end());
2342       Last->setOperations(S);
2343     } else {
2344       // Reorder scalars and build final mask.
2345       Last->Scalars.assign(VL.size(), nullptr);
2346       transform(ReorderIndices, Last->Scalars.begin(),
2347                 [VL](unsigned Idx) -> Value * {
2348                   if (Idx >= VL.size())
2349                     return UndefValue::get(VL.front()->getType());
2350                   return VL[Idx];
2351                 });
2352       InstructionsState S = getSameOpcode(Last->Scalars);
2353       Last->setOperations(S);
2354       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2355     }
2356     if (Last->State != TreeEntry::NeedToGather) {
2357       for (Value *V : VL) {
2358         assert(!getTreeEntry(V) && "Scalar already in tree!");
2359         ScalarToTreeEntry[V] = Last;
2360       }
2361       // Update the scheduler bundle to point to this TreeEntry.
2362       unsigned Lane = 0;
2363       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2364            BundleMember = BundleMember->NextInBundle) {
2365         BundleMember->TE = Last;
2366         BundleMember->Lane = Lane;
2367         ++Lane;
2368       }
2369       assert((!Bundle.getValue() || Lane == VL.size()) &&
2370              "Bundle and VL out of sync");
2371     } else {
2372       MustGather.insert(VL.begin(), VL.end());
2373     }
2374 
2375     if (UserTreeIdx.UserTE)
2376       Last->UserTreeIndices.push_back(UserTreeIdx);
2377 
2378     return Last;
2379   }
2380 
2381   /// -- Vectorization State --
2382   /// Holds all of the tree entries.
2383   TreeEntry::VecTreeTy VectorizableTree;
2384 
2385 #ifndef NDEBUG
2386   /// Debug printer.
2387   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2388     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2389       VectorizableTree[Id]->dump();
2390       dbgs() << "\n";
2391     }
2392   }
2393 #endif
2394 
2395   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2396 
2397   const TreeEntry *getTreeEntry(Value *V) const {
2398     return ScalarToTreeEntry.lookup(V);
2399   }
2400 
2401   /// Maps a specific scalar to its tree entry.
2402   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2403 
2404   /// Maps a value to the proposed vectorizable size.
2405   SmallDenseMap<Value *, unsigned> InstrElementSize;
2406 
2407   /// A list of scalars that we found that we need to keep as scalars.
2408   ValueSet MustGather;
2409 
2410   /// This POD struct describes one external user in the vectorized tree.
2411   struct ExternalUser {
2412     ExternalUser(Value *S, llvm::User *U, int L)
2413         : Scalar(S), User(U), Lane(L) {}
2414 
2415     // Which scalar in our function.
2416     Value *Scalar;
2417 
2418     // Which user that uses the scalar.
2419     llvm::User *User;
2420 
2421     // Which lane does the scalar belong to.
2422     int Lane;
2423   };
2424   using UserList = SmallVector<ExternalUser, 16>;
2425 
2426   /// Checks if two instructions may access the same memory.
2427   ///
2428   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2429   /// is invariant in the calling loop.
2430   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2431                  Instruction *Inst2) {
2432     // First check if the result is already in the cache.
2433     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2434     Optional<bool> &result = AliasCache[key];
2435     if (result.hasValue()) {
2436       return result.getValue();
2437     }
2438     bool aliased = true;
2439     if (Loc1.Ptr && isSimple(Inst1))
2440       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2441     // Store the result in the cache.
2442     result = aliased;
2443     return aliased;
2444   }
2445 
2446   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2447 
2448   /// Cache for alias results.
2449   /// TODO: consider moving this to the AliasAnalysis itself.
2450   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2451 
2452   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2453   // globally through SLP because we don't perform any action which
2454   // invalidates capture results.
2455   BatchAAResults BatchAA;
2456 
2457   /// Removes an instruction from its block and eventually deletes it.
2458   /// It's like Instruction::eraseFromParent() except that the actual deletion
2459   /// is delayed until BoUpSLP is destructed.
2460   /// This is required to ensure that there are no incorrect collisions in the
2461   /// AliasCache, which can happen if a new instruction is allocated at the
2462   /// same address as a previously deleted instruction.
2463   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2464     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2465     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2466   }
2467 
2468   /// Temporary store for deleted instructions. Instructions will be deleted
2469   /// eventually when the BoUpSLP is destructed.
2470   DenseMap<Instruction *, bool> DeletedInstructions;
2471 
2472   /// A list of values that need to extracted out of the tree.
2473   /// This list holds pairs of (Internal Scalar : External User). External User
2474   /// can be nullptr, it means that this Internal Scalar will be used later,
2475   /// after vectorization.
2476   UserList ExternalUses;
2477 
2478   /// Values used only by @llvm.assume calls.
2479   SmallPtrSet<const Value *, 32> EphValues;
2480 
2481   /// Holds all of the instructions that we gathered.
2482   SetVector<Instruction *> GatherShuffleSeq;
2483 
2484   /// A list of blocks that we are going to CSE.
2485   SetVector<BasicBlock *> CSEBlocks;
2486 
2487   /// Contains all scheduling relevant data for an instruction.
2488   /// A ScheduleData either represents a single instruction or a member of an
2489   /// instruction bundle (= a group of instructions which is combined into a
2490   /// vector instruction).
2491   struct ScheduleData {
2492     // The initial value for the dependency counters. It means that the
2493     // dependencies are not calculated yet.
2494     enum { InvalidDeps = -1 };
2495 
2496     ScheduleData() = default;
2497 
2498     void init(int BlockSchedulingRegionID, Value *OpVal) {
2499       FirstInBundle = this;
2500       NextInBundle = nullptr;
2501       NextLoadStore = nullptr;
2502       IsScheduled = false;
2503       SchedulingRegionID = BlockSchedulingRegionID;
2504       clearDependencies();
2505       OpValue = OpVal;
2506       TE = nullptr;
2507       Lane = -1;
2508     }
2509 
2510     /// Verify basic self consistency properties
2511     void verify() {
2512       if (hasValidDependencies()) {
2513         assert(UnscheduledDeps <= Dependencies && "invariant");
2514       } else {
2515         assert(UnscheduledDeps == Dependencies && "invariant");
2516       }
2517 
2518       if (IsScheduled) {
2519         assert(isSchedulingEntity() &&
2520                 "unexpected scheduled state");
2521         for (const ScheduleData *BundleMember = this; BundleMember;
2522              BundleMember = BundleMember->NextInBundle) {
2523           assert(BundleMember->hasValidDependencies() &&
2524                  BundleMember->UnscheduledDeps == 0 &&
2525                  "unexpected scheduled state");
2526           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2527                  "only bundle is marked scheduled");
2528         }
2529       }
2530 
2531       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2532              "all bundle members must be in same basic block");
2533     }
2534 
2535     /// Returns true if the dependency information has been calculated.
2536     /// Note that depenendency validity can vary between instructions within
2537     /// a single bundle.
2538     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2539 
2540     /// Returns true for single instructions and for bundle representatives
2541     /// (= the head of a bundle).
2542     bool isSchedulingEntity() const { return FirstInBundle == this; }
2543 
2544     /// Returns true if it represents an instruction bundle and not only a
2545     /// single instruction.
2546     bool isPartOfBundle() const {
2547       return NextInBundle != nullptr || FirstInBundle != this;
2548     }
2549 
2550     /// Returns true if it is ready for scheduling, i.e. it has no more
2551     /// unscheduled depending instructions/bundles.
2552     bool isReady() const {
2553       assert(isSchedulingEntity() &&
2554              "can't consider non-scheduling entity for ready list");
2555       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2556     }
2557 
2558     /// Modifies the number of unscheduled dependencies for this instruction,
2559     /// and returns the number of remaining dependencies for the containing
2560     /// bundle.
2561     int incrementUnscheduledDeps(int Incr) {
2562       assert(hasValidDependencies() &&
2563              "increment of unscheduled deps would be meaningless");
2564       UnscheduledDeps += Incr;
2565       return FirstInBundle->unscheduledDepsInBundle();
2566     }
2567 
2568     /// Sets the number of unscheduled dependencies to the number of
2569     /// dependencies.
2570     void resetUnscheduledDeps() {
2571       UnscheduledDeps = Dependencies;
2572     }
2573 
2574     /// Clears all dependency information.
2575     void clearDependencies() {
2576       Dependencies = InvalidDeps;
2577       resetUnscheduledDeps();
2578       MemoryDependencies.clear();
2579     }
2580 
2581     int unscheduledDepsInBundle() const {
2582       assert(isSchedulingEntity() && "only meaningful on the bundle");
2583       int Sum = 0;
2584       for (const ScheduleData *BundleMember = this; BundleMember;
2585            BundleMember = BundleMember->NextInBundle) {
2586         if (BundleMember->UnscheduledDeps == InvalidDeps)
2587           return InvalidDeps;
2588         Sum += BundleMember->UnscheduledDeps;
2589       }
2590       return Sum;
2591     }
2592 
2593     void dump(raw_ostream &os) const {
2594       if (!isSchedulingEntity()) {
2595         os << "/ " << *Inst;
2596       } else if (NextInBundle) {
2597         os << '[' << *Inst;
2598         ScheduleData *SD = NextInBundle;
2599         while (SD) {
2600           os << ';' << *SD->Inst;
2601           SD = SD->NextInBundle;
2602         }
2603         os << ']';
2604       } else {
2605         os << *Inst;
2606       }
2607     }
2608 
2609     Instruction *Inst = nullptr;
2610 
2611     /// Opcode of the current instruction in the schedule data.
2612     Value *OpValue = nullptr;
2613 
2614     /// The TreeEntry that this instruction corresponds to.
2615     TreeEntry *TE = nullptr;
2616 
2617     /// Points to the head in an instruction bundle (and always to this for
2618     /// single instructions).
2619     ScheduleData *FirstInBundle = nullptr;
2620 
2621     /// Single linked list of all instructions in a bundle. Null if it is a
2622     /// single instruction.
2623     ScheduleData *NextInBundle = nullptr;
2624 
2625     /// Single linked list of all memory instructions (e.g. load, store, call)
2626     /// in the block - until the end of the scheduling region.
2627     ScheduleData *NextLoadStore = nullptr;
2628 
2629     /// The dependent memory instructions.
2630     /// This list is derived on demand in calculateDependencies().
2631     SmallVector<ScheduleData *, 4> MemoryDependencies;
2632 
2633     /// This ScheduleData is in the current scheduling region if this matches
2634     /// the current SchedulingRegionID of BlockScheduling.
2635     int SchedulingRegionID = 0;
2636 
2637     /// Used for getting a "good" final ordering of instructions.
2638     int SchedulingPriority = 0;
2639 
2640     /// The number of dependencies. Constitutes of the number of users of the
2641     /// instruction plus the number of dependent memory instructions (if any).
2642     /// This value is calculated on demand.
2643     /// If InvalidDeps, the number of dependencies is not calculated yet.
2644     int Dependencies = InvalidDeps;
2645 
2646     /// The number of dependencies minus the number of dependencies of scheduled
2647     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2648     /// for scheduling.
2649     /// Note that this is negative as long as Dependencies is not calculated.
2650     int UnscheduledDeps = InvalidDeps;
2651 
2652     /// The lane of this node in the TreeEntry.
2653     int Lane = -1;
2654 
2655     /// True if this instruction is scheduled (or considered as scheduled in the
2656     /// dry-run).
2657     bool IsScheduled = false;
2658   };
2659 
2660 #ifndef NDEBUG
2661   friend inline raw_ostream &operator<<(raw_ostream &os,
2662                                         const BoUpSLP::ScheduleData &SD) {
2663     SD.dump(os);
2664     return os;
2665   }
2666 #endif
2667 
2668   friend struct GraphTraits<BoUpSLP *>;
2669   friend struct DOTGraphTraits<BoUpSLP *>;
2670 
2671   /// Contains all scheduling data for a basic block.
2672   struct BlockScheduling {
2673     BlockScheduling(BasicBlock *BB)
2674         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2675 
2676     void clear() {
2677       ReadyInsts.clear();
2678       ScheduleStart = nullptr;
2679       ScheduleEnd = nullptr;
2680       FirstLoadStoreInRegion = nullptr;
2681       LastLoadStoreInRegion = nullptr;
2682 
2683       // Reduce the maximum schedule region size by the size of the
2684       // previous scheduling run.
2685       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2686       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2687         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2688       ScheduleRegionSize = 0;
2689 
2690       // Make a new scheduling region, i.e. all existing ScheduleData is not
2691       // in the new region yet.
2692       ++SchedulingRegionID;
2693     }
2694 
2695     ScheduleData *getScheduleData(Instruction *I) {
2696       if (BB != I->getParent())
2697         // Avoid lookup if can't possibly be in map.
2698         return nullptr;
2699       ScheduleData *SD = ScheduleDataMap[I];
2700       if (SD && isInSchedulingRegion(SD))
2701         return SD;
2702       return nullptr;
2703     }
2704 
2705     ScheduleData *getScheduleData(Value *V) {
2706       if (auto *I = dyn_cast<Instruction>(V))
2707         return getScheduleData(I);
2708       return nullptr;
2709     }
2710 
2711     ScheduleData *getScheduleData(Value *V, Value *Key) {
2712       if (V == Key)
2713         return getScheduleData(V);
2714       auto I = ExtraScheduleDataMap.find(V);
2715       if (I != ExtraScheduleDataMap.end()) {
2716         ScheduleData *SD = I->second[Key];
2717         if (SD && isInSchedulingRegion(SD))
2718           return SD;
2719       }
2720       return nullptr;
2721     }
2722 
2723     bool isInSchedulingRegion(ScheduleData *SD) const {
2724       return SD->SchedulingRegionID == SchedulingRegionID;
2725     }
2726 
2727     /// Marks an instruction as scheduled and puts all dependent ready
2728     /// instructions into the ready-list.
2729     template <typename ReadyListType>
2730     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2731       SD->IsScheduled = true;
2732       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2733 
2734       for (ScheduleData *BundleMember = SD; BundleMember;
2735            BundleMember = BundleMember->NextInBundle) {
2736         if (BundleMember->Inst != BundleMember->OpValue)
2737           continue;
2738 
2739         // Handle the def-use chain dependencies.
2740 
2741         // Decrement the unscheduled counter and insert to ready list if ready.
2742         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2743           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2744             if (OpDef && OpDef->hasValidDependencies() &&
2745                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2746               // There are no more unscheduled dependencies after
2747               // decrementing, so we can put the dependent instruction
2748               // into the ready list.
2749               ScheduleData *DepBundle = OpDef->FirstInBundle;
2750               assert(!DepBundle->IsScheduled &&
2751                      "already scheduled bundle gets ready");
2752               ReadyList.insert(DepBundle);
2753               LLVM_DEBUG(dbgs()
2754                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2755             }
2756           });
2757         };
2758 
2759         // If BundleMember is a vector bundle, its operands may have been
2760         // reordered during buildTree(). We therefore need to get its operands
2761         // through the TreeEntry.
2762         if (TreeEntry *TE = BundleMember->TE) {
2763           int Lane = BundleMember->Lane;
2764           assert(Lane >= 0 && "Lane not set");
2765 
2766           // Since vectorization tree is being built recursively this assertion
2767           // ensures that the tree entry has all operands set before reaching
2768           // this code. Couple of exceptions known at the moment are extracts
2769           // where their second (immediate) operand is not added. Since
2770           // immediates do not affect scheduler behavior this is considered
2771           // okay.
2772           auto *In = TE->getMainOp();
2773           assert(In &&
2774                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2775                   In->getNumOperands() == TE->getNumOperands()) &&
2776                  "Missed TreeEntry operands?");
2777           (void)In; // fake use to avoid build failure when assertions disabled
2778 
2779           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2780                OpIdx != NumOperands; ++OpIdx)
2781             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2782               DecrUnsched(I);
2783         } else {
2784           // If BundleMember is a stand-alone instruction, no operand reordering
2785           // has taken place, so we directly access its operands.
2786           for (Use &U : BundleMember->Inst->operands())
2787             if (auto *I = dyn_cast<Instruction>(U.get()))
2788               DecrUnsched(I);
2789         }
2790         // Handle the memory dependencies.
2791         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2792           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2793             // There are no more unscheduled dependencies after decrementing,
2794             // so we can put the dependent instruction into the ready list.
2795             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2796             assert(!DepBundle->IsScheduled &&
2797                    "already scheduled bundle gets ready");
2798             ReadyList.insert(DepBundle);
2799             LLVM_DEBUG(dbgs()
2800                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2801           }
2802         }
2803       }
2804     }
2805 
2806     /// Verify basic self consistency properties of the data structure.
2807     void verify() {
2808       if (!ScheduleStart)
2809         return;
2810 
2811       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2812              ScheduleStart->comesBefore(ScheduleEnd) &&
2813              "Not a valid scheduling region?");
2814 
2815       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2816         auto *SD = getScheduleData(I);
2817         assert(SD && "primary scheduledata must exist in window");
2818         assert(isInSchedulingRegion(SD) &&
2819                "primary schedule data not in window?");
2820         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2821                "entire bundle in window!");
2822         (void)SD;
2823         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2824       }
2825 
2826       for (auto *SD : ReadyInsts) {
2827         assert(SD->isSchedulingEntity() && SD->isReady() &&
2828                "item in ready list not ready?");
2829         (void)SD;
2830       }
2831     }
2832 
2833     void doForAllOpcodes(Value *V,
2834                          function_ref<void(ScheduleData *SD)> Action) {
2835       if (ScheduleData *SD = getScheduleData(V))
2836         Action(SD);
2837       auto I = ExtraScheduleDataMap.find(V);
2838       if (I != ExtraScheduleDataMap.end())
2839         for (auto &P : I->second)
2840           if (isInSchedulingRegion(P.second))
2841             Action(P.second);
2842     }
2843 
2844     /// Put all instructions into the ReadyList which are ready for scheduling.
2845     template <typename ReadyListType>
2846     void initialFillReadyList(ReadyListType &ReadyList) {
2847       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2848         doForAllOpcodes(I, [&](ScheduleData *SD) {
2849           if (SD->isSchedulingEntity() && SD->isReady()) {
2850             ReadyList.insert(SD);
2851             LLVM_DEBUG(dbgs()
2852                        << "SLP:    initially in ready list: " << *SD << "\n");
2853           }
2854         });
2855       }
2856     }
2857 
2858     /// Build a bundle from the ScheduleData nodes corresponding to the
2859     /// scalar instruction for each lane.
2860     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2861 
2862     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2863     /// cyclic dependencies. This is only a dry-run, no instructions are
2864     /// actually moved at this stage.
2865     /// \returns the scheduling bundle. The returned Optional value is non-None
2866     /// if \p VL is allowed to be scheduled.
2867     Optional<ScheduleData *>
2868     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2869                       const InstructionsState &S);
2870 
2871     /// Un-bundles a group of instructions.
2872     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2873 
2874     /// Allocates schedule data chunk.
2875     ScheduleData *allocateScheduleDataChunks();
2876 
2877     /// Extends the scheduling region so that V is inside the region.
2878     /// \returns true if the region size is within the limit.
2879     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2880 
2881     /// Initialize the ScheduleData structures for new instructions in the
2882     /// scheduling region.
2883     void initScheduleData(Instruction *FromI, Instruction *ToI,
2884                           ScheduleData *PrevLoadStore,
2885                           ScheduleData *NextLoadStore);
2886 
2887     /// Updates the dependency information of a bundle and of all instructions/
2888     /// bundles which depend on the original bundle.
2889     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2890                                BoUpSLP *SLP);
2891 
2892     /// Sets all instruction in the scheduling region to un-scheduled.
2893     void resetSchedule();
2894 
2895     BasicBlock *BB;
2896 
2897     /// Simple memory allocation for ScheduleData.
2898     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2899 
2900     /// The size of a ScheduleData array in ScheduleDataChunks.
2901     int ChunkSize;
2902 
2903     /// The allocator position in the current chunk, which is the last entry
2904     /// of ScheduleDataChunks.
2905     int ChunkPos;
2906 
2907     /// Attaches ScheduleData to Instruction.
2908     /// Note that the mapping survives during all vectorization iterations, i.e.
2909     /// ScheduleData structures are recycled.
2910     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
2911 
2912     /// Attaches ScheduleData to Instruction with the leading key.
2913     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2914         ExtraScheduleDataMap;
2915 
2916     /// The ready-list for scheduling (only used for the dry-run).
2917     SetVector<ScheduleData *> ReadyInsts;
2918 
2919     /// The first instruction of the scheduling region.
2920     Instruction *ScheduleStart = nullptr;
2921 
2922     /// The first instruction _after_ the scheduling region.
2923     Instruction *ScheduleEnd = nullptr;
2924 
2925     /// The first memory accessing instruction in the scheduling region
2926     /// (can be null).
2927     ScheduleData *FirstLoadStoreInRegion = nullptr;
2928 
2929     /// The last memory accessing instruction in the scheduling region
2930     /// (can be null).
2931     ScheduleData *LastLoadStoreInRegion = nullptr;
2932 
2933     /// The current size of the scheduling region.
2934     int ScheduleRegionSize = 0;
2935 
2936     /// The maximum size allowed for the scheduling region.
2937     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2938 
2939     /// The ID of the scheduling region. For a new vectorization iteration this
2940     /// is incremented which "removes" all ScheduleData from the region.
2941     /// Make sure that the initial SchedulingRegionID is greater than the
2942     /// initial SchedulingRegionID in ScheduleData (which is 0).
2943     int SchedulingRegionID = 1;
2944   };
2945 
2946   /// Attaches the BlockScheduling structures to basic blocks.
2947   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2948 
2949   /// Performs the "real" scheduling. Done before vectorization is actually
2950   /// performed in a basic block.
2951   void scheduleBlock(BlockScheduling *BS);
2952 
2953   /// List of users to ignore during scheduling and that don't need extracting.
2954   ArrayRef<Value *> UserIgnoreList;
2955 
2956   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2957   /// sorted SmallVectors of unsigned.
2958   struct OrdersTypeDenseMapInfo {
2959     static OrdersType getEmptyKey() {
2960       OrdersType V;
2961       V.push_back(~1U);
2962       return V;
2963     }
2964 
2965     static OrdersType getTombstoneKey() {
2966       OrdersType V;
2967       V.push_back(~2U);
2968       return V;
2969     }
2970 
2971     static unsigned getHashValue(const OrdersType &V) {
2972       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2973     }
2974 
2975     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2976       return LHS == RHS;
2977     }
2978   };
2979 
2980   // Analysis and block reference.
2981   Function *F;
2982   ScalarEvolution *SE;
2983   TargetTransformInfo *TTI;
2984   TargetLibraryInfo *TLI;
2985   LoopInfo *LI;
2986   DominatorTree *DT;
2987   AssumptionCache *AC;
2988   DemandedBits *DB;
2989   MemorySSA *MSSA;
2990   const DataLayout *DL;
2991   OptimizationRemarkEmitter *ORE;
2992 
2993   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2994   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2995 
2996   /// Instruction builder to construct the vectorized tree.
2997   IRBuilder<> Builder;
2998 
2999   /// A map of scalar integer values to the smallest bit width with which they
3000   /// can legally be represented. The values map to (width, signed) pairs,
3001   /// where "width" indicates the minimum bit width and "signed" is True if the
3002   /// value must be signed-extended, rather than zero-extended, back to its
3003   /// original width.
3004   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3005 };
3006 
3007 } // end namespace slpvectorizer
3008 
3009 template <> struct GraphTraits<BoUpSLP *> {
3010   using TreeEntry = BoUpSLP::TreeEntry;
3011 
3012   /// NodeRef has to be a pointer per the GraphWriter.
3013   using NodeRef = TreeEntry *;
3014 
3015   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3016 
3017   /// Add the VectorizableTree to the index iterator to be able to return
3018   /// TreeEntry pointers.
3019   struct ChildIteratorType
3020       : public iterator_adaptor_base<
3021             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3022     ContainerTy &VectorizableTree;
3023 
3024     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3025                       ContainerTy &VT)
3026         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3027 
3028     NodeRef operator*() { return I->UserTE; }
3029   };
3030 
3031   static NodeRef getEntryNode(BoUpSLP &R) {
3032     return R.VectorizableTree[0].get();
3033   }
3034 
3035   static ChildIteratorType child_begin(NodeRef N) {
3036     return {N->UserTreeIndices.begin(), N->Container};
3037   }
3038 
3039   static ChildIteratorType child_end(NodeRef N) {
3040     return {N->UserTreeIndices.end(), N->Container};
3041   }
3042 
3043   /// For the node iterator we just need to turn the TreeEntry iterator into a
3044   /// TreeEntry* iterator so that it dereferences to NodeRef.
3045   class nodes_iterator {
3046     using ItTy = ContainerTy::iterator;
3047     ItTy It;
3048 
3049   public:
3050     nodes_iterator(const ItTy &It2) : It(It2) {}
3051     NodeRef operator*() { return It->get(); }
3052     nodes_iterator operator++() {
3053       ++It;
3054       return *this;
3055     }
3056     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3057   };
3058 
3059   static nodes_iterator nodes_begin(BoUpSLP *R) {
3060     return nodes_iterator(R->VectorizableTree.begin());
3061   }
3062 
3063   static nodes_iterator nodes_end(BoUpSLP *R) {
3064     return nodes_iterator(R->VectorizableTree.end());
3065   }
3066 
3067   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3068 };
3069 
3070 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3071   using TreeEntry = BoUpSLP::TreeEntry;
3072 
3073   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3074 
3075   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3076     std::string Str;
3077     raw_string_ostream OS(Str);
3078     if (isSplat(Entry->Scalars))
3079       OS << "<splat> ";
3080     for (auto V : Entry->Scalars) {
3081       OS << *V;
3082       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3083             return EU.Scalar == V;
3084           }))
3085         OS << " <extract>";
3086       OS << "\n";
3087     }
3088     return Str;
3089   }
3090 
3091   static std::string getNodeAttributes(const TreeEntry *Entry,
3092                                        const BoUpSLP *) {
3093     if (Entry->State == TreeEntry::NeedToGather)
3094       return "color=red";
3095     return "";
3096   }
3097 };
3098 
3099 } // end namespace llvm
3100 
3101 BoUpSLP::~BoUpSLP() {
3102   if (MSSA) {
3103     MemorySSAUpdater MSSAU(MSSA);
3104     for (const auto &Pair : DeletedInstructions) {
3105       if (auto *Access = MSSA->getMemoryAccess(Pair.first))
3106         MSSAU.removeMemoryAccess(Access);
3107     }
3108   }
3109   for (const auto &Pair : DeletedInstructions) {
3110     // Replace operands of ignored instructions with Undefs in case if they were
3111     // marked for deletion.
3112     if (Pair.getSecond()) {
3113       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3114       Pair.getFirst()->replaceAllUsesWith(Undef);
3115     }
3116     Pair.getFirst()->dropAllReferences();
3117   }
3118   for (const auto &Pair : DeletedInstructions) {
3119     assert(Pair.getFirst()->use_empty() &&
3120            "trying to erase instruction with users.");
3121     Pair.getFirst()->eraseFromParent();
3122   }
3123 #ifdef EXPENSIVE_CHECKS
3124   // If we could guarantee that this call is not extremely slow, we could
3125   // remove the ifdef limitation (see PR47712).
3126   assert(!verifyFunction(*F, &dbgs()));
3127 #endif
3128 }
3129 
3130 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3131   for (auto *V : AV) {
3132     if (auto *I = dyn_cast<Instruction>(V))
3133       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3134   };
3135 }
3136 
3137 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3138 /// contains original mask for the scalars reused in the node. Procedure
3139 /// transform this mask in accordance with the given \p Mask.
3140 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3141   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3142          "Expected non-empty mask.");
3143   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3144   Prev.swap(Reuses);
3145   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3146     if (Mask[I] != UndefMaskElem)
3147       Reuses[Mask[I]] = Prev[I];
3148 }
3149 
3150 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3151 /// the original order of the scalars. Procedure transforms the provided order
3152 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3153 /// identity order, \p Order is cleared.
3154 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3155   assert(!Mask.empty() && "Expected non-empty mask.");
3156   SmallVector<int> MaskOrder;
3157   if (Order.empty()) {
3158     MaskOrder.resize(Mask.size());
3159     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3160   } else {
3161     inversePermutation(Order, MaskOrder);
3162   }
3163   reorderReuses(MaskOrder, Mask);
3164   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3165     Order.clear();
3166     return;
3167   }
3168   Order.assign(Mask.size(), Mask.size());
3169   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3170     if (MaskOrder[I] != UndefMaskElem)
3171       Order[MaskOrder[I]] = I;
3172   fixupOrderingIndices(Order);
3173 }
3174 
3175 Optional<BoUpSLP::OrdersType>
3176 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3177   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3178   unsigned NumScalars = TE.Scalars.size();
3179   OrdersType CurrentOrder(NumScalars, NumScalars);
3180   SmallVector<int> Positions;
3181   SmallBitVector UsedPositions(NumScalars);
3182   const TreeEntry *STE = nullptr;
3183   // Try to find all gathered scalars that are gets vectorized in other
3184   // vectorize node. Here we can have only one single tree vector node to
3185   // correctly identify order of the gathered scalars.
3186   for (unsigned I = 0; I < NumScalars; ++I) {
3187     Value *V = TE.Scalars[I];
3188     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3189       continue;
3190     if (const auto *LocalSTE = getTreeEntry(V)) {
3191       if (!STE)
3192         STE = LocalSTE;
3193       else if (STE != LocalSTE)
3194         // Take the order only from the single vector node.
3195         return None;
3196       unsigned Lane =
3197           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3198       if (Lane >= NumScalars)
3199         return None;
3200       if (CurrentOrder[Lane] != NumScalars) {
3201         if (Lane != I)
3202           continue;
3203         UsedPositions.reset(CurrentOrder[Lane]);
3204       }
3205       // The partial identity (where only some elements of the gather node are
3206       // in the identity order) is good.
3207       CurrentOrder[Lane] = I;
3208       UsedPositions.set(I);
3209     }
3210   }
3211   // Need to keep the order if we have a vector entry and at least 2 scalars or
3212   // the vectorized entry has just 2 scalars.
3213   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3214     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3215       for (unsigned I = 0; I < NumScalars; ++I)
3216         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3217           return false;
3218       return true;
3219     };
3220     if (IsIdentityOrder(CurrentOrder)) {
3221       CurrentOrder.clear();
3222       return CurrentOrder;
3223     }
3224     auto *It = CurrentOrder.begin();
3225     for (unsigned I = 0; I < NumScalars;) {
3226       if (UsedPositions.test(I)) {
3227         ++I;
3228         continue;
3229       }
3230       if (*It == NumScalars) {
3231         *It = I;
3232         ++I;
3233       }
3234       ++It;
3235     }
3236     return CurrentOrder;
3237   }
3238   return None;
3239 }
3240 
3241 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3242                                                          bool TopToBottom) {
3243   // No need to reorder if need to shuffle reuses, still need to shuffle the
3244   // node.
3245   if (!TE.ReuseShuffleIndices.empty())
3246     return None;
3247   if (TE.State == TreeEntry::Vectorize &&
3248       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3249        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3250       !TE.isAltShuffle())
3251     return TE.ReorderIndices;
3252   if (TE.State == TreeEntry::NeedToGather) {
3253     // TODO: add analysis of other gather nodes with extractelement
3254     // instructions and other values/instructions, not only undefs.
3255     if (((TE.getOpcode() == Instruction::ExtractElement &&
3256           !TE.isAltShuffle()) ||
3257          (all_of(TE.Scalars,
3258                  [](Value *V) {
3259                    return isa<UndefValue, ExtractElementInst>(V);
3260                  }) &&
3261           any_of(TE.Scalars,
3262                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3263         all_of(TE.Scalars,
3264                [](Value *V) {
3265                  auto *EE = dyn_cast<ExtractElementInst>(V);
3266                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3267                }) &&
3268         allSameType(TE.Scalars)) {
3269       // Check that gather of extractelements can be represented as
3270       // just a shuffle of a single vector.
3271       OrdersType CurrentOrder;
3272       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3273       if (Reuse || !CurrentOrder.empty()) {
3274         if (!CurrentOrder.empty())
3275           fixupOrderingIndices(CurrentOrder);
3276         return CurrentOrder;
3277       }
3278     }
3279     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3280       return CurrentOrder;
3281   }
3282   return None;
3283 }
3284 
3285 void BoUpSLP::reorderTopToBottom() {
3286   // Maps VF to the graph nodes.
3287   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3288   // ExtractElement gather nodes which can be vectorized and need to handle
3289   // their ordering.
3290   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3291   // Find all reorderable nodes with the given VF.
3292   // Currently the are vectorized stores,loads,extracts + some gathering of
3293   // extracts.
3294   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3295                                  const std::unique_ptr<TreeEntry> &TE) {
3296     if (Optional<OrdersType> CurrentOrder =
3297             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3298       // Do not include ordering for nodes used in the alt opcode vectorization,
3299       // better to reorder them during bottom-to-top stage. If follow the order
3300       // here, it causes reordering of the whole graph though actually it is
3301       // profitable just to reorder the subgraph that starts from the alternate
3302       // opcode vectorization node. Such nodes already end-up with the shuffle
3303       // instruction and it is just enough to change this shuffle rather than
3304       // rotate the scalars for the whole graph.
3305       unsigned Cnt = 0;
3306       const TreeEntry *UserTE = TE.get();
3307       while (UserTE && Cnt < RecursionMaxDepth) {
3308         if (UserTE->UserTreeIndices.size() != 1)
3309           break;
3310         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3311               return EI.UserTE->State == TreeEntry::Vectorize &&
3312                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3313             }))
3314           return;
3315         if (UserTE->UserTreeIndices.empty())
3316           UserTE = nullptr;
3317         else
3318           UserTE = UserTE->UserTreeIndices.back().UserTE;
3319         ++Cnt;
3320       }
3321       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3322       if (TE->State != TreeEntry::Vectorize)
3323         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3324     }
3325   });
3326 
3327   // Reorder the graph nodes according to their vectorization factor.
3328   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3329        VF /= 2) {
3330     auto It = VFToOrderedEntries.find(VF);
3331     if (It == VFToOrderedEntries.end())
3332       continue;
3333     // Try to find the most profitable order. We just are looking for the most
3334     // used order and reorder scalar elements in the nodes according to this
3335     // mostly used order.
3336     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3337     // All operands are reordered and used only in this node - propagate the
3338     // most used order to the user node.
3339     MapVector<OrdersType, unsigned,
3340               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3341         OrdersUses;
3342     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3343     for (const TreeEntry *OpTE : OrderedEntries) {
3344       // No need to reorder this nodes, still need to extend and to use shuffle,
3345       // just need to merge reordering shuffle and the reuse shuffle.
3346       if (!OpTE->ReuseShuffleIndices.empty())
3347         continue;
3348       // Count number of orders uses.
3349       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3350         if (OpTE->State == TreeEntry::NeedToGather)
3351           return GathersToOrders.find(OpTE)->second;
3352         return OpTE->ReorderIndices;
3353       }();
3354       // Stores actually store the mask, not the order, need to invert.
3355       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3356           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3357         SmallVector<int> Mask;
3358         inversePermutation(Order, Mask);
3359         unsigned E = Order.size();
3360         OrdersType CurrentOrder(E, E);
3361         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3362           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3363         });
3364         fixupOrderingIndices(CurrentOrder);
3365         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3366       } else {
3367         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3368       }
3369     }
3370     // Set order of the user node.
3371     if (OrdersUses.empty())
3372       continue;
3373     // Choose the most used order.
3374     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3375     unsigned Cnt = OrdersUses.front().second;
3376     for (const auto &Pair : drop_begin(OrdersUses)) {
3377       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3378         BestOrder = Pair.first;
3379         Cnt = Pair.second;
3380       }
3381     }
3382     // Set order of the user node.
3383     if (BestOrder.empty())
3384       continue;
3385     SmallVector<int> Mask;
3386     inversePermutation(BestOrder, Mask);
3387     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3388     unsigned E = BestOrder.size();
3389     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3390       return I < E ? static_cast<int>(I) : UndefMaskElem;
3391     });
3392     // Do an actual reordering, if profitable.
3393     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3394       // Just do the reordering for the nodes with the given VF.
3395       if (TE->Scalars.size() != VF) {
3396         if (TE->ReuseShuffleIndices.size() == VF) {
3397           // Need to reorder the reuses masks of the operands with smaller VF to
3398           // be able to find the match between the graph nodes and scalar
3399           // operands of the given node during vectorization/cost estimation.
3400           assert(all_of(TE->UserTreeIndices,
3401                         [VF, &TE](const EdgeInfo &EI) {
3402                           return EI.UserTE->Scalars.size() == VF ||
3403                                  EI.UserTE->Scalars.size() ==
3404                                      TE->Scalars.size();
3405                         }) &&
3406                  "All users must be of VF size.");
3407           // Update ordering of the operands with the smaller VF than the given
3408           // one.
3409           reorderReuses(TE->ReuseShuffleIndices, Mask);
3410         }
3411         continue;
3412       }
3413       if (TE->State == TreeEntry::Vectorize &&
3414           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3415               InsertElementInst>(TE->getMainOp()) &&
3416           !TE->isAltShuffle()) {
3417         // Build correct orders for extract{element,value}, loads and
3418         // stores.
3419         reorderOrder(TE->ReorderIndices, Mask);
3420         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3421           TE->reorderOperands(Mask);
3422       } else {
3423         // Reorder the node and its operands.
3424         TE->reorderOperands(Mask);
3425         assert(TE->ReorderIndices.empty() &&
3426                "Expected empty reorder sequence.");
3427         reorderScalars(TE->Scalars, Mask);
3428       }
3429       if (!TE->ReuseShuffleIndices.empty()) {
3430         // Apply reversed order to keep the original ordering of the reused
3431         // elements to avoid extra reorder indices shuffling.
3432         OrdersType CurrentOrder;
3433         reorderOrder(CurrentOrder, MaskOrder);
3434         SmallVector<int> NewReuses;
3435         inversePermutation(CurrentOrder, NewReuses);
3436         addMask(NewReuses, TE->ReuseShuffleIndices);
3437         TE->ReuseShuffleIndices.swap(NewReuses);
3438       }
3439     }
3440   }
3441 }
3442 
3443 bool BoUpSLP::canReorderOperands(
3444     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3445     ArrayRef<TreeEntry *> ReorderableGathers,
3446     SmallVectorImpl<TreeEntry *> &GatherOps) {
3447   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3448     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3449           return OpData.first == I &&
3450                  OpData.second->State == TreeEntry::Vectorize;
3451         }))
3452       continue;
3453     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3454       // Do not reorder if operand node is used by many user nodes.
3455       if (any_of(TE->UserTreeIndices,
3456                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3457         return false;
3458       // Add the node to the list of the ordered nodes with the identity
3459       // order.
3460       Edges.emplace_back(I, TE);
3461       continue;
3462     }
3463     ArrayRef<Value *> VL = UserTE->getOperand(I);
3464     TreeEntry *Gather = nullptr;
3465     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3466           assert(TE->State != TreeEntry::Vectorize &&
3467                  "Only non-vectorized nodes are expected.");
3468           if (TE->isSame(VL)) {
3469             Gather = TE;
3470             return true;
3471           }
3472           return false;
3473         }) > 1)
3474       return false;
3475     if (Gather)
3476       GatherOps.push_back(Gather);
3477   }
3478   return true;
3479 }
3480 
3481 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3482   SetVector<TreeEntry *> OrderedEntries;
3483   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3484   // Find all reorderable leaf nodes with the given VF.
3485   // Currently the are vectorized loads,extracts without alternate operands +
3486   // some gathering of extracts.
3487   SmallVector<TreeEntry *> NonVectorized;
3488   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3489                               &NonVectorized](
3490                                  const std::unique_ptr<TreeEntry> &TE) {
3491     if (TE->State != TreeEntry::Vectorize)
3492       NonVectorized.push_back(TE.get());
3493     if (Optional<OrdersType> CurrentOrder =
3494             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3495       OrderedEntries.insert(TE.get());
3496       if (TE->State != TreeEntry::Vectorize)
3497         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3498     }
3499   });
3500 
3501   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3502   // I.e., if the node has operands, that are reordered, try to make at least
3503   // one operand order in the natural order and reorder others + reorder the
3504   // user node itself.
3505   SmallPtrSet<const TreeEntry *, 4> Visited;
3506   while (!OrderedEntries.empty()) {
3507     // 1. Filter out only reordered nodes.
3508     // 2. If the entry has multiple uses - skip it and jump to the next node.
3509     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3510     SmallVector<TreeEntry *> Filtered;
3511     for (TreeEntry *TE : OrderedEntries) {
3512       if (!(TE->State == TreeEntry::Vectorize ||
3513             (TE->State == TreeEntry::NeedToGather &&
3514              GathersToOrders.count(TE))) ||
3515           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3516           !all_of(drop_begin(TE->UserTreeIndices),
3517                   [TE](const EdgeInfo &EI) {
3518                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3519                   }) ||
3520           !Visited.insert(TE).second) {
3521         Filtered.push_back(TE);
3522         continue;
3523       }
3524       // Build a map between user nodes and their operands order to speedup
3525       // search. The graph currently does not provide this dependency directly.
3526       for (EdgeInfo &EI : TE->UserTreeIndices) {
3527         TreeEntry *UserTE = EI.UserTE;
3528         auto It = Users.find(UserTE);
3529         if (It == Users.end())
3530           It = Users.insert({UserTE, {}}).first;
3531         It->second.emplace_back(EI.EdgeIdx, TE);
3532       }
3533     }
3534     // Erase filtered entries.
3535     for_each(Filtered,
3536              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3537     for (auto &Data : Users) {
3538       // Check that operands are used only in the User node.
3539       SmallVector<TreeEntry *> GatherOps;
3540       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3541                               GatherOps)) {
3542         for_each(Data.second,
3543                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3544                    OrderedEntries.remove(Op.second);
3545                  });
3546         continue;
3547       }
3548       // All operands are reordered and used only in this node - propagate the
3549       // most used order to the user node.
3550       MapVector<OrdersType, unsigned,
3551                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3552           OrdersUses;
3553       // Do the analysis for each tree entry only once, otherwise the order of
3554       // the same node my be considered several times, though might be not
3555       // profitable.
3556       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3557       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3558       for (const auto &Op : Data.second) {
3559         TreeEntry *OpTE = Op.second;
3560         if (!VisitedOps.insert(OpTE).second)
3561           continue;
3562         if (!OpTE->ReuseShuffleIndices.empty() ||
3563             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3564           continue;
3565         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3566           if (OpTE->State == TreeEntry::NeedToGather)
3567             return GathersToOrders.find(OpTE)->second;
3568           return OpTE->ReorderIndices;
3569         }();
3570         unsigned NumOps = count_if(
3571             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3572               return P.second == OpTE;
3573             });
3574         // Stores actually store the mask, not the order, need to invert.
3575         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3576             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3577           SmallVector<int> Mask;
3578           inversePermutation(Order, Mask);
3579           unsigned E = Order.size();
3580           OrdersType CurrentOrder(E, E);
3581           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3582             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3583           });
3584           fixupOrderingIndices(CurrentOrder);
3585           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3586               NumOps;
3587         } else {
3588           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3589         }
3590         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3591         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3592                                             const TreeEntry *TE) {
3593           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3594               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3595               (IgnoreReorder && TE->Idx == 0))
3596             return true;
3597           if (TE->State == TreeEntry::NeedToGather) {
3598             auto It = GathersToOrders.find(TE);
3599             if (It != GathersToOrders.end())
3600               return !It->second.empty();
3601             return true;
3602           }
3603           return false;
3604         };
3605         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3606           TreeEntry *UserTE = EI.UserTE;
3607           if (!VisitedUsers.insert(UserTE).second)
3608             continue;
3609           // May reorder user node if it requires reordering, has reused
3610           // scalars, is an alternate op vectorize node or its op nodes require
3611           // reordering.
3612           if (AllowsReordering(UserTE))
3613             continue;
3614           // Check if users allow reordering.
3615           // Currently look up just 1 level of operands to avoid increase of
3616           // the compile time.
3617           // Profitable to reorder if definitely more operands allow
3618           // reordering rather than those with natural order.
3619           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3620           if (static_cast<unsigned>(count_if(
3621                   Ops, [UserTE, &AllowsReordering](
3622                            const std::pair<unsigned, TreeEntry *> &Op) {
3623                     return AllowsReordering(Op.second) &&
3624                            all_of(Op.second->UserTreeIndices,
3625                                   [UserTE](const EdgeInfo &EI) {
3626                                     return EI.UserTE == UserTE;
3627                                   });
3628                   })) <= Ops.size() / 2)
3629             ++Res.first->second;
3630         }
3631       }
3632       // If no orders - skip current nodes and jump to the next one, if any.
3633       if (OrdersUses.empty()) {
3634         for_each(Data.second,
3635                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3636                    OrderedEntries.remove(Op.second);
3637                  });
3638         continue;
3639       }
3640       // Choose the best order.
3641       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3642       unsigned Cnt = OrdersUses.front().second;
3643       for (const auto &Pair : drop_begin(OrdersUses)) {
3644         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3645           BestOrder = Pair.first;
3646           Cnt = Pair.second;
3647         }
3648       }
3649       // Set order of the user node (reordering of operands and user nodes).
3650       if (BestOrder.empty()) {
3651         for_each(Data.second,
3652                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3653                    OrderedEntries.remove(Op.second);
3654                  });
3655         continue;
3656       }
3657       // Erase operands from OrderedEntries list and adjust their orders.
3658       VisitedOps.clear();
3659       SmallVector<int> Mask;
3660       inversePermutation(BestOrder, Mask);
3661       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3662       unsigned E = BestOrder.size();
3663       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3664         return I < E ? static_cast<int>(I) : UndefMaskElem;
3665       });
3666       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3667         TreeEntry *TE = Op.second;
3668         OrderedEntries.remove(TE);
3669         if (!VisitedOps.insert(TE).second)
3670           continue;
3671         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3672           // Just reorder reuses indices.
3673           reorderReuses(TE->ReuseShuffleIndices, Mask);
3674           continue;
3675         }
3676         // Gathers are processed separately.
3677         if (TE->State != TreeEntry::Vectorize)
3678           continue;
3679         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3680                 TE->ReorderIndices.empty()) &&
3681                "Non-matching sizes of user/operand entries.");
3682         reorderOrder(TE->ReorderIndices, Mask);
3683       }
3684       // For gathers just need to reorder its scalars.
3685       for (TreeEntry *Gather : GatherOps) {
3686         assert(Gather->ReorderIndices.empty() &&
3687                "Unexpected reordering of gathers.");
3688         if (!Gather->ReuseShuffleIndices.empty()) {
3689           // Just reorder reuses indices.
3690           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3691           continue;
3692         }
3693         reorderScalars(Gather->Scalars, Mask);
3694         OrderedEntries.remove(Gather);
3695       }
3696       // Reorder operands of the user node and set the ordering for the user
3697       // node itself.
3698       if (Data.first->State != TreeEntry::Vectorize ||
3699           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3700               Data.first->getMainOp()) ||
3701           Data.first->isAltShuffle())
3702         Data.first->reorderOperands(Mask);
3703       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3704           Data.first->isAltShuffle()) {
3705         reorderScalars(Data.first->Scalars, Mask);
3706         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3707         if (Data.first->ReuseShuffleIndices.empty() &&
3708             !Data.first->ReorderIndices.empty() &&
3709             !Data.first->isAltShuffle()) {
3710           // Insert user node to the list to try to sink reordering deeper in
3711           // the graph.
3712           OrderedEntries.insert(Data.first);
3713         }
3714       } else {
3715         reorderOrder(Data.first->ReorderIndices, Mask);
3716       }
3717     }
3718   }
3719   // If the reordering is unnecessary, just remove the reorder.
3720   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3721       VectorizableTree.front()->ReuseShuffleIndices.empty())
3722     VectorizableTree.front()->ReorderIndices.clear();
3723 }
3724 
3725 void BoUpSLP::buildExternalUses(
3726     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3727   // Collect the values that we need to extract from the tree.
3728   for (auto &TEPtr : VectorizableTree) {
3729     TreeEntry *Entry = TEPtr.get();
3730 
3731     // No need to handle users of gathered values.
3732     if (Entry->State == TreeEntry::NeedToGather)
3733       continue;
3734 
3735     // For each lane:
3736     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3737       Value *Scalar = Entry->Scalars[Lane];
3738       int FoundLane = Entry->findLaneForValue(Scalar);
3739 
3740       // Check if the scalar is externally used as an extra arg.
3741       auto ExtI = ExternallyUsedValues.find(Scalar);
3742       if (ExtI != ExternallyUsedValues.end()) {
3743         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3744                           << Lane << " from " << *Scalar << ".\n");
3745         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3746       }
3747       for (User *U : Scalar->users()) {
3748         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3749 
3750         Instruction *UserInst = dyn_cast<Instruction>(U);
3751         if (!UserInst)
3752           continue;
3753 
3754         if (isDeleted(UserInst))
3755           continue;
3756 
3757         // Skip in-tree scalars that become vectors
3758         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3759           Value *UseScalar = UseEntry->Scalars[0];
3760           // Some in-tree scalars will remain as scalar in vectorized
3761           // instructions. If that is the case, the one in Lane 0 will
3762           // be used.
3763           if (UseScalar != U ||
3764               UseEntry->State == TreeEntry::ScatterVectorize ||
3765               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3766             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3767                               << ".\n");
3768             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3769             continue;
3770           }
3771         }
3772 
3773         // Ignore users in the user ignore list.
3774         if (is_contained(UserIgnoreList, UserInst))
3775           continue;
3776 
3777         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3778                           << Lane << " from " << *Scalar << ".\n");
3779         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3780       }
3781     }
3782   }
3783 }
3784 
3785 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3786                         ArrayRef<Value *> UserIgnoreLst) {
3787   deleteTree();
3788   UserIgnoreList = UserIgnoreLst;
3789   if (!allSameType(Roots))
3790     return;
3791   buildTree_rec(Roots, 0, EdgeInfo());
3792 }
3793 
3794 namespace {
3795 /// Tracks the state we can represent the loads in the given sequence.
3796 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3797 } // anonymous namespace
3798 
3799 /// Checks if the given array of loads can be represented as a vectorized,
3800 /// scatter or just simple gather.
3801 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3802                                     const TargetTransformInfo &TTI,
3803                                     const DataLayout &DL, ScalarEvolution &SE,
3804                                     SmallVectorImpl<unsigned> &Order,
3805                                     SmallVectorImpl<Value *> &PointerOps) {
3806   // Check that a vectorized load would load the same memory as a scalar
3807   // load. For example, we don't want to vectorize loads that are smaller
3808   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3809   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3810   // from such a struct, we read/write packed bits disagreeing with the
3811   // unvectorized version.
3812   Type *ScalarTy = VL0->getType();
3813 
3814   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3815     return LoadsState::Gather;
3816 
3817   // Make sure all loads in the bundle are simple - we can't vectorize
3818   // atomic or volatile loads.
3819   PointerOps.clear();
3820   PointerOps.resize(VL.size());
3821   auto *POIter = PointerOps.begin();
3822   for (Value *V : VL) {
3823     auto *L = cast<LoadInst>(V);
3824     if (!L->isSimple())
3825       return LoadsState::Gather;
3826     *POIter = L->getPointerOperand();
3827     ++POIter;
3828   }
3829 
3830   Order.clear();
3831   // Check the order of pointer operands.
3832   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3833     Value *Ptr0;
3834     Value *PtrN;
3835     if (Order.empty()) {
3836       Ptr0 = PointerOps.front();
3837       PtrN = PointerOps.back();
3838     } else {
3839       Ptr0 = PointerOps[Order.front()];
3840       PtrN = PointerOps[Order.back()];
3841     }
3842     Optional<int> Diff =
3843         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3844     // Check that the sorted loads are consecutive.
3845     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3846       return LoadsState::Vectorize;
3847     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3848     for (Value *V : VL)
3849       CommonAlignment =
3850           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3851     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3852                                 CommonAlignment))
3853       return LoadsState::ScatterVectorize;
3854   }
3855 
3856   return LoadsState::Gather;
3857 }
3858 
3859 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3860                             const EdgeInfo &UserTreeIdx) {
3861   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3862 
3863   SmallVector<int> ReuseShuffleIndicies;
3864   SmallVector<Value *> UniqueValues;
3865   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3866                                 &UserTreeIdx,
3867                                 this](const InstructionsState &S) {
3868     // Check that every instruction appears once in this bundle.
3869     DenseMap<Value *, unsigned> UniquePositions;
3870     for (Value *V : VL) {
3871       if (isConstant(V)) {
3872         ReuseShuffleIndicies.emplace_back(
3873             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3874         UniqueValues.emplace_back(V);
3875         continue;
3876       }
3877       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3878       ReuseShuffleIndicies.emplace_back(Res.first->second);
3879       if (Res.second)
3880         UniqueValues.emplace_back(V);
3881     }
3882     size_t NumUniqueScalarValues = UniqueValues.size();
3883     if (NumUniqueScalarValues == VL.size()) {
3884       ReuseShuffleIndicies.clear();
3885     } else {
3886       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3887       if (NumUniqueScalarValues <= 1 ||
3888           (UniquePositions.size() == 1 && all_of(UniqueValues,
3889                                                  [](Value *V) {
3890                                                    return isa<UndefValue>(V) ||
3891                                                           !isConstant(V);
3892                                                  })) ||
3893           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3894         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3895         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3896         return false;
3897       }
3898       VL = UniqueValues;
3899     }
3900     return true;
3901   };
3902 
3903   InstructionsState S = getSameOpcode(VL);
3904   if (Depth == RecursionMaxDepth) {
3905     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3906     if (TryToFindDuplicates(S))
3907       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3908                    ReuseShuffleIndicies);
3909     return;
3910   }
3911 
3912   // Don't handle scalable vectors
3913   if (S.getOpcode() == Instruction::ExtractElement &&
3914       isa<ScalableVectorType>(
3915           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3916     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3917     if (TryToFindDuplicates(S))
3918       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3919                    ReuseShuffleIndicies);
3920     return;
3921   }
3922 
3923   // Don't handle vectors.
3924   if (S.OpValue->getType()->isVectorTy() &&
3925       !isa<InsertElementInst>(S.OpValue)) {
3926     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3927     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3928     return;
3929   }
3930 
3931   // Avoid attempting to schedule allocas; there are unmodeled dependencies
3932   // for "static" alloca status and for reordering with stacksave calls.
3933   for (Value *V : VL) {
3934     if (isa<AllocaInst>(V)) {
3935       LLVM_DEBUG(dbgs() << "SLP: Gathering due to alloca.\n");
3936       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3937       return;
3938     }
3939   }
3940 
3941   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3942     if (SI->getValueOperand()->getType()->isVectorTy()) {
3943       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3944       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3945       return;
3946     }
3947 
3948   // If all of the operands are identical or constant we have a simple solution.
3949   // If we deal with insert/extract instructions, they all must have constant
3950   // indices, otherwise we should gather them, not try to vectorize.
3951   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3952       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3953        !all_of(VL, isVectorLikeInstWithConstOps))) {
3954     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3955     if (TryToFindDuplicates(S))
3956       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3957                    ReuseShuffleIndicies);
3958     return;
3959   }
3960 
3961   // We now know that this is a vector of instructions of the same type from
3962   // the same block.
3963 
3964   // Don't vectorize ephemeral values.
3965   for (Value *V : VL) {
3966     if (EphValues.count(V)) {
3967       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3968                         << ") is ephemeral.\n");
3969       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3970       return;
3971     }
3972   }
3973 
3974   // Check if this is a duplicate of another entry.
3975   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3976     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3977     if (!E->isSame(VL)) {
3978       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3979       if (TryToFindDuplicates(S))
3980         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3981                      ReuseShuffleIndicies);
3982       return;
3983     }
3984     // Record the reuse of the tree node.  FIXME, currently this is only used to
3985     // properly draw the graph rather than for the actual vectorization.
3986     E->UserTreeIndices.push_back(UserTreeIdx);
3987     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3988                       << ".\n");
3989     return;
3990   }
3991 
3992   // Check that none of the instructions in the bundle are already in the tree.
3993   for (Value *V : VL) {
3994     auto *I = dyn_cast<Instruction>(V);
3995     if (!I)
3996       continue;
3997     if (getTreeEntry(I)) {
3998       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3999                         << ") is already in tree.\n");
4000       if (TryToFindDuplicates(S))
4001         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4002                      ReuseShuffleIndicies);
4003       return;
4004     }
4005   }
4006 
4007   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4008   for (Value *V : VL) {
4009     if (is_contained(UserIgnoreList, V)) {
4010       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4011       if (TryToFindDuplicates(S))
4012         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4013                      ReuseShuffleIndicies);
4014       return;
4015     }
4016   }
4017 
4018   // Check that all of the users of the scalars that we want to vectorize are
4019   // schedulable.
4020   auto *VL0 = cast<Instruction>(S.OpValue);
4021   BasicBlock *BB = VL0->getParent();
4022 
4023   if (!DT->isReachableFromEntry(BB)) {
4024     // Don't go into unreachable blocks. They may contain instructions with
4025     // dependency cycles which confuse the final scheduling.
4026     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4027     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4028     return;
4029   }
4030 
4031   // Check that every instruction appears once in this bundle.
4032   if (!TryToFindDuplicates(S))
4033     return;
4034 
4035   auto &BSRef = BlocksSchedules[BB];
4036   if (!BSRef)
4037     BSRef = std::make_unique<BlockScheduling>(BB);
4038 
4039   BlockScheduling &BS = *BSRef.get();
4040 
4041   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4042 #ifdef EXPENSIVE_CHECKS
4043   // Make sure we didn't break any internal invariants
4044   BS.verify();
4045 #endif
4046   if (!Bundle) {
4047     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4048     assert((!BS.getScheduleData(VL0) ||
4049             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4050            "tryScheduleBundle should cancelScheduling on failure");
4051     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4052                  ReuseShuffleIndicies);
4053     return;
4054   }
4055   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4056 
4057   unsigned ShuffleOrOp = S.isAltShuffle() ?
4058                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4059   switch (ShuffleOrOp) {
4060     case Instruction::PHI: {
4061       auto *PH = cast<PHINode>(VL0);
4062 
4063       // Check for terminator values (e.g. invoke).
4064       for (Value *V : VL)
4065         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4066           Instruction *Term = dyn_cast<Instruction>(Incoming);
4067           if (Term && Term->isTerminator()) {
4068             LLVM_DEBUG(dbgs()
4069                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4070             BS.cancelScheduling(VL, VL0);
4071             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4072                          ReuseShuffleIndicies);
4073             return;
4074           }
4075         }
4076 
4077       TreeEntry *TE =
4078           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4079       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4080 
4081       // Keeps the reordered operands to avoid code duplication.
4082       SmallVector<ValueList, 2> OperandsVec;
4083       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4084         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4085           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4086           TE->setOperand(I, Operands);
4087           OperandsVec.push_back(Operands);
4088           continue;
4089         }
4090         ValueList Operands;
4091         // Prepare the operand vector.
4092         for (Value *V : VL)
4093           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4094               PH->getIncomingBlock(I)));
4095         TE->setOperand(I, Operands);
4096         OperandsVec.push_back(Operands);
4097       }
4098       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4099         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4100       return;
4101     }
4102     case Instruction::ExtractValue:
4103     case Instruction::ExtractElement: {
4104       OrdersType CurrentOrder;
4105       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4106       if (Reuse) {
4107         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4108         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4109                      ReuseShuffleIndicies);
4110         // This is a special case, as it does not gather, but at the same time
4111         // we are not extending buildTree_rec() towards the operands.
4112         ValueList Op0;
4113         Op0.assign(VL.size(), VL0->getOperand(0));
4114         VectorizableTree.back()->setOperand(0, Op0);
4115         return;
4116       }
4117       if (!CurrentOrder.empty()) {
4118         LLVM_DEBUG({
4119           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4120                     "with order";
4121           for (unsigned Idx : CurrentOrder)
4122             dbgs() << " " << Idx;
4123           dbgs() << "\n";
4124         });
4125         fixupOrderingIndices(CurrentOrder);
4126         // Insert new order with initial value 0, if it does not exist,
4127         // otherwise return the iterator to the existing one.
4128         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4129                      ReuseShuffleIndicies, CurrentOrder);
4130         // This is a special case, as it does not gather, but at the same time
4131         // we are not extending buildTree_rec() towards the operands.
4132         ValueList Op0;
4133         Op0.assign(VL.size(), VL0->getOperand(0));
4134         VectorizableTree.back()->setOperand(0, Op0);
4135         return;
4136       }
4137       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4138       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4139                    ReuseShuffleIndicies);
4140       BS.cancelScheduling(VL, VL0);
4141       return;
4142     }
4143     case Instruction::InsertElement: {
4144       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4145 
4146       // Check that we have a buildvector and not a shuffle of 2 or more
4147       // different vectors.
4148       ValueSet SourceVectors;
4149       for (Value *V : VL) {
4150         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4151         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4152       }
4153 
4154       if (count_if(VL, [&SourceVectors](Value *V) {
4155             return !SourceVectors.contains(V);
4156           }) >= 2) {
4157         // Found 2nd source vector - cancel.
4158         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4159                              "different source vectors.\n");
4160         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4161         BS.cancelScheduling(VL, VL0);
4162         return;
4163       }
4164 
4165       auto OrdCompare = [](const std::pair<int, int> &P1,
4166                            const std::pair<int, int> &P2) {
4167         return P1.first > P2.first;
4168       };
4169       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4170                     decltype(OrdCompare)>
4171           Indices(OrdCompare);
4172       for (int I = 0, E = VL.size(); I < E; ++I) {
4173         unsigned Idx = *getInsertIndex(VL[I]);
4174         Indices.emplace(Idx, I);
4175       }
4176       OrdersType CurrentOrder(VL.size(), VL.size());
4177       bool IsIdentity = true;
4178       for (int I = 0, E = VL.size(); I < E; ++I) {
4179         CurrentOrder[Indices.top().second] = I;
4180         IsIdentity &= Indices.top().second == I;
4181         Indices.pop();
4182       }
4183       if (IsIdentity)
4184         CurrentOrder.clear();
4185       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4186                                    None, CurrentOrder);
4187       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4188 
4189       constexpr int NumOps = 2;
4190       ValueList VectorOperands[NumOps];
4191       for (int I = 0; I < NumOps; ++I) {
4192         for (Value *V : VL)
4193           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4194 
4195         TE->setOperand(I, VectorOperands[I]);
4196       }
4197       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4198       return;
4199     }
4200     case Instruction::Load: {
4201       // Check that a vectorized load would load the same memory as a scalar
4202       // load. For example, we don't want to vectorize loads that are smaller
4203       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4204       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4205       // from such a struct, we read/write packed bits disagreeing with the
4206       // unvectorized version.
4207       SmallVector<Value *> PointerOps;
4208       OrdersType CurrentOrder;
4209       TreeEntry *TE = nullptr;
4210       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4211                                 PointerOps)) {
4212       case LoadsState::Vectorize:
4213         if (CurrentOrder.empty()) {
4214           // Original loads are consecutive and does not require reordering.
4215           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4216                             ReuseShuffleIndicies);
4217           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4218         } else {
4219           fixupOrderingIndices(CurrentOrder);
4220           // Need to reorder.
4221           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4222                             ReuseShuffleIndicies, CurrentOrder);
4223           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4224         }
4225         TE->setOperandsInOrder();
4226         break;
4227       case LoadsState::ScatterVectorize:
4228         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4229         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4230                           UserTreeIdx, ReuseShuffleIndicies);
4231         TE->setOperandsInOrder();
4232         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4233         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4234         break;
4235       case LoadsState::Gather:
4236         BS.cancelScheduling(VL, VL0);
4237         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4238                      ReuseShuffleIndicies);
4239 #ifndef NDEBUG
4240         Type *ScalarTy = VL0->getType();
4241         if (DL->getTypeSizeInBits(ScalarTy) !=
4242             DL->getTypeAllocSizeInBits(ScalarTy))
4243           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4244         else if (any_of(VL, [](Value *V) {
4245                    return !cast<LoadInst>(V)->isSimple();
4246                  }))
4247           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4248         else
4249           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4250 #endif // NDEBUG
4251         break;
4252       }
4253       return;
4254     }
4255     case Instruction::ZExt:
4256     case Instruction::SExt:
4257     case Instruction::FPToUI:
4258     case Instruction::FPToSI:
4259     case Instruction::FPExt:
4260     case Instruction::PtrToInt:
4261     case Instruction::IntToPtr:
4262     case Instruction::SIToFP:
4263     case Instruction::UIToFP:
4264     case Instruction::Trunc:
4265     case Instruction::FPTrunc:
4266     case Instruction::BitCast: {
4267       Type *SrcTy = VL0->getOperand(0)->getType();
4268       for (Value *V : VL) {
4269         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4270         if (Ty != SrcTy || !isValidElementType(Ty)) {
4271           BS.cancelScheduling(VL, VL0);
4272           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4273                        ReuseShuffleIndicies);
4274           LLVM_DEBUG(dbgs()
4275                      << "SLP: Gathering casts with different src types.\n");
4276           return;
4277         }
4278       }
4279       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4280                                    ReuseShuffleIndicies);
4281       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4282 
4283       TE->setOperandsInOrder();
4284       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4285         ValueList Operands;
4286         // Prepare the operand vector.
4287         for (Value *V : VL)
4288           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4289 
4290         buildTree_rec(Operands, Depth + 1, {TE, i});
4291       }
4292       return;
4293     }
4294     case Instruction::ICmp:
4295     case Instruction::FCmp: {
4296       // Check that all of the compares have the same predicate.
4297       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4298       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4299       Type *ComparedTy = VL0->getOperand(0)->getType();
4300       for (Value *V : VL) {
4301         CmpInst *Cmp = cast<CmpInst>(V);
4302         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4303             Cmp->getOperand(0)->getType() != ComparedTy) {
4304           BS.cancelScheduling(VL, VL0);
4305           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4306                        ReuseShuffleIndicies);
4307           LLVM_DEBUG(dbgs()
4308                      << "SLP: Gathering cmp with different predicate.\n");
4309           return;
4310         }
4311       }
4312 
4313       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4314                                    ReuseShuffleIndicies);
4315       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4316 
4317       ValueList Left, Right;
4318       if (cast<CmpInst>(VL0)->isCommutative()) {
4319         // Commutative predicate - collect + sort operands of the instructions
4320         // so that each side is more likely to have the same opcode.
4321         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4322         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4323       } else {
4324         // Collect operands - commute if it uses the swapped predicate.
4325         for (Value *V : VL) {
4326           auto *Cmp = cast<CmpInst>(V);
4327           Value *LHS = Cmp->getOperand(0);
4328           Value *RHS = Cmp->getOperand(1);
4329           if (Cmp->getPredicate() != P0)
4330             std::swap(LHS, RHS);
4331           Left.push_back(LHS);
4332           Right.push_back(RHS);
4333         }
4334       }
4335       TE->setOperand(0, Left);
4336       TE->setOperand(1, Right);
4337       buildTree_rec(Left, Depth + 1, {TE, 0});
4338       buildTree_rec(Right, Depth + 1, {TE, 1});
4339       return;
4340     }
4341     case Instruction::Select:
4342     case Instruction::FNeg:
4343     case Instruction::Add:
4344     case Instruction::FAdd:
4345     case Instruction::Sub:
4346     case Instruction::FSub:
4347     case Instruction::Mul:
4348     case Instruction::FMul:
4349     case Instruction::UDiv:
4350     case Instruction::SDiv:
4351     case Instruction::FDiv:
4352     case Instruction::URem:
4353     case Instruction::SRem:
4354     case Instruction::FRem:
4355     case Instruction::Shl:
4356     case Instruction::LShr:
4357     case Instruction::AShr:
4358     case Instruction::And:
4359     case Instruction::Or:
4360     case Instruction::Xor: {
4361       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4362                                    ReuseShuffleIndicies);
4363       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4364 
4365       // Sort operands of the instructions so that each side is more likely to
4366       // have the same opcode.
4367       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4368         ValueList Left, Right;
4369         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4370         TE->setOperand(0, Left);
4371         TE->setOperand(1, Right);
4372         buildTree_rec(Left, Depth + 1, {TE, 0});
4373         buildTree_rec(Right, Depth + 1, {TE, 1});
4374         return;
4375       }
4376 
4377       TE->setOperandsInOrder();
4378       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4379         ValueList Operands;
4380         // Prepare the operand vector.
4381         for (Value *V : VL)
4382           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4383 
4384         buildTree_rec(Operands, Depth + 1, {TE, i});
4385       }
4386       return;
4387     }
4388     case Instruction::GetElementPtr: {
4389       // We don't combine GEPs with complicated (nested) indexing.
4390       for (Value *V : VL) {
4391         if (cast<Instruction>(V)->getNumOperands() != 2) {
4392           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4393           BS.cancelScheduling(VL, VL0);
4394           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4395                        ReuseShuffleIndicies);
4396           return;
4397         }
4398       }
4399 
4400       // We can't combine several GEPs into one vector if they operate on
4401       // different types.
4402       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4403       for (Value *V : VL) {
4404         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4405         if (Ty0 != CurTy) {
4406           LLVM_DEBUG(dbgs()
4407                      << "SLP: not-vectorizable GEP (different types).\n");
4408           BS.cancelScheduling(VL, VL0);
4409           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4410                        ReuseShuffleIndicies);
4411           return;
4412         }
4413       }
4414 
4415       // We don't combine GEPs with non-constant indexes.
4416       Type *Ty1 = VL0->getOperand(1)->getType();
4417       for (Value *V : VL) {
4418         auto Op = cast<Instruction>(V)->getOperand(1);
4419         if (!isa<ConstantInt>(Op) ||
4420             (Op->getType() != Ty1 &&
4421              Op->getType()->getScalarSizeInBits() >
4422                  DL->getIndexSizeInBits(
4423                      V->getType()->getPointerAddressSpace()))) {
4424           LLVM_DEBUG(dbgs()
4425                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4426           BS.cancelScheduling(VL, VL0);
4427           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4428                        ReuseShuffleIndicies);
4429           return;
4430         }
4431       }
4432 
4433       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4434                                    ReuseShuffleIndicies);
4435       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4436       SmallVector<ValueList, 2> Operands(2);
4437       // Prepare the operand vector for pointer operands.
4438       for (Value *V : VL)
4439         Operands.front().push_back(
4440             cast<GetElementPtrInst>(V)->getPointerOperand());
4441       TE->setOperand(0, Operands.front());
4442       // Need to cast all indices to the same type before vectorization to
4443       // avoid crash.
4444       // Required to be able to find correct matches between different gather
4445       // nodes and reuse the vectorized values rather than trying to gather them
4446       // again.
4447       int IndexIdx = 1;
4448       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4449       Type *Ty = all_of(VL,
4450                         [VL0Ty, IndexIdx](Value *V) {
4451                           return VL0Ty == cast<GetElementPtrInst>(V)
4452                                               ->getOperand(IndexIdx)
4453                                               ->getType();
4454                         })
4455                      ? VL0Ty
4456                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4457                                             ->getPointerOperandType()
4458                                             ->getScalarType());
4459       // Prepare the operand vector.
4460       for (Value *V : VL) {
4461         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4462         auto *CI = cast<ConstantInt>(Op);
4463         Operands.back().push_back(ConstantExpr::getIntegerCast(
4464             CI, Ty, CI->getValue().isSignBitSet()));
4465       }
4466       TE->setOperand(IndexIdx, Operands.back());
4467 
4468       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4469         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4470       return;
4471     }
4472     case Instruction::Store: {
4473       // Check if the stores are consecutive or if we need to swizzle them.
4474       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4475       // Avoid types that are padded when being allocated as scalars, while
4476       // being packed together in a vector (such as i1).
4477       if (DL->getTypeSizeInBits(ScalarTy) !=
4478           DL->getTypeAllocSizeInBits(ScalarTy)) {
4479         BS.cancelScheduling(VL, VL0);
4480         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4481                      ReuseShuffleIndicies);
4482         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4483         return;
4484       }
4485       // Make sure all stores in the bundle are simple - we can't vectorize
4486       // atomic or volatile stores.
4487       SmallVector<Value *, 4> PointerOps(VL.size());
4488       ValueList Operands(VL.size());
4489       auto POIter = PointerOps.begin();
4490       auto OIter = Operands.begin();
4491       for (Value *V : VL) {
4492         auto *SI = cast<StoreInst>(V);
4493         if (!SI->isSimple()) {
4494           BS.cancelScheduling(VL, VL0);
4495           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4496                        ReuseShuffleIndicies);
4497           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4498           return;
4499         }
4500         *POIter = SI->getPointerOperand();
4501         *OIter = SI->getValueOperand();
4502         ++POIter;
4503         ++OIter;
4504       }
4505 
4506       OrdersType CurrentOrder;
4507       // Check the order of pointer operands.
4508       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4509         Value *Ptr0;
4510         Value *PtrN;
4511         if (CurrentOrder.empty()) {
4512           Ptr0 = PointerOps.front();
4513           PtrN = PointerOps.back();
4514         } else {
4515           Ptr0 = PointerOps[CurrentOrder.front()];
4516           PtrN = PointerOps[CurrentOrder.back()];
4517         }
4518         Optional<int> Dist =
4519             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4520         // Check that the sorted pointer operands are consecutive.
4521         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4522           if (CurrentOrder.empty()) {
4523             // Original stores are consecutive and does not require reordering.
4524             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4525                                          UserTreeIdx, ReuseShuffleIndicies);
4526             TE->setOperandsInOrder();
4527             buildTree_rec(Operands, Depth + 1, {TE, 0});
4528             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4529           } else {
4530             fixupOrderingIndices(CurrentOrder);
4531             TreeEntry *TE =
4532                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4533                              ReuseShuffleIndicies, CurrentOrder);
4534             TE->setOperandsInOrder();
4535             buildTree_rec(Operands, Depth + 1, {TE, 0});
4536             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4537           }
4538           return;
4539         }
4540       }
4541 
4542       BS.cancelScheduling(VL, VL0);
4543       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4544                    ReuseShuffleIndicies);
4545       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4546       return;
4547     }
4548     case Instruction::Call: {
4549       // Check if the calls are all to the same vectorizable intrinsic or
4550       // library function.
4551       CallInst *CI = cast<CallInst>(VL0);
4552       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4553 
4554       VFShape Shape = VFShape::get(
4555           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4556           false /*HasGlobalPred*/);
4557       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4558 
4559       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4560         BS.cancelScheduling(VL, VL0);
4561         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4562                      ReuseShuffleIndicies);
4563         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4564         return;
4565       }
4566       Function *F = CI->getCalledFunction();
4567       unsigned NumArgs = CI->arg_size();
4568       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4569       for (unsigned j = 0; j != NumArgs; ++j)
4570         if (hasVectorInstrinsicScalarOpd(ID, j))
4571           ScalarArgs[j] = CI->getArgOperand(j);
4572       for (Value *V : VL) {
4573         CallInst *CI2 = dyn_cast<CallInst>(V);
4574         if (!CI2 || CI2->getCalledFunction() != F ||
4575             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4576             (VecFunc &&
4577              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4578             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4579           BS.cancelScheduling(VL, VL0);
4580           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4581                        ReuseShuffleIndicies);
4582           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4583                             << "\n");
4584           return;
4585         }
4586         // Some intrinsics have scalar arguments and should be same in order for
4587         // them to be vectorized.
4588         for (unsigned j = 0; j != NumArgs; ++j) {
4589           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4590             Value *A1J = CI2->getArgOperand(j);
4591             if (ScalarArgs[j] != A1J) {
4592               BS.cancelScheduling(VL, VL0);
4593               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4594                            ReuseShuffleIndicies);
4595               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4596                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4597                                 << "\n");
4598               return;
4599             }
4600           }
4601         }
4602         // Verify that the bundle operands are identical between the two calls.
4603         if (CI->hasOperandBundles() &&
4604             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4605                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4606                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4607           BS.cancelScheduling(VL, VL0);
4608           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4609                        ReuseShuffleIndicies);
4610           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4611                             << *CI << "!=" << *V << '\n');
4612           return;
4613         }
4614       }
4615 
4616       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4617                                    ReuseShuffleIndicies);
4618       TE->setOperandsInOrder();
4619       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4620         // For scalar operands no need to to create an entry since no need to
4621         // vectorize it.
4622         if (hasVectorInstrinsicScalarOpd(ID, i))
4623           continue;
4624         ValueList Operands;
4625         // Prepare the operand vector.
4626         for (Value *V : VL) {
4627           auto *CI2 = cast<CallInst>(V);
4628           Operands.push_back(CI2->getArgOperand(i));
4629         }
4630         buildTree_rec(Operands, Depth + 1, {TE, i});
4631       }
4632       return;
4633     }
4634     case Instruction::ShuffleVector: {
4635       // If this is not an alternate sequence of opcode like add-sub
4636       // then do not vectorize this instruction.
4637       if (!S.isAltShuffle()) {
4638         BS.cancelScheduling(VL, VL0);
4639         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4640                      ReuseShuffleIndicies);
4641         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4642         return;
4643       }
4644       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4645                                    ReuseShuffleIndicies);
4646       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4647 
4648       // Reorder operands if reordering would enable vectorization.
4649       auto *CI = dyn_cast<CmpInst>(VL0);
4650       if (isa<BinaryOperator>(VL0) || CI) {
4651         ValueList Left, Right;
4652         if (!CI || all_of(VL, [](Value *V) {
4653               return cast<CmpInst>(V)->isCommutative();
4654             })) {
4655           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4656         } else {
4657           CmpInst::Predicate P0 = CI->getPredicate();
4658           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4659           assert(P0 != AltP0 &&
4660                  "Expected different main/alternate predicates.");
4661           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4662           Value *BaseOp0 = VL0->getOperand(0);
4663           Value *BaseOp1 = VL0->getOperand(1);
4664           // Collect operands - commute if it uses the swapped predicate or
4665           // alternate operation.
4666           for (Value *V : VL) {
4667             auto *Cmp = cast<CmpInst>(V);
4668             Value *LHS = Cmp->getOperand(0);
4669             Value *RHS = Cmp->getOperand(1);
4670             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4671             if (P0 == AltP0Swapped) {
4672               if (CI != Cmp && S.AltOp != Cmp &&
4673                   ((P0 == CurrentPred &&
4674                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4675                    (AltP0 == CurrentPred &&
4676                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4677                 std::swap(LHS, RHS);
4678             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4679               std::swap(LHS, RHS);
4680             }
4681             Left.push_back(LHS);
4682             Right.push_back(RHS);
4683           }
4684         }
4685         TE->setOperand(0, Left);
4686         TE->setOperand(1, Right);
4687         buildTree_rec(Left, Depth + 1, {TE, 0});
4688         buildTree_rec(Right, Depth + 1, {TE, 1});
4689         return;
4690       }
4691 
4692       TE->setOperandsInOrder();
4693       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4694         ValueList Operands;
4695         // Prepare the operand vector.
4696         for (Value *V : VL)
4697           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4698 
4699         buildTree_rec(Operands, Depth + 1, {TE, i});
4700       }
4701       return;
4702     }
4703     default:
4704       BS.cancelScheduling(VL, VL0);
4705       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4706                    ReuseShuffleIndicies);
4707       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4708       return;
4709   }
4710 }
4711 
4712 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4713   unsigned N = 1;
4714   Type *EltTy = T;
4715 
4716   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4717          isa<VectorType>(EltTy)) {
4718     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4719       // Check that struct is homogeneous.
4720       for (const auto *Ty : ST->elements())
4721         if (Ty != *ST->element_begin())
4722           return 0;
4723       N *= ST->getNumElements();
4724       EltTy = *ST->element_begin();
4725     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4726       N *= AT->getNumElements();
4727       EltTy = AT->getElementType();
4728     } else {
4729       auto *VT = cast<FixedVectorType>(EltTy);
4730       N *= VT->getNumElements();
4731       EltTy = VT->getElementType();
4732     }
4733   }
4734 
4735   if (!isValidElementType(EltTy))
4736     return 0;
4737   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4738   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4739     return 0;
4740   return N;
4741 }
4742 
4743 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4744                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4745   const auto *It = find_if(VL, [](Value *V) {
4746     return isa<ExtractElementInst, ExtractValueInst>(V);
4747   });
4748   assert(It != VL.end() && "Expected at least one extract instruction.");
4749   auto *E0 = cast<Instruction>(*It);
4750   assert(all_of(VL,
4751                 [](Value *V) {
4752                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4753                       V);
4754                 }) &&
4755          "Invalid opcode");
4756   // Check if all of the extracts come from the same vector and from the
4757   // correct offset.
4758   Value *Vec = E0->getOperand(0);
4759 
4760   CurrentOrder.clear();
4761 
4762   // We have to extract from a vector/aggregate with the same number of elements.
4763   unsigned NElts;
4764   if (E0->getOpcode() == Instruction::ExtractValue) {
4765     const DataLayout &DL = E0->getModule()->getDataLayout();
4766     NElts = canMapToVector(Vec->getType(), DL);
4767     if (!NElts)
4768       return false;
4769     // Check if load can be rewritten as load of vector.
4770     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4771     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4772       return false;
4773   } else {
4774     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4775   }
4776 
4777   if (NElts != VL.size())
4778     return false;
4779 
4780   // Check that all of the indices extract from the correct offset.
4781   bool ShouldKeepOrder = true;
4782   unsigned E = VL.size();
4783   // Assign to all items the initial value E + 1 so we can check if the extract
4784   // instruction index was used already.
4785   // Also, later we can check that all the indices are used and we have a
4786   // consecutive access in the extract instructions, by checking that no
4787   // element of CurrentOrder still has value E + 1.
4788   CurrentOrder.assign(E, E);
4789   unsigned I = 0;
4790   for (; I < E; ++I) {
4791     auto *Inst = dyn_cast<Instruction>(VL[I]);
4792     if (!Inst)
4793       continue;
4794     if (Inst->getOperand(0) != Vec)
4795       break;
4796     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4797       if (isa<UndefValue>(EE->getIndexOperand()))
4798         continue;
4799     Optional<unsigned> Idx = getExtractIndex(Inst);
4800     if (!Idx)
4801       break;
4802     const unsigned ExtIdx = *Idx;
4803     if (ExtIdx != I) {
4804       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4805         break;
4806       ShouldKeepOrder = false;
4807       CurrentOrder[ExtIdx] = I;
4808     } else {
4809       if (CurrentOrder[I] != E)
4810         break;
4811       CurrentOrder[I] = I;
4812     }
4813   }
4814   if (I < E) {
4815     CurrentOrder.clear();
4816     return false;
4817   }
4818   if (ShouldKeepOrder)
4819     CurrentOrder.clear();
4820 
4821   return ShouldKeepOrder;
4822 }
4823 
4824 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4825                                     ArrayRef<Value *> VectorizedVals) const {
4826   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4827          all_of(I->users(), [this](User *U) {
4828            return ScalarToTreeEntry.count(U) > 0 ||
4829                   isVectorLikeInstWithConstOps(U) ||
4830                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4831          });
4832 }
4833 
4834 static std::pair<InstructionCost, InstructionCost>
4835 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4836                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4837   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4838 
4839   // Calculate the cost of the scalar and vector calls.
4840   SmallVector<Type *, 4> VecTys;
4841   for (Use &Arg : CI->args())
4842     VecTys.push_back(
4843         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4844   FastMathFlags FMF;
4845   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4846     FMF = FPCI->getFastMathFlags();
4847   SmallVector<const Value *> Arguments(CI->args());
4848   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4849                                     dyn_cast<IntrinsicInst>(CI));
4850   auto IntrinsicCost =
4851     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4852 
4853   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4854                                      VecTy->getNumElements())),
4855                             false /*HasGlobalPred*/);
4856   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4857   auto LibCost = IntrinsicCost;
4858   if (!CI->isNoBuiltin() && VecFunc) {
4859     // Calculate the cost of the vector library call.
4860     // If the corresponding vector call is cheaper, return its cost.
4861     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4862                                     TTI::TCK_RecipThroughput);
4863   }
4864   return {IntrinsicCost, LibCost};
4865 }
4866 
4867 /// Compute the cost of creating a vector of type \p VecTy containing the
4868 /// extracted values from \p VL.
4869 static InstructionCost
4870 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4871                    TargetTransformInfo::ShuffleKind ShuffleKind,
4872                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4873   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4874 
4875   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4876       VecTy->getNumElements() < NumOfParts)
4877     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4878 
4879   bool AllConsecutive = true;
4880   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4881   unsigned Idx = -1;
4882   InstructionCost Cost = 0;
4883 
4884   // Process extracts in blocks of EltsPerVector to check if the source vector
4885   // operand can be re-used directly. If not, add the cost of creating a shuffle
4886   // to extract the values into a vector register.
4887   for (auto *V : VL) {
4888     ++Idx;
4889 
4890     // Need to exclude undefs from analysis.
4891     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4892       continue;
4893 
4894     // Reached the start of a new vector registers.
4895     if (Idx % EltsPerVector == 0) {
4896       AllConsecutive = true;
4897       continue;
4898     }
4899 
4900     // Check all extracts for a vector register on the target directly
4901     // extract values in order.
4902     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4903     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4904       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4905       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4906                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4907     }
4908 
4909     if (AllConsecutive)
4910       continue;
4911 
4912     // Skip all indices, except for the last index per vector block.
4913     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4914       continue;
4915 
4916     // If we have a series of extracts which are not consecutive and hence
4917     // cannot re-use the source vector register directly, compute the shuffle
4918     // cost to extract the a vector with EltsPerVector elements.
4919     Cost += TTI.getShuffleCost(
4920         TargetTransformInfo::SK_PermuteSingleSrc,
4921         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4922   }
4923   return Cost;
4924 }
4925 
4926 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4927 /// operations operands.
4928 static void
4929 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4930                       ArrayRef<int> ReusesIndices,
4931                       const function_ref<bool(Instruction *)> IsAltOp,
4932                       SmallVectorImpl<int> &Mask,
4933                       SmallVectorImpl<Value *> *OpScalars = nullptr,
4934                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
4935   unsigned Sz = VL.size();
4936   Mask.assign(Sz, UndefMaskElem);
4937   SmallVector<int> OrderMask;
4938   if (!ReorderIndices.empty())
4939     inversePermutation(ReorderIndices, OrderMask);
4940   for (unsigned I = 0; I < Sz; ++I) {
4941     unsigned Idx = I;
4942     if (!ReorderIndices.empty())
4943       Idx = OrderMask[I];
4944     auto *OpInst = cast<Instruction>(VL[Idx]);
4945     if (IsAltOp(OpInst)) {
4946       Mask[I] = Sz + Idx;
4947       if (AltScalars)
4948         AltScalars->push_back(OpInst);
4949     } else {
4950       Mask[I] = Idx;
4951       if (OpScalars)
4952         OpScalars->push_back(OpInst);
4953     }
4954   }
4955   if (!ReusesIndices.empty()) {
4956     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4957     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4958       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4959     });
4960     Mask.swap(NewMask);
4961   }
4962 }
4963 
4964 /// Checks if the specified instruction \p I is an alternate operation for the
4965 /// given \p MainOp and \p AltOp instructions.
4966 static bool isAlternateInstruction(const Instruction *I,
4967                                    const Instruction *MainOp,
4968                                    const Instruction *AltOp) {
4969   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
4970     auto *AltCI0 = cast<CmpInst>(AltOp);
4971     auto *CI = cast<CmpInst>(I);
4972     CmpInst::Predicate P0 = CI0->getPredicate();
4973     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
4974     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
4975     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4976     CmpInst::Predicate CurrentPred = CI->getPredicate();
4977     if (P0 == AltP0Swapped)
4978       return I == AltCI0 ||
4979              (I != MainOp &&
4980               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
4981                                    CI->getOperand(0), CI->getOperand(1)));
4982     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
4983   }
4984   return I->getOpcode() == AltOp->getOpcode();
4985 }
4986 
4987 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4988                                       ArrayRef<Value *> VectorizedVals) {
4989   ArrayRef<Value*> VL = E->Scalars;
4990 
4991   Type *ScalarTy = VL[0]->getType();
4992   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4993     ScalarTy = SI->getValueOperand()->getType();
4994   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4995     ScalarTy = CI->getOperand(0)->getType();
4996   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4997     ScalarTy = IE->getOperand(1)->getType();
4998   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4999   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5000 
5001   // If we have computed a smaller type for the expression, update VecTy so
5002   // that the costs will be accurate.
5003   if (MinBWs.count(VL[0]))
5004     VecTy = FixedVectorType::get(
5005         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5006   unsigned EntryVF = E->getVectorFactor();
5007   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5008 
5009   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5010   // FIXME: it tries to fix a problem with MSVC buildbots.
5011   TargetTransformInfo &TTIRef = *TTI;
5012   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5013                                VectorizedVals, E](InstructionCost &Cost) {
5014     DenseMap<Value *, int> ExtractVectorsTys;
5015     SmallPtrSet<Value *, 4> CheckedExtracts;
5016     for (auto *V : VL) {
5017       if (isa<UndefValue>(V))
5018         continue;
5019       // If all users of instruction are going to be vectorized and this
5020       // instruction itself is not going to be vectorized, consider this
5021       // instruction as dead and remove its cost from the final cost of the
5022       // vectorized tree.
5023       // Also, avoid adjusting the cost for extractelements with multiple uses
5024       // in different graph entries.
5025       const TreeEntry *VE = getTreeEntry(V);
5026       if (!CheckedExtracts.insert(V).second ||
5027           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5028           (VE && VE != E))
5029         continue;
5030       auto *EE = cast<ExtractElementInst>(V);
5031       Optional<unsigned> EEIdx = getExtractIndex(EE);
5032       if (!EEIdx)
5033         continue;
5034       unsigned Idx = *EEIdx;
5035       if (TTIRef.getNumberOfParts(VecTy) !=
5036           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5037         auto It =
5038             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5039         It->getSecond() = std::min<int>(It->second, Idx);
5040       }
5041       // Take credit for instruction that will become dead.
5042       if (EE->hasOneUse()) {
5043         Instruction *Ext = EE->user_back();
5044         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5045             all_of(Ext->users(),
5046                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5047           // Use getExtractWithExtendCost() to calculate the cost of
5048           // extractelement/ext pair.
5049           Cost -=
5050               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5051                                               EE->getVectorOperandType(), Idx);
5052           // Add back the cost of s|zext which is subtracted separately.
5053           Cost += TTIRef.getCastInstrCost(
5054               Ext->getOpcode(), Ext->getType(), EE->getType(),
5055               TTI::getCastContextHint(Ext), CostKind, Ext);
5056           continue;
5057         }
5058       }
5059       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5060                                         EE->getVectorOperandType(), Idx);
5061     }
5062     // Add a cost for subvector extracts/inserts if required.
5063     for (const auto &Data : ExtractVectorsTys) {
5064       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5065       unsigned NumElts = VecTy->getNumElements();
5066       if (Data.second % NumElts == 0)
5067         continue;
5068       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5069         unsigned Idx = (Data.second / NumElts) * NumElts;
5070         unsigned EENumElts = EEVTy->getNumElements();
5071         if (Idx + NumElts <= EENumElts) {
5072           Cost +=
5073               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5074                                     EEVTy, None, Idx, VecTy);
5075         } else {
5076           // Need to round up the subvector type vectorization factor to avoid a
5077           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5078           // <= EENumElts.
5079           auto *SubVT =
5080               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5081           Cost +=
5082               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5083                                     EEVTy, None, Idx, SubVT);
5084         }
5085       } else {
5086         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5087                                       VecTy, None, 0, EEVTy);
5088       }
5089     }
5090   };
5091   if (E->State == TreeEntry::NeedToGather) {
5092     if (allConstant(VL))
5093       return 0;
5094     if (isa<InsertElementInst>(VL[0]))
5095       return InstructionCost::getInvalid();
5096     SmallVector<int> Mask;
5097     SmallVector<const TreeEntry *> Entries;
5098     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5099         isGatherShuffledEntry(E, Mask, Entries);
5100     if (Shuffle.hasValue()) {
5101       InstructionCost GatherCost = 0;
5102       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5103         // Perfect match in the graph, will reuse the previously vectorized
5104         // node. Cost is 0.
5105         LLVM_DEBUG(
5106             dbgs()
5107             << "SLP: perfect diamond match for gather bundle that starts with "
5108             << *VL.front() << ".\n");
5109         if (NeedToShuffleReuses)
5110           GatherCost =
5111               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5112                                   FinalVecTy, E->ReuseShuffleIndices);
5113       } else {
5114         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5115                           << " entries for bundle that starts with "
5116                           << *VL.front() << ".\n");
5117         // Detected that instead of gather we can emit a shuffle of single/two
5118         // previously vectorized nodes. Add the cost of the permutation rather
5119         // than gather.
5120         ::addMask(Mask, E->ReuseShuffleIndices);
5121         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5122       }
5123       return GatherCost;
5124     }
5125     if ((E->getOpcode() == Instruction::ExtractElement ||
5126          all_of(E->Scalars,
5127                 [](Value *V) {
5128                   return isa<ExtractElementInst, UndefValue>(V);
5129                 })) &&
5130         allSameType(VL)) {
5131       // Check that gather of extractelements can be represented as just a
5132       // shuffle of a single/two vectors the scalars are extracted from.
5133       SmallVector<int> Mask;
5134       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5135           isFixedVectorShuffle(VL, Mask);
5136       if (ShuffleKind.hasValue()) {
5137         // Found the bunch of extractelement instructions that must be gathered
5138         // into a vector and can be represented as a permutation elements in a
5139         // single input vector or of 2 input vectors.
5140         InstructionCost Cost =
5141             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5142         AdjustExtractsCost(Cost);
5143         if (NeedToShuffleReuses)
5144           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5145                                       FinalVecTy, E->ReuseShuffleIndices);
5146         return Cost;
5147       }
5148     }
5149     if (isSplat(VL)) {
5150       // Found the broadcasting of the single scalar, calculate the cost as the
5151       // broadcast.
5152       assert(VecTy == FinalVecTy &&
5153              "No reused scalars expected for broadcast.");
5154       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
5155     }
5156     InstructionCost ReuseShuffleCost = 0;
5157     if (NeedToShuffleReuses)
5158       ReuseShuffleCost = TTI->getShuffleCost(
5159           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5160     // Improve gather cost for gather of loads, if we can group some of the
5161     // loads into vector loads.
5162     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5163         !E->isAltShuffle()) {
5164       BoUpSLP::ValueSet VectorizedLoads;
5165       unsigned StartIdx = 0;
5166       unsigned VF = VL.size() / 2;
5167       unsigned VectorizedCnt = 0;
5168       unsigned ScatterVectorizeCnt = 0;
5169       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5170       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5171         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5172              Cnt += VF) {
5173           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5174           if (!VectorizedLoads.count(Slice.front()) &&
5175               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5176             SmallVector<Value *> PointerOps;
5177             OrdersType CurrentOrder;
5178             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5179                                               *SE, CurrentOrder, PointerOps);
5180             switch (LS) {
5181             case LoadsState::Vectorize:
5182             case LoadsState::ScatterVectorize:
5183               // Mark the vectorized loads so that we don't vectorize them
5184               // again.
5185               if (LS == LoadsState::Vectorize)
5186                 ++VectorizedCnt;
5187               else
5188                 ++ScatterVectorizeCnt;
5189               VectorizedLoads.insert(Slice.begin(), Slice.end());
5190               // If we vectorized initial block, no need to try to vectorize it
5191               // again.
5192               if (Cnt == StartIdx)
5193                 StartIdx += VF;
5194               break;
5195             case LoadsState::Gather:
5196               break;
5197             }
5198           }
5199         }
5200         // Check if the whole array was vectorized already - exit.
5201         if (StartIdx >= VL.size())
5202           break;
5203         // Found vectorizable parts - exit.
5204         if (!VectorizedLoads.empty())
5205           break;
5206       }
5207       if (!VectorizedLoads.empty()) {
5208         InstructionCost GatherCost = 0;
5209         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5210         bool NeedInsertSubvectorAnalysis =
5211             !NumParts || (VL.size() / VF) > NumParts;
5212         // Get the cost for gathered loads.
5213         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5214           if (VectorizedLoads.contains(VL[I]))
5215             continue;
5216           GatherCost += getGatherCost(VL.slice(I, VF));
5217         }
5218         // The cost for vectorized loads.
5219         InstructionCost ScalarsCost = 0;
5220         for (Value *V : VectorizedLoads) {
5221           auto *LI = cast<LoadInst>(V);
5222           ScalarsCost += TTI->getMemoryOpCost(
5223               Instruction::Load, LI->getType(), LI->getAlign(),
5224               LI->getPointerAddressSpace(), CostKind, LI);
5225         }
5226         auto *LI = cast<LoadInst>(E->getMainOp());
5227         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5228         Align Alignment = LI->getAlign();
5229         GatherCost +=
5230             VectorizedCnt *
5231             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5232                                  LI->getPointerAddressSpace(), CostKind, LI);
5233         GatherCost += ScatterVectorizeCnt *
5234                       TTI->getGatherScatterOpCost(
5235                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5236                           /*VariableMask=*/false, Alignment, CostKind, LI);
5237         if (NeedInsertSubvectorAnalysis) {
5238           // Add the cost for the subvectors insert.
5239           for (int I = VF, E = VL.size(); I < E; I += VF)
5240             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5241                                               None, I, LoadTy);
5242         }
5243         return ReuseShuffleCost + GatherCost - ScalarsCost;
5244       }
5245     }
5246     return ReuseShuffleCost + getGatherCost(VL);
5247   }
5248   InstructionCost CommonCost = 0;
5249   SmallVector<int> Mask;
5250   if (!E->ReorderIndices.empty()) {
5251     SmallVector<int> NewMask;
5252     if (E->getOpcode() == Instruction::Store) {
5253       // For stores the order is actually a mask.
5254       NewMask.resize(E->ReorderIndices.size());
5255       copy(E->ReorderIndices, NewMask.begin());
5256     } else {
5257       inversePermutation(E->ReorderIndices, NewMask);
5258     }
5259     ::addMask(Mask, NewMask);
5260   }
5261   if (NeedToShuffleReuses)
5262     ::addMask(Mask, E->ReuseShuffleIndices);
5263   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5264     CommonCost =
5265         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5266   assert((E->State == TreeEntry::Vectorize ||
5267           E->State == TreeEntry::ScatterVectorize) &&
5268          "Unhandled state");
5269   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5270   Instruction *VL0 = E->getMainOp();
5271   unsigned ShuffleOrOp =
5272       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5273   switch (ShuffleOrOp) {
5274     case Instruction::PHI:
5275       return 0;
5276 
5277     case Instruction::ExtractValue:
5278     case Instruction::ExtractElement: {
5279       // The common cost of removal ExtractElement/ExtractValue instructions +
5280       // the cost of shuffles, if required to resuffle the original vector.
5281       if (NeedToShuffleReuses) {
5282         unsigned Idx = 0;
5283         for (unsigned I : E->ReuseShuffleIndices) {
5284           if (ShuffleOrOp == Instruction::ExtractElement) {
5285             auto *EE = cast<ExtractElementInst>(VL[I]);
5286             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5287                                                   EE->getVectorOperandType(),
5288                                                   *getExtractIndex(EE));
5289           } else {
5290             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5291                                                   VecTy, Idx);
5292             ++Idx;
5293           }
5294         }
5295         Idx = EntryVF;
5296         for (Value *V : VL) {
5297           if (ShuffleOrOp == Instruction::ExtractElement) {
5298             auto *EE = cast<ExtractElementInst>(V);
5299             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5300                                                   EE->getVectorOperandType(),
5301                                                   *getExtractIndex(EE));
5302           } else {
5303             --Idx;
5304             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5305                                                   VecTy, Idx);
5306           }
5307         }
5308       }
5309       if (ShuffleOrOp == Instruction::ExtractValue) {
5310         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5311           auto *EI = cast<Instruction>(VL[I]);
5312           // Take credit for instruction that will become dead.
5313           if (EI->hasOneUse()) {
5314             Instruction *Ext = EI->user_back();
5315             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5316                 all_of(Ext->users(),
5317                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5318               // Use getExtractWithExtendCost() to calculate the cost of
5319               // extractelement/ext pair.
5320               CommonCost -= TTI->getExtractWithExtendCost(
5321                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5322               // Add back the cost of s|zext which is subtracted separately.
5323               CommonCost += TTI->getCastInstrCost(
5324                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5325                   TTI::getCastContextHint(Ext), CostKind, Ext);
5326               continue;
5327             }
5328           }
5329           CommonCost -=
5330               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5331         }
5332       } else {
5333         AdjustExtractsCost(CommonCost);
5334       }
5335       return CommonCost;
5336     }
5337     case Instruction::InsertElement: {
5338       assert(E->ReuseShuffleIndices.empty() &&
5339              "Unique insertelements only are expected.");
5340       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5341 
5342       unsigned const NumElts = SrcVecTy->getNumElements();
5343       unsigned const NumScalars = VL.size();
5344       APInt DemandedElts = APInt::getZero(NumElts);
5345       // TODO: Add support for Instruction::InsertValue.
5346       SmallVector<int> Mask;
5347       if (!E->ReorderIndices.empty()) {
5348         inversePermutation(E->ReorderIndices, Mask);
5349         Mask.append(NumElts - NumScalars, UndefMaskElem);
5350       } else {
5351         Mask.assign(NumElts, UndefMaskElem);
5352         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5353       }
5354       unsigned Offset = *getInsertIndex(VL0);
5355       bool IsIdentity = true;
5356       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5357       Mask.swap(PrevMask);
5358       for (unsigned I = 0; I < NumScalars; ++I) {
5359         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5360         DemandedElts.setBit(InsertIdx);
5361         IsIdentity &= InsertIdx - Offset == I;
5362         Mask[InsertIdx - Offset] = I;
5363       }
5364       assert(Offset < NumElts && "Failed to find vector index offset");
5365 
5366       InstructionCost Cost = 0;
5367       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5368                                             /*Insert*/ true, /*Extract*/ false);
5369 
5370       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5371         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5372         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5373         Cost += TTI->getShuffleCost(
5374             TargetTransformInfo::SK_PermuteSingleSrc,
5375             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5376       } else if (!IsIdentity) {
5377         auto *FirstInsert =
5378             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5379               return !is_contained(E->Scalars,
5380                                    cast<Instruction>(V)->getOperand(0));
5381             }));
5382         if (isUndefVector(FirstInsert->getOperand(0))) {
5383           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5384         } else {
5385           SmallVector<int> InsertMask(NumElts);
5386           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5387           for (unsigned I = 0; I < NumElts; I++) {
5388             if (Mask[I] != UndefMaskElem)
5389               InsertMask[Offset + I] = NumElts + I;
5390           }
5391           Cost +=
5392               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5393         }
5394       }
5395 
5396       return Cost;
5397     }
5398     case Instruction::ZExt:
5399     case Instruction::SExt:
5400     case Instruction::FPToUI:
5401     case Instruction::FPToSI:
5402     case Instruction::FPExt:
5403     case Instruction::PtrToInt:
5404     case Instruction::IntToPtr:
5405     case Instruction::SIToFP:
5406     case Instruction::UIToFP:
5407     case Instruction::Trunc:
5408     case Instruction::FPTrunc:
5409     case Instruction::BitCast: {
5410       Type *SrcTy = VL0->getOperand(0)->getType();
5411       InstructionCost ScalarEltCost =
5412           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5413                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5414       if (NeedToShuffleReuses) {
5415         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5416       }
5417 
5418       // Calculate the cost of this instruction.
5419       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5420 
5421       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5422       InstructionCost VecCost = 0;
5423       // Check if the values are candidates to demote.
5424       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5425         VecCost = CommonCost + TTI->getCastInstrCost(
5426                                    E->getOpcode(), VecTy, SrcVecTy,
5427                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5428       }
5429       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5430       return VecCost - ScalarCost;
5431     }
5432     case Instruction::FCmp:
5433     case Instruction::ICmp:
5434     case Instruction::Select: {
5435       // Calculate the cost of this instruction.
5436       InstructionCost ScalarEltCost =
5437           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5438                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5439       if (NeedToShuffleReuses) {
5440         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5441       }
5442       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5443       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5444 
5445       // Check if all entries in VL are either compares or selects with compares
5446       // as condition that have the same predicates.
5447       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5448       bool First = true;
5449       for (auto *V : VL) {
5450         CmpInst::Predicate CurrentPred;
5451         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5452         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5453              !match(V, MatchCmp)) ||
5454             (!First && VecPred != CurrentPred)) {
5455           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5456           break;
5457         }
5458         First = false;
5459         VecPred = CurrentPred;
5460       }
5461 
5462       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5463           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5464       // Check if it is possible and profitable to use min/max for selects in
5465       // VL.
5466       //
5467       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5468       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5469         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5470                                           {VecTy, VecTy});
5471         InstructionCost IntrinsicCost =
5472             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5473         // If the selects are the only uses of the compares, they will be dead
5474         // and we can adjust the cost by removing their cost.
5475         if (IntrinsicAndUse.second)
5476           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5477                                                    MaskTy, VecPred, CostKind);
5478         VecCost = std::min(VecCost, IntrinsicCost);
5479       }
5480       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5481       return CommonCost + VecCost - ScalarCost;
5482     }
5483     case Instruction::FNeg:
5484     case Instruction::Add:
5485     case Instruction::FAdd:
5486     case Instruction::Sub:
5487     case Instruction::FSub:
5488     case Instruction::Mul:
5489     case Instruction::FMul:
5490     case Instruction::UDiv:
5491     case Instruction::SDiv:
5492     case Instruction::FDiv:
5493     case Instruction::URem:
5494     case Instruction::SRem:
5495     case Instruction::FRem:
5496     case Instruction::Shl:
5497     case Instruction::LShr:
5498     case Instruction::AShr:
5499     case Instruction::And:
5500     case Instruction::Or:
5501     case Instruction::Xor: {
5502       // Certain instructions can be cheaper to vectorize if they have a
5503       // constant second vector operand.
5504       TargetTransformInfo::OperandValueKind Op1VK =
5505           TargetTransformInfo::OK_AnyValue;
5506       TargetTransformInfo::OperandValueKind Op2VK =
5507           TargetTransformInfo::OK_UniformConstantValue;
5508       TargetTransformInfo::OperandValueProperties Op1VP =
5509           TargetTransformInfo::OP_None;
5510       TargetTransformInfo::OperandValueProperties Op2VP =
5511           TargetTransformInfo::OP_PowerOf2;
5512 
5513       // If all operands are exactly the same ConstantInt then set the
5514       // operand kind to OK_UniformConstantValue.
5515       // If instead not all operands are constants, then set the operand kind
5516       // to OK_AnyValue. If all operands are constants but not the same,
5517       // then set the operand kind to OK_NonUniformConstantValue.
5518       ConstantInt *CInt0 = nullptr;
5519       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5520         const Instruction *I = cast<Instruction>(VL[i]);
5521         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5522         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5523         if (!CInt) {
5524           Op2VK = TargetTransformInfo::OK_AnyValue;
5525           Op2VP = TargetTransformInfo::OP_None;
5526           break;
5527         }
5528         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5529             !CInt->getValue().isPowerOf2())
5530           Op2VP = TargetTransformInfo::OP_None;
5531         if (i == 0) {
5532           CInt0 = CInt;
5533           continue;
5534         }
5535         if (CInt0 != CInt)
5536           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5537       }
5538 
5539       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5540       InstructionCost ScalarEltCost =
5541           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5542                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5543       if (NeedToShuffleReuses) {
5544         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5545       }
5546       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5547       InstructionCost VecCost =
5548           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5549                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5550       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5551       return CommonCost + VecCost - ScalarCost;
5552     }
5553     case Instruction::GetElementPtr: {
5554       TargetTransformInfo::OperandValueKind Op1VK =
5555           TargetTransformInfo::OK_AnyValue;
5556       TargetTransformInfo::OperandValueKind Op2VK =
5557           TargetTransformInfo::OK_UniformConstantValue;
5558 
5559       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5560           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5561       if (NeedToShuffleReuses) {
5562         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5563       }
5564       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5565       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5566           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5567       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5568       return CommonCost + VecCost - ScalarCost;
5569     }
5570     case Instruction::Load: {
5571       // Cost of wide load - cost of scalar loads.
5572       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5573       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5574           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5575       if (NeedToShuffleReuses) {
5576         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5577       }
5578       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5579       InstructionCost VecLdCost;
5580       if (E->State == TreeEntry::Vectorize) {
5581         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5582                                          CostKind, VL0);
5583       } else {
5584         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5585         Align CommonAlignment = Alignment;
5586         for (Value *V : VL)
5587           CommonAlignment =
5588               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5589         VecLdCost = TTI->getGatherScatterOpCost(
5590             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5591             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5592       }
5593       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5594       return CommonCost + VecLdCost - ScalarLdCost;
5595     }
5596     case Instruction::Store: {
5597       // We know that we can merge the stores. Calculate the cost.
5598       bool IsReorder = !E->ReorderIndices.empty();
5599       auto *SI =
5600           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5601       Align Alignment = SI->getAlign();
5602       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5603           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5604       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5605       InstructionCost VecStCost = TTI->getMemoryOpCost(
5606           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5607       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5608       return CommonCost + VecStCost - ScalarStCost;
5609     }
5610     case Instruction::Call: {
5611       CallInst *CI = cast<CallInst>(VL0);
5612       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5613 
5614       // Calculate the cost of the scalar and vector calls.
5615       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5616       InstructionCost ScalarEltCost =
5617           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5618       if (NeedToShuffleReuses) {
5619         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5620       }
5621       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5622 
5623       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5624       InstructionCost VecCallCost =
5625           std::min(VecCallCosts.first, VecCallCosts.second);
5626 
5627       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5628                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5629                         << " for " << *CI << "\n");
5630 
5631       return CommonCost + VecCallCost - ScalarCallCost;
5632     }
5633     case Instruction::ShuffleVector: {
5634       assert(E->isAltShuffle() &&
5635              ((Instruction::isBinaryOp(E->getOpcode()) &&
5636                Instruction::isBinaryOp(E->getAltOpcode())) ||
5637               (Instruction::isCast(E->getOpcode()) &&
5638                Instruction::isCast(E->getAltOpcode())) ||
5639               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5640              "Invalid Shuffle Vector Operand");
5641       InstructionCost ScalarCost = 0;
5642       if (NeedToShuffleReuses) {
5643         for (unsigned Idx : E->ReuseShuffleIndices) {
5644           Instruction *I = cast<Instruction>(VL[Idx]);
5645           CommonCost -= TTI->getInstructionCost(I, CostKind);
5646         }
5647         for (Value *V : VL) {
5648           Instruction *I = cast<Instruction>(V);
5649           CommonCost += TTI->getInstructionCost(I, CostKind);
5650         }
5651       }
5652       for (Value *V : VL) {
5653         Instruction *I = cast<Instruction>(V);
5654         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5655         ScalarCost += TTI->getInstructionCost(I, CostKind);
5656       }
5657       // VecCost is equal to sum of the cost of creating 2 vectors
5658       // and the cost of creating shuffle.
5659       InstructionCost VecCost = 0;
5660       // Try to find the previous shuffle node with the same operands and same
5661       // main/alternate ops.
5662       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5663         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5664           if (TE.get() == E)
5665             break;
5666           if (TE->isAltShuffle() &&
5667               ((TE->getOpcode() == E->getOpcode() &&
5668                 TE->getAltOpcode() == E->getAltOpcode()) ||
5669                (TE->getOpcode() == E->getAltOpcode() &&
5670                 TE->getAltOpcode() == E->getOpcode())) &&
5671               TE->hasEqualOperands(*E))
5672             return true;
5673         }
5674         return false;
5675       };
5676       if (TryFindNodeWithEqualOperands()) {
5677         LLVM_DEBUG({
5678           dbgs() << "SLP: diamond match for alternate node found.\n";
5679           E->dump();
5680         });
5681         // No need to add new vector costs here since we're going to reuse
5682         // same main/alternate vector ops, just do different shuffling.
5683       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5684         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5685         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5686                                                CostKind);
5687       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5688         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5689                                           Builder.getInt1Ty(),
5690                                           CI0->getPredicate(), CostKind, VL0);
5691         VecCost += TTI->getCmpSelInstrCost(
5692             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5693             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5694             E->getAltOp());
5695       } else {
5696         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5697         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5698         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5699         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5700         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5701                                         TTI::CastContextHint::None, CostKind);
5702         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5703                                          TTI::CastContextHint::None, CostKind);
5704       }
5705 
5706       SmallVector<int> Mask;
5707       buildShuffleEntryMask(
5708           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5709           [E](Instruction *I) {
5710             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5711             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5712           },
5713           Mask);
5714       CommonCost =
5715           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5716       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5717       return CommonCost + VecCost - ScalarCost;
5718     }
5719     default:
5720       llvm_unreachable("Unknown instruction");
5721   }
5722 }
5723 
5724 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5725   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5726                     << VectorizableTree.size() << " is fully vectorizable .\n");
5727 
5728   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5729     SmallVector<int> Mask;
5730     return TE->State == TreeEntry::NeedToGather &&
5731            !any_of(TE->Scalars,
5732                    [this](Value *V) { return EphValues.contains(V); }) &&
5733            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5734             TE->Scalars.size() < Limit ||
5735             ((TE->getOpcode() == Instruction::ExtractElement ||
5736               all_of(TE->Scalars,
5737                      [](Value *V) {
5738                        return isa<ExtractElementInst, UndefValue>(V);
5739                      })) &&
5740              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5741             (TE->State == TreeEntry::NeedToGather &&
5742              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5743   };
5744 
5745   // We only handle trees of heights 1 and 2.
5746   if (VectorizableTree.size() == 1 &&
5747       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5748        (ForReduction &&
5749         AreVectorizableGathers(VectorizableTree[0].get(),
5750                                VectorizableTree[0]->Scalars.size()) &&
5751         VectorizableTree[0]->getVectorFactor() > 2)))
5752     return true;
5753 
5754   if (VectorizableTree.size() != 2)
5755     return false;
5756 
5757   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5758   // with the second gather nodes if they have less scalar operands rather than
5759   // the initial tree element (may be profitable to shuffle the second gather)
5760   // or they are extractelements, which form shuffle.
5761   SmallVector<int> Mask;
5762   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5763       AreVectorizableGathers(VectorizableTree[1].get(),
5764                              VectorizableTree[0]->Scalars.size()))
5765     return true;
5766 
5767   // Gathering cost would be too much for tiny trees.
5768   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5769       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5770        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5771     return false;
5772 
5773   return true;
5774 }
5775 
5776 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5777                                        TargetTransformInfo *TTI,
5778                                        bool MustMatchOrInst) {
5779   // Look past the root to find a source value. Arbitrarily follow the
5780   // path through operand 0 of any 'or'. Also, peek through optional
5781   // shift-left-by-multiple-of-8-bits.
5782   Value *ZextLoad = Root;
5783   const APInt *ShAmtC;
5784   bool FoundOr = false;
5785   while (!isa<ConstantExpr>(ZextLoad) &&
5786          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5787           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5788            ShAmtC->urem(8) == 0))) {
5789     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5790     ZextLoad = BinOp->getOperand(0);
5791     if (BinOp->getOpcode() == Instruction::Or)
5792       FoundOr = true;
5793   }
5794   // Check if the input is an extended load of the required or/shift expression.
5795   Value *Load;
5796   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5797       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5798     return false;
5799 
5800   // Require that the total load bit width is a legal integer type.
5801   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5802   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5803   Type *SrcTy = Load->getType();
5804   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5805   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5806     return false;
5807 
5808   // Everything matched - assume that we can fold the whole sequence using
5809   // load combining.
5810   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5811              << *(cast<Instruction>(Root)) << "\n");
5812 
5813   return true;
5814 }
5815 
5816 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5817   if (RdxKind != RecurKind::Or)
5818     return false;
5819 
5820   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5821   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5822   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5823                                     /* MatchOr */ false);
5824 }
5825 
5826 bool BoUpSLP::isLoadCombineCandidate() const {
5827   // Peek through a final sequence of stores and check if all operations are
5828   // likely to be load-combined.
5829   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5830   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5831     Value *X;
5832     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5833         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5834       return false;
5835   }
5836   return true;
5837 }
5838 
5839 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5840   // No need to vectorize inserts of gathered values.
5841   if (VectorizableTree.size() == 2 &&
5842       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5843       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5844     return true;
5845 
5846   // We can vectorize the tree if its size is greater than or equal to the
5847   // minimum size specified by the MinTreeSize command line option.
5848   if (VectorizableTree.size() >= MinTreeSize)
5849     return false;
5850 
5851   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5852   // can vectorize it if we can prove it fully vectorizable.
5853   if (isFullyVectorizableTinyTree(ForReduction))
5854     return false;
5855 
5856   assert(VectorizableTree.empty()
5857              ? ExternalUses.empty()
5858              : true && "We shouldn't have any external users");
5859 
5860   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5861   // vectorizable.
5862   return true;
5863 }
5864 
5865 InstructionCost BoUpSLP::getSpillCost() const {
5866   // Walk from the bottom of the tree to the top, tracking which values are
5867   // live. When we see a call instruction that is not part of our tree,
5868   // query TTI to see if there is a cost to keeping values live over it
5869   // (for example, if spills and fills are required).
5870   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5871   InstructionCost Cost = 0;
5872 
5873   SmallPtrSet<Instruction*, 4> LiveValues;
5874   Instruction *PrevInst = nullptr;
5875 
5876   // The entries in VectorizableTree are not necessarily ordered by their
5877   // position in basic blocks. Collect them and order them by dominance so later
5878   // instructions are guaranteed to be visited first. For instructions in
5879   // different basic blocks, we only scan to the beginning of the block, so
5880   // their order does not matter, as long as all instructions in a basic block
5881   // are grouped together. Using dominance ensures a deterministic order.
5882   SmallVector<Instruction *, 16> OrderedScalars;
5883   for (const auto &TEPtr : VectorizableTree) {
5884     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5885     if (!Inst)
5886       continue;
5887     OrderedScalars.push_back(Inst);
5888   }
5889   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5890     auto *NodeA = DT->getNode(A->getParent());
5891     auto *NodeB = DT->getNode(B->getParent());
5892     assert(NodeA && "Should only process reachable instructions");
5893     assert(NodeB && "Should only process reachable instructions");
5894     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5895            "Different nodes should have different DFS numbers");
5896     if (NodeA != NodeB)
5897       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5898     return B->comesBefore(A);
5899   });
5900 
5901   for (Instruction *Inst : OrderedScalars) {
5902     if (!PrevInst) {
5903       PrevInst = Inst;
5904       continue;
5905     }
5906 
5907     // Update LiveValues.
5908     LiveValues.erase(PrevInst);
5909     for (auto &J : PrevInst->operands()) {
5910       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5911         LiveValues.insert(cast<Instruction>(&*J));
5912     }
5913 
5914     LLVM_DEBUG({
5915       dbgs() << "SLP: #LV: " << LiveValues.size();
5916       for (auto *X : LiveValues)
5917         dbgs() << " " << X->getName();
5918       dbgs() << ", Looking at ";
5919       Inst->dump();
5920     });
5921 
5922     // Now find the sequence of instructions between PrevInst and Inst.
5923     unsigned NumCalls = 0;
5924     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5925                                  PrevInstIt =
5926                                      PrevInst->getIterator().getReverse();
5927     while (InstIt != PrevInstIt) {
5928       if (PrevInstIt == PrevInst->getParent()->rend()) {
5929         PrevInstIt = Inst->getParent()->rbegin();
5930         continue;
5931       }
5932 
5933       // Debug information does not impact spill cost.
5934       if ((isa<CallInst>(&*PrevInstIt) &&
5935            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5936           &*PrevInstIt != PrevInst)
5937         NumCalls++;
5938 
5939       ++PrevInstIt;
5940     }
5941 
5942     if (NumCalls) {
5943       SmallVector<Type*, 4> V;
5944       for (auto *II : LiveValues) {
5945         auto *ScalarTy = II->getType();
5946         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5947           ScalarTy = VectorTy->getElementType();
5948         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5949       }
5950       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5951     }
5952 
5953     PrevInst = Inst;
5954   }
5955 
5956   return Cost;
5957 }
5958 
5959 /// Check if two insertelement instructions are from the same buildvector.
5960 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5961                                             InsertElementInst *V) {
5962   // Instructions must be from the same basic blocks.
5963   if (VU->getParent() != V->getParent())
5964     return false;
5965   // Checks if 2 insertelements are from the same buildvector.
5966   if (VU->getType() != V->getType())
5967     return false;
5968   // Multiple used inserts are separate nodes.
5969   if (!VU->hasOneUse() && !V->hasOneUse())
5970     return false;
5971   auto *IE1 = VU;
5972   auto *IE2 = V;
5973   // Go through the vector operand of insertelement instructions trying to find
5974   // either VU as the original vector for IE2 or V as the original vector for
5975   // IE1.
5976   do {
5977     if (IE2 == VU || IE1 == V)
5978       return true;
5979     if (IE1) {
5980       if (IE1 != VU && !IE1->hasOneUse())
5981         IE1 = nullptr;
5982       else
5983         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5984     }
5985     if (IE2) {
5986       if (IE2 != V && !IE2->hasOneUse())
5987         IE2 = nullptr;
5988       else
5989         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5990     }
5991   } while (IE1 || IE2);
5992   return false;
5993 }
5994 
5995 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5996   InstructionCost Cost = 0;
5997   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5998                     << VectorizableTree.size() << ".\n");
5999 
6000   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6001 
6002   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6003     TreeEntry &TE = *VectorizableTree[I].get();
6004 
6005     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6006     Cost += C;
6007     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6008                       << " for bundle that starts with " << *TE.Scalars[0]
6009                       << ".\n"
6010                       << "SLP: Current total cost = " << Cost << "\n");
6011   }
6012 
6013   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6014   InstructionCost ExtractCost = 0;
6015   SmallVector<unsigned> VF;
6016   SmallVector<SmallVector<int>> ShuffleMask;
6017   SmallVector<Value *> FirstUsers;
6018   SmallVector<APInt> DemandedElts;
6019   for (ExternalUser &EU : ExternalUses) {
6020     // We only add extract cost once for the same scalar.
6021     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6022         !ExtractCostCalculated.insert(EU.Scalar).second)
6023       continue;
6024 
6025     // Uses by ephemeral values are free (because the ephemeral value will be
6026     // removed prior to code generation, and so the extraction will be
6027     // removed as well).
6028     if (EphValues.count(EU.User))
6029       continue;
6030 
6031     // No extract cost for vector "scalar"
6032     if (isa<FixedVectorType>(EU.Scalar->getType()))
6033       continue;
6034 
6035     // Already counted the cost for external uses when tried to adjust the cost
6036     // for extractelements, no need to add it again.
6037     if (isa<ExtractElementInst>(EU.Scalar))
6038       continue;
6039 
6040     // If found user is an insertelement, do not calculate extract cost but try
6041     // to detect it as a final shuffled/identity match.
6042     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6043       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6044         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6045         if (InsertIdx) {
6046           auto *It = find_if(FirstUsers, [VU](Value *V) {
6047             return areTwoInsertFromSameBuildVector(VU,
6048                                                    cast<InsertElementInst>(V));
6049           });
6050           int VecId = -1;
6051           if (It == FirstUsers.end()) {
6052             VF.push_back(FTy->getNumElements());
6053             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6054             // Find the insertvector, vectorized in tree, if any.
6055             Value *Base = VU;
6056             while (isa<InsertElementInst>(Base)) {
6057               // Build the mask for the vectorized insertelement instructions.
6058               if (const TreeEntry *E = getTreeEntry(Base)) {
6059                 VU = cast<InsertElementInst>(Base);
6060                 do {
6061                   int Idx = E->findLaneForValue(Base);
6062                   ShuffleMask.back()[Idx] = Idx;
6063                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6064                 } while (E == getTreeEntry(Base));
6065                 break;
6066               }
6067               Base = cast<InsertElementInst>(Base)->getOperand(0);
6068             }
6069             FirstUsers.push_back(VU);
6070             DemandedElts.push_back(APInt::getZero(VF.back()));
6071             VecId = FirstUsers.size() - 1;
6072           } else {
6073             VecId = std::distance(FirstUsers.begin(), It);
6074           }
6075           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6076           DemandedElts[VecId].setBit(*InsertIdx);
6077           continue;
6078         }
6079       }
6080     }
6081 
6082     // If we plan to rewrite the tree in a smaller type, we will need to sign
6083     // extend the extracted value back to the original type. Here, we account
6084     // for the extract and the added cost of the sign extend if needed.
6085     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6086     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6087     if (MinBWs.count(ScalarRoot)) {
6088       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6089       auto Extend =
6090           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6091       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6092       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6093                                                    VecTy, EU.Lane);
6094     } else {
6095       ExtractCost +=
6096           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6097     }
6098   }
6099 
6100   InstructionCost SpillCost = getSpillCost();
6101   Cost += SpillCost + ExtractCost;
6102   if (FirstUsers.size() == 1) {
6103     int Limit = ShuffleMask.front().size() * 2;
6104     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6105         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6106       InstructionCost C = TTI->getShuffleCost(
6107           TTI::SK_PermuteSingleSrc,
6108           cast<FixedVectorType>(FirstUsers.front()->getType()),
6109           ShuffleMask.front());
6110       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6111                         << " for final shuffle of insertelement external users "
6112                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6113                         << "SLP: Current total cost = " << Cost << "\n");
6114       Cost += C;
6115     }
6116     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6117         cast<FixedVectorType>(FirstUsers.front()->getType()),
6118         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6119     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6120                       << " for insertelements gather.\n"
6121                       << "SLP: Current total cost = " << Cost << "\n");
6122     Cost -= InsertCost;
6123   } else if (FirstUsers.size() >= 2) {
6124     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6125     // Combined masks of the first 2 vectors.
6126     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6127     copy(ShuffleMask.front(), CombinedMask.begin());
6128     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6129     auto *VecTy = FixedVectorType::get(
6130         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6131         MaxVF);
6132     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6133       if (ShuffleMask[1][I] != UndefMaskElem) {
6134         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6135         CombinedDemandedElts.setBit(I);
6136       }
6137     }
6138     InstructionCost C =
6139         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6140     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6141                       << " for final shuffle of vector node and external "
6142                          "insertelement users "
6143                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6144                       << "SLP: Current total cost = " << Cost << "\n");
6145     Cost += C;
6146     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6147         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6148     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6149                       << " for insertelements gather.\n"
6150                       << "SLP: Current total cost = " << Cost << "\n");
6151     Cost -= InsertCost;
6152     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6153       // Other elements - permutation of 2 vectors (the initial one and the
6154       // next Ith incoming vector).
6155       unsigned VF = ShuffleMask[I].size();
6156       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6157         int Mask = ShuffleMask[I][Idx];
6158         if (Mask != UndefMaskElem)
6159           CombinedMask[Idx] = MaxVF + Mask;
6160         else if (CombinedMask[Idx] != UndefMaskElem)
6161           CombinedMask[Idx] = Idx;
6162       }
6163       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6164         if (CombinedMask[Idx] != UndefMaskElem)
6165           CombinedMask[Idx] = Idx;
6166       InstructionCost C =
6167           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6168       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6169                         << " for final shuffle of vector node and external "
6170                            "insertelement users "
6171                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6172                         << "SLP: Current total cost = " << Cost << "\n");
6173       Cost += C;
6174       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6175           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6176           /*Insert*/ true, /*Extract*/ false);
6177       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6178                         << " for insertelements gather.\n"
6179                         << "SLP: Current total cost = " << Cost << "\n");
6180       Cost -= InsertCost;
6181     }
6182   }
6183 
6184 #ifndef NDEBUG
6185   SmallString<256> Str;
6186   {
6187     raw_svector_ostream OS(Str);
6188     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6189        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6190        << "SLP: Total Cost = " << Cost << ".\n";
6191   }
6192   LLVM_DEBUG(dbgs() << Str);
6193   if (ViewSLPTree)
6194     ViewGraph(this, "SLP" + F->getName(), false, Str);
6195 #endif
6196 
6197   return Cost;
6198 }
6199 
6200 Optional<TargetTransformInfo::ShuffleKind>
6201 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6202                                SmallVectorImpl<const TreeEntry *> &Entries) {
6203   // TODO: currently checking only for Scalars in the tree entry, need to count
6204   // reused elements too for better cost estimation.
6205   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6206   Entries.clear();
6207   // Build a lists of values to tree entries.
6208   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6209   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6210     if (EntryPtr.get() == TE)
6211       break;
6212     if (EntryPtr->State != TreeEntry::NeedToGather)
6213       continue;
6214     for (Value *V : EntryPtr->Scalars)
6215       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6216   }
6217   // Find all tree entries used by the gathered values. If no common entries
6218   // found - not a shuffle.
6219   // Here we build a set of tree nodes for each gathered value and trying to
6220   // find the intersection between these sets. If we have at least one common
6221   // tree node for each gathered value - we have just a permutation of the
6222   // single vector. If we have 2 different sets, we're in situation where we
6223   // have a permutation of 2 input vectors.
6224   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6225   DenseMap<Value *, int> UsedValuesEntry;
6226   for (Value *V : TE->Scalars) {
6227     if (isa<UndefValue>(V))
6228       continue;
6229     // Build a list of tree entries where V is used.
6230     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6231     auto It = ValueToTEs.find(V);
6232     if (It != ValueToTEs.end())
6233       VToTEs = It->second;
6234     if (const TreeEntry *VTE = getTreeEntry(V))
6235       VToTEs.insert(VTE);
6236     if (VToTEs.empty())
6237       return None;
6238     if (UsedTEs.empty()) {
6239       // The first iteration, just insert the list of nodes to vector.
6240       UsedTEs.push_back(VToTEs);
6241     } else {
6242       // Need to check if there are any previously used tree nodes which use V.
6243       // If there are no such nodes, consider that we have another one input
6244       // vector.
6245       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6246       unsigned Idx = 0;
6247       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6248         // Do we have a non-empty intersection of previously listed tree entries
6249         // and tree entries using current V?
6250         set_intersect(VToTEs, Set);
6251         if (!VToTEs.empty()) {
6252           // Yes, write the new subset and continue analysis for the next
6253           // scalar.
6254           Set.swap(VToTEs);
6255           break;
6256         }
6257         VToTEs = SavedVToTEs;
6258         ++Idx;
6259       }
6260       // No non-empty intersection found - need to add a second set of possible
6261       // source vectors.
6262       if (Idx == UsedTEs.size()) {
6263         // If the number of input vectors is greater than 2 - not a permutation,
6264         // fallback to the regular gather.
6265         if (UsedTEs.size() == 2)
6266           return None;
6267         UsedTEs.push_back(SavedVToTEs);
6268         Idx = UsedTEs.size() - 1;
6269       }
6270       UsedValuesEntry.try_emplace(V, Idx);
6271     }
6272   }
6273 
6274   unsigned VF = 0;
6275   if (UsedTEs.size() == 1) {
6276     // Try to find the perfect match in another gather node at first.
6277     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6278       return EntryPtr->isSame(TE->Scalars);
6279     });
6280     if (It != UsedTEs.front().end()) {
6281       Entries.push_back(*It);
6282       std::iota(Mask.begin(), Mask.end(), 0);
6283       return TargetTransformInfo::SK_PermuteSingleSrc;
6284     }
6285     // No perfect match, just shuffle, so choose the first tree node.
6286     Entries.push_back(*UsedTEs.front().begin());
6287   } else {
6288     // Try to find nodes with the same vector factor.
6289     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6290     DenseMap<int, const TreeEntry *> VFToTE;
6291     for (const TreeEntry *TE : UsedTEs.front())
6292       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6293     for (const TreeEntry *TE : UsedTEs.back()) {
6294       auto It = VFToTE.find(TE->getVectorFactor());
6295       if (It != VFToTE.end()) {
6296         VF = It->first;
6297         Entries.push_back(It->second);
6298         Entries.push_back(TE);
6299         break;
6300       }
6301     }
6302     // No 2 source vectors with the same vector factor - give up and do regular
6303     // gather.
6304     if (Entries.empty())
6305       return None;
6306   }
6307 
6308   // Build a shuffle mask for better cost estimation and vector emission.
6309   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6310     Value *V = TE->Scalars[I];
6311     if (isa<UndefValue>(V))
6312       continue;
6313     unsigned Idx = UsedValuesEntry.lookup(V);
6314     const TreeEntry *VTE = Entries[Idx];
6315     int FoundLane = VTE->findLaneForValue(V);
6316     Mask[I] = Idx * VF + FoundLane;
6317     // Extra check required by isSingleSourceMaskImpl function (called by
6318     // ShuffleVectorInst::isSingleSourceMask).
6319     if (Mask[I] >= 2 * E)
6320       return None;
6321   }
6322   switch (Entries.size()) {
6323   case 1:
6324     return TargetTransformInfo::SK_PermuteSingleSrc;
6325   case 2:
6326     return TargetTransformInfo::SK_PermuteTwoSrc;
6327   default:
6328     break;
6329   }
6330   return None;
6331 }
6332 
6333 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6334                                        const APInt &ShuffledIndices,
6335                                        bool NeedToShuffle) const {
6336   InstructionCost Cost =
6337       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6338                                     /*Extract*/ false);
6339   if (NeedToShuffle)
6340     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6341   return Cost;
6342 }
6343 
6344 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6345   // Find the type of the operands in VL.
6346   Type *ScalarTy = VL[0]->getType();
6347   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6348     ScalarTy = SI->getValueOperand()->getType();
6349   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6350   bool DuplicateNonConst = false;
6351   // Find the cost of inserting/extracting values from the vector.
6352   // Check if the same elements are inserted several times and count them as
6353   // shuffle candidates.
6354   APInt ShuffledElements = APInt::getZero(VL.size());
6355   DenseSet<Value *> UniqueElements;
6356   // Iterate in reverse order to consider insert elements with the high cost.
6357   for (unsigned I = VL.size(); I > 0; --I) {
6358     unsigned Idx = I - 1;
6359     // No need to shuffle duplicates for constants.
6360     if (isConstant(VL[Idx])) {
6361       ShuffledElements.setBit(Idx);
6362       continue;
6363     }
6364     if (!UniqueElements.insert(VL[Idx]).second) {
6365       DuplicateNonConst = true;
6366       ShuffledElements.setBit(Idx);
6367     }
6368   }
6369   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6370 }
6371 
6372 // Perform operand reordering on the instructions in VL and return the reordered
6373 // operands in Left and Right.
6374 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6375                                              SmallVectorImpl<Value *> &Left,
6376                                              SmallVectorImpl<Value *> &Right,
6377                                              const DataLayout &DL,
6378                                              ScalarEvolution &SE,
6379                                              const BoUpSLP &R) {
6380   if (VL.empty())
6381     return;
6382   VLOperands Ops(VL, DL, SE, R);
6383   // Reorder the operands in place.
6384   Ops.reorder();
6385   Left = Ops.getVL(0);
6386   Right = Ops.getVL(1);
6387 }
6388 
6389 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6390   // Get the basic block this bundle is in. All instructions in the bundle
6391   // should be in this block.
6392   auto *Front = E->getMainOp();
6393   auto *BB = Front->getParent();
6394   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6395     auto *I = cast<Instruction>(V);
6396     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6397   }));
6398 
6399   // The last instruction in the bundle in program order.
6400   Instruction *LastInst = nullptr;
6401 
6402   // Find the last instruction. The common case should be that BB has been
6403   // scheduled, and the last instruction is VL.back(). So we start with
6404   // VL.back() and iterate over schedule data until we reach the end of the
6405   // bundle. The end of the bundle is marked by null ScheduleData.
6406   if (BlocksSchedules.count(BB)) {
6407     auto *Bundle =
6408         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6409     if (Bundle && Bundle->isPartOfBundle())
6410       for (; Bundle; Bundle = Bundle->NextInBundle)
6411         if (Bundle->OpValue == Bundle->Inst)
6412           LastInst = Bundle->Inst;
6413   }
6414 
6415   // LastInst can still be null at this point if there's either not an entry
6416   // for BB in BlocksSchedules or there's no ScheduleData available for
6417   // VL.back(). This can be the case if buildTree_rec aborts for various
6418   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6419   // size is reached, etc.). ScheduleData is initialized in the scheduling
6420   // "dry-run".
6421   //
6422   // If this happens, we can still find the last instruction by brute force. We
6423   // iterate forwards from Front (inclusive) until we either see all
6424   // instructions in the bundle or reach the end of the block. If Front is the
6425   // last instruction in program order, LastInst will be set to Front, and we
6426   // will visit all the remaining instructions in the block.
6427   //
6428   // One of the reasons we exit early from buildTree_rec is to place an upper
6429   // bound on compile-time. Thus, taking an additional compile-time hit here is
6430   // not ideal. However, this should be exceedingly rare since it requires that
6431   // we both exit early from buildTree_rec and that the bundle be out-of-order
6432   // (causing us to iterate all the way to the end of the block).
6433   if (!LastInst) {
6434     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6435     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6436       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6437         LastInst = &I;
6438       if (Bundle.empty())
6439         break;
6440     }
6441   }
6442   assert(LastInst && "Failed to find last instruction in bundle");
6443 
6444   // Set the insertion point after the last instruction in the bundle. Set the
6445   // debug location to Front.
6446   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6447   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6448 }
6449 
6450 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6451   // List of instructions/lanes from current block and/or the blocks which are
6452   // part of the current loop. These instructions will be inserted at the end to
6453   // make it possible to optimize loops and hoist invariant instructions out of
6454   // the loops body with better chances for success.
6455   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6456   SmallSet<int, 4> PostponedIndices;
6457   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6458   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6459     SmallPtrSet<BasicBlock *, 4> Visited;
6460     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6461       InsertBB = InsertBB->getSinglePredecessor();
6462     return InsertBB && InsertBB == InstBB;
6463   };
6464   for (int I = 0, E = VL.size(); I < E; ++I) {
6465     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6466       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6467            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6468           PostponedIndices.insert(I).second)
6469         PostponedInsts.emplace_back(Inst, I);
6470   }
6471 
6472   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6473     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6474     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6475     if (!InsElt)
6476       return Vec;
6477     GatherShuffleSeq.insert(InsElt);
6478     CSEBlocks.insert(InsElt->getParent());
6479     // Add to our 'need-to-extract' list.
6480     if (TreeEntry *Entry = getTreeEntry(V)) {
6481       // Find which lane we need to extract.
6482       unsigned FoundLane = Entry->findLaneForValue(V);
6483       ExternalUses.emplace_back(V, InsElt, FoundLane);
6484     }
6485     return Vec;
6486   };
6487   Value *Val0 =
6488       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6489   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6490   Value *Vec = PoisonValue::get(VecTy);
6491   SmallVector<int> NonConsts;
6492   // Insert constant values at first.
6493   for (int I = 0, E = VL.size(); I < E; ++I) {
6494     if (PostponedIndices.contains(I))
6495       continue;
6496     if (!isConstant(VL[I])) {
6497       NonConsts.push_back(I);
6498       continue;
6499     }
6500     Vec = CreateInsertElement(Vec, VL[I], I);
6501   }
6502   // Insert non-constant values.
6503   for (int I : NonConsts)
6504     Vec = CreateInsertElement(Vec, VL[I], I);
6505   // Append instructions, which are/may be part of the loop, in the end to make
6506   // it possible to hoist non-loop-based instructions.
6507   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6508     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6509 
6510   return Vec;
6511 }
6512 
6513 namespace {
6514 /// Merges shuffle masks and emits final shuffle instruction, if required.
6515 class ShuffleInstructionBuilder {
6516   IRBuilderBase &Builder;
6517   const unsigned VF = 0;
6518   bool IsFinalized = false;
6519   SmallVector<int, 4> Mask;
6520   /// Holds all of the instructions that we gathered.
6521   SetVector<Instruction *> &GatherShuffleSeq;
6522   /// A list of blocks that we are going to CSE.
6523   SetVector<BasicBlock *> &CSEBlocks;
6524 
6525 public:
6526   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6527                             SetVector<Instruction *> &GatherShuffleSeq,
6528                             SetVector<BasicBlock *> &CSEBlocks)
6529       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6530         CSEBlocks(CSEBlocks) {}
6531 
6532   /// Adds a mask, inverting it before applying.
6533   void addInversedMask(ArrayRef<unsigned> SubMask) {
6534     if (SubMask.empty())
6535       return;
6536     SmallVector<int, 4> NewMask;
6537     inversePermutation(SubMask, NewMask);
6538     addMask(NewMask);
6539   }
6540 
6541   /// Functions adds masks, merging them into  single one.
6542   void addMask(ArrayRef<unsigned> SubMask) {
6543     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6544     addMask(NewMask);
6545   }
6546 
6547   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6548 
6549   Value *finalize(Value *V) {
6550     IsFinalized = true;
6551     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6552     if (VF == ValueVF && Mask.empty())
6553       return V;
6554     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6555     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6556     addMask(NormalizedMask);
6557 
6558     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6559       return V;
6560     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6561     if (auto *I = dyn_cast<Instruction>(Vec)) {
6562       GatherShuffleSeq.insert(I);
6563       CSEBlocks.insert(I->getParent());
6564     }
6565     return Vec;
6566   }
6567 
6568   ~ShuffleInstructionBuilder() {
6569     assert((IsFinalized || Mask.empty()) &&
6570            "Shuffle construction must be finalized.");
6571   }
6572 };
6573 } // namespace
6574 
6575 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6576   const unsigned VF = VL.size();
6577   InstructionsState S = getSameOpcode(VL);
6578   if (S.getOpcode()) {
6579     if (TreeEntry *E = getTreeEntry(S.OpValue))
6580       if (E->isSame(VL)) {
6581         Value *V = vectorizeTree(E);
6582         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6583           if (!E->ReuseShuffleIndices.empty()) {
6584             // Reshuffle to get only unique values.
6585             // If some of the scalars are duplicated in the vectorization tree
6586             // entry, we do not vectorize them but instead generate a mask for
6587             // the reuses. But if there are several users of the same entry,
6588             // they may have different vectorization factors. This is especially
6589             // important for PHI nodes. In this case, we need to adapt the
6590             // resulting instruction for the user vectorization factor and have
6591             // to reshuffle it again to take only unique elements of the vector.
6592             // Without this code the function incorrectly returns reduced vector
6593             // instruction with the same elements, not with the unique ones.
6594 
6595             // block:
6596             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6597             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6598             // ... (use %2)
6599             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6600             // br %block
6601             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6602             SmallSet<int, 4> UsedIdxs;
6603             int Pos = 0;
6604             int Sz = VL.size();
6605             for (int Idx : E->ReuseShuffleIndices) {
6606               if (Idx != Sz && Idx != UndefMaskElem &&
6607                   UsedIdxs.insert(Idx).second)
6608                 UniqueIdxs[Idx] = Pos;
6609               ++Pos;
6610             }
6611             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6612                                             "less than original vector size.");
6613             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6614             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6615           } else {
6616             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6617                    "Expected vectorization factor less "
6618                    "than original vector size.");
6619             SmallVector<int> UniformMask(VF, 0);
6620             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6621             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6622           }
6623           if (auto *I = dyn_cast<Instruction>(V)) {
6624             GatherShuffleSeq.insert(I);
6625             CSEBlocks.insert(I->getParent());
6626           }
6627         }
6628         return V;
6629       }
6630   }
6631 
6632   // Can't vectorize this, so simply build a new vector with each lane
6633   // corresponding to the requested value.
6634   return createBuildVector(VL);
6635 }
6636 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6637   unsigned VF = VL.size();
6638   // Exploit possible reuse of values across lanes.
6639   SmallVector<int> ReuseShuffleIndicies;
6640   SmallVector<Value *> UniqueValues;
6641   if (VL.size() > 2) {
6642     DenseMap<Value *, unsigned> UniquePositions;
6643     unsigned NumValues =
6644         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6645                                     return !isa<UndefValue>(V);
6646                                   }).base());
6647     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6648     int UniqueVals = 0;
6649     for (Value *V : VL.drop_back(VL.size() - VF)) {
6650       if (isa<UndefValue>(V)) {
6651         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6652         continue;
6653       }
6654       if (isConstant(V)) {
6655         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6656         UniqueValues.emplace_back(V);
6657         continue;
6658       }
6659       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6660       ReuseShuffleIndicies.emplace_back(Res.first->second);
6661       if (Res.second) {
6662         UniqueValues.emplace_back(V);
6663         ++UniqueVals;
6664       }
6665     }
6666     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6667       // Emit pure splat vector.
6668       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6669                                   UndefMaskElem);
6670     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6671       ReuseShuffleIndicies.clear();
6672       UniqueValues.clear();
6673       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6674     }
6675     UniqueValues.append(VF - UniqueValues.size(),
6676                         PoisonValue::get(VL[0]->getType()));
6677     VL = UniqueValues;
6678   }
6679 
6680   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6681                                            CSEBlocks);
6682   Value *Vec = gather(VL);
6683   if (!ReuseShuffleIndicies.empty()) {
6684     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6685     Vec = ShuffleBuilder.finalize(Vec);
6686   }
6687   return Vec;
6688 }
6689 
6690 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6691   IRBuilder<>::InsertPointGuard Guard(Builder);
6692 
6693   if (E->VectorizedValue) {
6694     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6695     return E->VectorizedValue;
6696   }
6697 
6698   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6699   unsigned VF = E->getVectorFactor();
6700   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6701                                            CSEBlocks);
6702   if (E->State == TreeEntry::NeedToGather) {
6703     if (E->getMainOp())
6704       setInsertPointAfterBundle(E);
6705     Value *Vec;
6706     SmallVector<int> Mask;
6707     SmallVector<const TreeEntry *> Entries;
6708     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6709         isGatherShuffledEntry(E, Mask, Entries);
6710     if (Shuffle.hasValue()) {
6711       assert((Entries.size() == 1 || Entries.size() == 2) &&
6712              "Expected shuffle of 1 or 2 entries.");
6713       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6714                                         Entries.back()->VectorizedValue, Mask);
6715       if (auto *I = dyn_cast<Instruction>(Vec)) {
6716         GatherShuffleSeq.insert(I);
6717         CSEBlocks.insert(I->getParent());
6718       }
6719     } else {
6720       Vec = gather(E->Scalars);
6721     }
6722     if (NeedToShuffleReuses) {
6723       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6724       Vec = ShuffleBuilder.finalize(Vec);
6725     }
6726     E->VectorizedValue = Vec;
6727     return Vec;
6728   }
6729 
6730   assert((E->State == TreeEntry::Vectorize ||
6731           E->State == TreeEntry::ScatterVectorize) &&
6732          "Unhandled state");
6733   unsigned ShuffleOrOp =
6734       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6735   Instruction *VL0 = E->getMainOp();
6736   Type *ScalarTy = VL0->getType();
6737   if (auto *Store = dyn_cast<StoreInst>(VL0))
6738     ScalarTy = Store->getValueOperand()->getType();
6739   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6740     ScalarTy = IE->getOperand(1)->getType();
6741   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6742   switch (ShuffleOrOp) {
6743     case Instruction::PHI: {
6744       assert(
6745           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6746           "PHI reordering is free.");
6747       auto *PH = cast<PHINode>(VL0);
6748       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6749       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6750       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6751       Value *V = NewPhi;
6752 
6753       // Adjust insertion point once all PHI's have been generated.
6754       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6755       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6756 
6757       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6758       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6759       V = ShuffleBuilder.finalize(V);
6760 
6761       E->VectorizedValue = V;
6762 
6763       // PHINodes may have multiple entries from the same block. We want to
6764       // visit every block once.
6765       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6766 
6767       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6768         ValueList Operands;
6769         BasicBlock *IBB = PH->getIncomingBlock(i);
6770 
6771         if (!VisitedBBs.insert(IBB).second) {
6772           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6773           continue;
6774         }
6775 
6776         Builder.SetInsertPoint(IBB->getTerminator());
6777         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6778         Value *Vec = vectorizeTree(E->getOperand(i));
6779         NewPhi->addIncoming(Vec, IBB);
6780       }
6781 
6782       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6783              "Invalid number of incoming values");
6784       return V;
6785     }
6786 
6787     case Instruction::ExtractElement: {
6788       Value *V = E->getSingleOperand(0);
6789       Builder.SetInsertPoint(VL0);
6790       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6791       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6792       V = ShuffleBuilder.finalize(V);
6793       E->VectorizedValue = V;
6794       return V;
6795     }
6796     case Instruction::ExtractValue: {
6797       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6798       Builder.SetInsertPoint(LI);
6799       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6800       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6801       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6802       if (MSSA) {
6803         MemorySSAUpdater MSSAU(MSSA);
6804         auto *Access = MSSA->getMemoryAccess(LI);
6805         assert(Access);
6806         MemoryUseOrDef *NewAccess =
6807           MSSAU.createMemoryAccessBefore(V, Access->getDefiningAccess(),
6808                                          Access);
6809         MSSAU.insertUse(cast<MemoryUse>(NewAccess), true);
6810       }
6811       Value *NewV = propagateMetadata(V, E->Scalars);
6812       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6813       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6814       NewV = ShuffleBuilder.finalize(NewV);
6815       E->VectorizedValue = NewV;
6816       return NewV;
6817     }
6818     case Instruction::InsertElement: {
6819       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6820       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6821       Value *V = vectorizeTree(E->getOperand(1));
6822 
6823       // Create InsertVector shuffle if necessary
6824       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6825         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6826       }));
6827       const unsigned NumElts =
6828           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6829       const unsigned NumScalars = E->Scalars.size();
6830 
6831       unsigned Offset = *getInsertIndex(VL0);
6832       assert(Offset < NumElts && "Failed to find vector index offset");
6833 
6834       // Create shuffle to resize vector
6835       SmallVector<int> Mask;
6836       if (!E->ReorderIndices.empty()) {
6837         inversePermutation(E->ReorderIndices, Mask);
6838         Mask.append(NumElts - NumScalars, UndefMaskElem);
6839       } else {
6840         Mask.assign(NumElts, UndefMaskElem);
6841         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6842       }
6843       // Create InsertVector shuffle if necessary
6844       bool IsIdentity = true;
6845       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6846       Mask.swap(PrevMask);
6847       for (unsigned I = 0; I < NumScalars; ++I) {
6848         Value *Scalar = E->Scalars[PrevMask[I]];
6849         unsigned InsertIdx = *getInsertIndex(Scalar);
6850         IsIdentity &= InsertIdx - Offset == I;
6851         Mask[InsertIdx - Offset] = I;
6852       }
6853       if (!IsIdentity || NumElts != NumScalars) {
6854         V = Builder.CreateShuffleVector(V, Mask);
6855         if (auto *I = dyn_cast<Instruction>(V)) {
6856           GatherShuffleSeq.insert(I);
6857           CSEBlocks.insert(I->getParent());
6858         }
6859       }
6860 
6861       if ((!IsIdentity || Offset != 0 ||
6862            !isUndefVector(FirstInsert->getOperand(0))) &&
6863           NumElts != NumScalars) {
6864         SmallVector<int> InsertMask(NumElts);
6865         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6866         for (unsigned I = 0; I < NumElts; I++) {
6867           if (Mask[I] != UndefMaskElem)
6868             InsertMask[Offset + I] = NumElts + I;
6869         }
6870 
6871         V = Builder.CreateShuffleVector(
6872             FirstInsert->getOperand(0), V, InsertMask,
6873             cast<Instruction>(E->Scalars.back())->getName());
6874         if (auto *I = dyn_cast<Instruction>(V)) {
6875           GatherShuffleSeq.insert(I);
6876           CSEBlocks.insert(I->getParent());
6877         }
6878       }
6879 
6880       ++NumVectorInstructions;
6881       E->VectorizedValue = V;
6882       return V;
6883     }
6884     case Instruction::ZExt:
6885     case Instruction::SExt:
6886     case Instruction::FPToUI:
6887     case Instruction::FPToSI:
6888     case Instruction::FPExt:
6889     case Instruction::PtrToInt:
6890     case Instruction::IntToPtr:
6891     case Instruction::SIToFP:
6892     case Instruction::UIToFP:
6893     case Instruction::Trunc:
6894     case Instruction::FPTrunc:
6895     case Instruction::BitCast: {
6896       setInsertPointAfterBundle(E);
6897 
6898       Value *InVec = vectorizeTree(E->getOperand(0));
6899 
6900       if (E->VectorizedValue) {
6901         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6902         return E->VectorizedValue;
6903       }
6904 
6905       auto *CI = cast<CastInst>(VL0);
6906       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6907       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6908       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6909       V = ShuffleBuilder.finalize(V);
6910 
6911       E->VectorizedValue = V;
6912       ++NumVectorInstructions;
6913       return V;
6914     }
6915     case Instruction::FCmp:
6916     case Instruction::ICmp: {
6917       setInsertPointAfterBundle(E);
6918 
6919       Value *L = vectorizeTree(E->getOperand(0));
6920       Value *R = vectorizeTree(E->getOperand(1));
6921 
6922       if (E->VectorizedValue) {
6923         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6924         return E->VectorizedValue;
6925       }
6926 
6927       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6928       Value *V = Builder.CreateCmp(P0, L, R);
6929       propagateIRFlags(V, E->Scalars, VL0);
6930       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6931       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6932       V = ShuffleBuilder.finalize(V);
6933 
6934       E->VectorizedValue = V;
6935       ++NumVectorInstructions;
6936       return V;
6937     }
6938     case Instruction::Select: {
6939       setInsertPointAfterBundle(E);
6940 
6941       Value *Cond = vectorizeTree(E->getOperand(0));
6942       Value *True = vectorizeTree(E->getOperand(1));
6943       Value *False = vectorizeTree(E->getOperand(2));
6944 
6945       if (E->VectorizedValue) {
6946         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6947         return E->VectorizedValue;
6948       }
6949 
6950       Value *V = Builder.CreateSelect(Cond, True, False);
6951       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6952       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6953       V = ShuffleBuilder.finalize(V);
6954 
6955       E->VectorizedValue = V;
6956       ++NumVectorInstructions;
6957       return V;
6958     }
6959     case Instruction::FNeg: {
6960       setInsertPointAfterBundle(E);
6961 
6962       Value *Op = vectorizeTree(E->getOperand(0));
6963 
6964       if (E->VectorizedValue) {
6965         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6966         return E->VectorizedValue;
6967       }
6968 
6969       Value *V = Builder.CreateUnOp(
6970           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6971       propagateIRFlags(V, E->Scalars, VL0);
6972       if (auto *I = dyn_cast<Instruction>(V))
6973         V = propagateMetadata(I, E->Scalars);
6974 
6975       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6976       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6977       V = ShuffleBuilder.finalize(V);
6978 
6979       E->VectorizedValue = V;
6980       ++NumVectorInstructions;
6981 
6982       return V;
6983     }
6984     case Instruction::Add:
6985     case Instruction::FAdd:
6986     case Instruction::Sub:
6987     case Instruction::FSub:
6988     case Instruction::Mul:
6989     case Instruction::FMul:
6990     case Instruction::UDiv:
6991     case Instruction::SDiv:
6992     case Instruction::FDiv:
6993     case Instruction::URem:
6994     case Instruction::SRem:
6995     case Instruction::FRem:
6996     case Instruction::Shl:
6997     case Instruction::LShr:
6998     case Instruction::AShr:
6999     case Instruction::And:
7000     case Instruction::Or:
7001     case Instruction::Xor: {
7002       setInsertPointAfterBundle(E);
7003 
7004       Value *LHS = vectorizeTree(E->getOperand(0));
7005       Value *RHS = vectorizeTree(E->getOperand(1));
7006 
7007       if (E->VectorizedValue) {
7008         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7009         return E->VectorizedValue;
7010       }
7011 
7012       Value *V = Builder.CreateBinOp(
7013           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7014           RHS);
7015       propagateIRFlags(V, E->Scalars, VL0);
7016       if (auto *I = dyn_cast<Instruction>(V))
7017         V = propagateMetadata(I, E->Scalars);
7018 
7019       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7020       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7021       V = ShuffleBuilder.finalize(V);
7022 
7023       E->VectorizedValue = V;
7024       ++NumVectorInstructions;
7025 
7026       return V;
7027     }
7028     case Instruction::Load: {
7029       // Loads are inserted at the head of the tree because we don't want to
7030       // sink them all the way down past store instructions.
7031       setInsertPointAfterBundle(E);
7032 
7033       LoadInst *LI = cast<LoadInst>(VL0);
7034       Instruction *NewLI;
7035       unsigned AS = LI->getPointerAddressSpace();
7036       Value *PO = LI->getPointerOperand();
7037       if (E->State == TreeEntry::Vectorize) {
7038         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7039         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7040 
7041         // The pointer operand uses an in-tree scalar so we add the new BitCast
7042         // or LoadInst to ExternalUses list to make sure that an extract will
7043         // be generated in the future.
7044         if (TreeEntry *Entry = getTreeEntry(PO)) {
7045           // Find which lane we need to extract.
7046           unsigned FoundLane = Entry->findLaneForValue(PO);
7047           ExternalUses.emplace_back(
7048               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7049         }
7050       } else {
7051         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7052         Value *VecPtr = vectorizeTree(E->getOperand(0));
7053         // Use the minimum alignment of the gathered loads.
7054         Align CommonAlignment = LI->getAlign();
7055         for (Value *V : E->Scalars)
7056           CommonAlignment =
7057               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7058         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7059       }
7060 
7061       if (MSSA) {
7062         MemorySSAUpdater MSSAU(MSSA);
7063         auto *Access = MSSA->getMemoryAccess(LI);
7064         assert(Access);
7065         MemoryUseOrDef *NewAccess =
7066           MSSAU.createMemoryAccessAfter(NewLI, Access->getDefiningAccess(),
7067                                         Access);
7068         MSSAU.insertUse(cast<MemoryUse>(NewAccess), true);
7069       }
7070 
7071       Value *V = propagateMetadata(NewLI, E->Scalars);
7072 
7073       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7074       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7075       V = ShuffleBuilder.finalize(V);
7076       E->VectorizedValue = V;
7077       ++NumVectorInstructions;
7078       return V;
7079     }
7080     case Instruction::Store: {
7081       auto *SI = cast<StoreInst>(VL0);
7082       unsigned AS = SI->getPointerAddressSpace();
7083 
7084       setInsertPointAfterBundle(E);
7085 
7086       Value *VecValue = vectorizeTree(E->getOperand(0));
7087       ShuffleBuilder.addMask(E->ReorderIndices);
7088       VecValue = ShuffleBuilder.finalize(VecValue);
7089 
7090       Value *ScalarPtr = SI->getPointerOperand();
7091       Value *VecPtr = Builder.CreateBitCast(
7092           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7093       StoreInst *ST =
7094           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7095 
7096       if (MSSA) {
7097         MemorySSAUpdater MSSAU(MSSA);
7098         auto *Access = MSSA->getMemoryAccess(SI);
7099         assert(Access);
7100         MemoryUseOrDef *NewAccess =
7101           MSSAU.createMemoryAccessAfter(ST, Access->getDefiningAccess(),
7102                                         Access);
7103         MSSAU.insertDef(cast<MemoryDef>(NewAccess), true);
7104       }
7105 
7106       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7107       // StoreInst to ExternalUses to make sure that an extract will be
7108       // generated in the future.
7109       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7110         // Find which lane we need to extract.
7111         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7112         ExternalUses.push_back(ExternalUser(
7113             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7114             FoundLane));
7115       }
7116 
7117       Value *V = propagateMetadata(ST, E->Scalars);
7118 
7119       E->VectorizedValue = V;
7120       ++NumVectorInstructions;
7121       return V;
7122     }
7123     case Instruction::GetElementPtr: {
7124       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7125       setInsertPointAfterBundle(E);
7126 
7127       Value *Op0 = vectorizeTree(E->getOperand(0));
7128 
7129       SmallVector<Value *> OpVecs;
7130       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7131         Value *OpVec = vectorizeTree(E->getOperand(J));
7132         OpVecs.push_back(OpVec);
7133       }
7134 
7135       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7136       if (Instruction *I = dyn_cast<Instruction>(V))
7137         V = propagateMetadata(I, E->Scalars);
7138 
7139       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7140       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7141       V = ShuffleBuilder.finalize(V);
7142 
7143       E->VectorizedValue = V;
7144       ++NumVectorInstructions;
7145 
7146       return V;
7147     }
7148     case Instruction::Call: {
7149       CallInst *CI = cast<CallInst>(VL0);
7150       setInsertPointAfterBundle(E);
7151 
7152       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7153       if (Function *FI = CI->getCalledFunction())
7154         IID = FI->getIntrinsicID();
7155 
7156       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7157 
7158       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7159       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7160                           VecCallCosts.first <= VecCallCosts.second;
7161 
7162       Value *ScalarArg = nullptr;
7163       std::vector<Value *> OpVecs;
7164       SmallVector<Type *, 2> TysForDecl =
7165           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7166       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7167         ValueList OpVL;
7168         // Some intrinsics have scalar arguments. This argument should not be
7169         // vectorized.
7170         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7171           CallInst *CEI = cast<CallInst>(VL0);
7172           ScalarArg = CEI->getArgOperand(j);
7173           OpVecs.push_back(CEI->getArgOperand(j));
7174           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7175             TysForDecl.push_back(ScalarArg->getType());
7176           continue;
7177         }
7178 
7179         Value *OpVec = vectorizeTree(E->getOperand(j));
7180         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7181         OpVecs.push_back(OpVec);
7182       }
7183 
7184       Function *CF;
7185       if (!UseIntrinsic) {
7186         VFShape Shape =
7187             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7188                                   VecTy->getNumElements())),
7189                          false /*HasGlobalPred*/);
7190         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7191       } else {
7192         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7193       }
7194 
7195       SmallVector<OperandBundleDef, 1> OpBundles;
7196       CI->getOperandBundlesAsDefs(OpBundles);
7197       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7198 
7199       // The scalar argument uses an in-tree scalar so we add the new vectorized
7200       // call to ExternalUses list to make sure that an extract will be
7201       // generated in the future.
7202       if (ScalarArg) {
7203         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7204           // Find which lane we need to extract.
7205           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7206           ExternalUses.push_back(
7207               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7208         }
7209       }
7210 
7211       propagateIRFlags(V, E->Scalars, VL0);
7212       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7213       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7214       V = ShuffleBuilder.finalize(V);
7215 
7216       E->VectorizedValue = V;
7217       ++NumVectorInstructions;
7218       return V;
7219     }
7220     case Instruction::ShuffleVector: {
7221       assert(E->isAltShuffle() &&
7222              ((Instruction::isBinaryOp(E->getOpcode()) &&
7223                Instruction::isBinaryOp(E->getAltOpcode())) ||
7224               (Instruction::isCast(E->getOpcode()) &&
7225                Instruction::isCast(E->getAltOpcode())) ||
7226               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7227              "Invalid Shuffle Vector Operand");
7228 
7229       Value *LHS = nullptr, *RHS = nullptr;
7230       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7231         setInsertPointAfterBundle(E);
7232         LHS = vectorizeTree(E->getOperand(0));
7233         RHS = vectorizeTree(E->getOperand(1));
7234       } else {
7235         setInsertPointAfterBundle(E);
7236         LHS = vectorizeTree(E->getOperand(0));
7237       }
7238 
7239       if (E->VectorizedValue) {
7240         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7241         return E->VectorizedValue;
7242       }
7243 
7244       Value *V0, *V1;
7245       if (Instruction::isBinaryOp(E->getOpcode())) {
7246         V0 = Builder.CreateBinOp(
7247             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7248         V1 = Builder.CreateBinOp(
7249             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7250       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7251         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7252         auto *AltCI = cast<CmpInst>(E->getAltOp());
7253         CmpInst::Predicate AltPred = AltCI->getPredicate();
7254         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7255       } else {
7256         V0 = Builder.CreateCast(
7257             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7258         V1 = Builder.CreateCast(
7259             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7260       }
7261       // Add V0 and V1 to later analysis to try to find and remove matching
7262       // instruction, if any.
7263       for (Value *V : {V0, V1}) {
7264         if (auto *I = dyn_cast<Instruction>(V)) {
7265           GatherShuffleSeq.insert(I);
7266           CSEBlocks.insert(I->getParent());
7267         }
7268       }
7269 
7270       // Create shuffle to take alternate operations from the vector.
7271       // Also, gather up main and alt scalar ops to propagate IR flags to
7272       // each vector operation.
7273       ValueList OpScalars, AltScalars;
7274       SmallVector<int> Mask;
7275       buildShuffleEntryMask(
7276           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7277           [E](Instruction *I) {
7278             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7279             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7280           },
7281           Mask, &OpScalars, &AltScalars);
7282 
7283       propagateIRFlags(V0, OpScalars);
7284       propagateIRFlags(V1, AltScalars);
7285 
7286       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7287       if (auto *I = dyn_cast<Instruction>(V)) {
7288         V = propagateMetadata(I, E->Scalars);
7289         GatherShuffleSeq.insert(I);
7290         CSEBlocks.insert(I->getParent());
7291       }
7292       V = ShuffleBuilder.finalize(V);
7293 
7294       E->VectorizedValue = V;
7295       ++NumVectorInstructions;
7296 
7297       return V;
7298     }
7299     default:
7300     llvm_unreachable("unknown inst");
7301   }
7302   return nullptr;
7303 }
7304 
7305 Value *BoUpSLP::vectorizeTree() {
7306   ExtraValueToDebugLocsMap ExternallyUsedValues;
7307   return vectorizeTree(ExternallyUsedValues);
7308 }
7309 
7310 Value *
7311 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7312   // All blocks must be scheduled before any instructions are inserted.
7313   for (auto &BSIter : BlocksSchedules) {
7314     scheduleBlock(BSIter.second.get());
7315   }
7316 
7317   Builder.SetInsertPoint(&F->getEntryBlock().front());
7318   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7319 
7320   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7321   // vectorized root. InstCombine will then rewrite the entire expression. We
7322   // sign extend the extracted values below.
7323   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7324   if (MinBWs.count(ScalarRoot)) {
7325     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7326       // If current instr is a phi and not the last phi, insert it after the
7327       // last phi node.
7328       if (isa<PHINode>(I))
7329         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7330       else
7331         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7332     }
7333     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7334     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7335     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7336     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7337     VectorizableTree[0]->VectorizedValue = Trunc;
7338   }
7339 
7340   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7341                     << " values .\n");
7342 
7343   // Extract all of the elements with the external uses.
7344   for (const auto &ExternalUse : ExternalUses) {
7345     Value *Scalar = ExternalUse.Scalar;
7346     llvm::User *User = ExternalUse.User;
7347 
7348     // Skip users that we already RAUW. This happens when one instruction
7349     // has multiple uses of the same value.
7350     if (User && !is_contained(Scalar->users(), User))
7351       continue;
7352     TreeEntry *E = getTreeEntry(Scalar);
7353     assert(E && "Invalid scalar");
7354     assert(E->State != TreeEntry::NeedToGather &&
7355            "Extracting from a gather list");
7356 
7357     Value *Vec = E->VectorizedValue;
7358     assert(Vec && "Can't find vectorizable value");
7359 
7360     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7361     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7362       if (Scalar->getType() != Vec->getType()) {
7363         Value *Ex;
7364         // "Reuse" the existing extract to improve final codegen.
7365         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7366           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7367                                             ES->getOperand(1));
7368         } else {
7369           Ex = Builder.CreateExtractElement(Vec, Lane);
7370         }
7371         // If necessary, sign-extend or zero-extend ScalarRoot
7372         // to the larger type.
7373         if (!MinBWs.count(ScalarRoot))
7374           return Ex;
7375         if (MinBWs[ScalarRoot].second)
7376           return Builder.CreateSExt(Ex, Scalar->getType());
7377         return Builder.CreateZExt(Ex, Scalar->getType());
7378       }
7379       assert(isa<FixedVectorType>(Scalar->getType()) &&
7380              isa<InsertElementInst>(Scalar) &&
7381              "In-tree scalar of vector type is not insertelement?");
7382       return Vec;
7383     };
7384     // If User == nullptr, the Scalar is used as extra arg. Generate
7385     // ExtractElement instruction and update the record for this scalar in
7386     // ExternallyUsedValues.
7387     if (!User) {
7388       assert(ExternallyUsedValues.count(Scalar) &&
7389              "Scalar with nullptr as an external user must be registered in "
7390              "ExternallyUsedValues map");
7391       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7392         Builder.SetInsertPoint(VecI->getParent(),
7393                                std::next(VecI->getIterator()));
7394       } else {
7395         Builder.SetInsertPoint(&F->getEntryBlock().front());
7396       }
7397       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7398       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7399       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7400       auto It = ExternallyUsedValues.find(Scalar);
7401       assert(It != ExternallyUsedValues.end() &&
7402              "Externally used scalar is not found in ExternallyUsedValues");
7403       NewInstLocs.append(It->second);
7404       ExternallyUsedValues.erase(Scalar);
7405       // Required to update internally referenced instructions.
7406       Scalar->replaceAllUsesWith(NewInst);
7407       continue;
7408     }
7409 
7410     // Generate extracts for out-of-tree users.
7411     // Find the insertion point for the extractelement lane.
7412     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7413       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7414         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7415           if (PH->getIncomingValue(i) == Scalar) {
7416             Instruction *IncomingTerminator =
7417                 PH->getIncomingBlock(i)->getTerminator();
7418             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7419               Builder.SetInsertPoint(VecI->getParent(),
7420                                      std::next(VecI->getIterator()));
7421             } else {
7422               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7423             }
7424             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7425             CSEBlocks.insert(PH->getIncomingBlock(i));
7426             PH->setOperand(i, NewInst);
7427           }
7428         }
7429       } else {
7430         Builder.SetInsertPoint(cast<Instruction>(User));
7431         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7432         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7433         User->replaceUsesOfWith(Scalar, NewInst);
7434       }
7435     } else {
7436       Builder.SetInsertPoint(&F->getEntryBlock().front());
7437       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7438       CSEBlocks.insert(&F->getEntryBlock());
7439       User->replaceUsesOfWith(Scalar, NewInst);
7440     }
7441 
7442     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7443   }
7444 
7445   // For each vectorized value:
7446   for (auto &TEPtr : VectorizableTree) {
7447     TreeEntry *Entry = TEPtr.get();
7448 
7449     // No need to handle users of gathered values.
7450     if (Entry->State == TreeEntry::NeedToGather)
7451       continue;
7452 
7453     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7454 
7455     // For each lane:
7456     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7457       Value *Scalar = Entry->Scalars[Lane];
7458 
7459 #ifndef NDEBUG
7460       Type *Ty = Scalar->getType();
7461       if (!Ty->isVoidTy()) {
7462         for (User *U : Scalar->users()) {
7463           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7464 
7465           // It is legal to delete users in the ignorelist.
7466           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7467                   (isa_and_nonnull<Instruction>(U) &&
7468                    isDeleted(cast<Instruction>(U)))) &&
7469                  "Deleting out-of-tree value");
7470         }
7471       }
7472 #endif
7473       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7474       eraseInstruction(cast<Instruction>(Scalar));
7475     }
7476   }
7477 
7478   Builder.ClearInsertionPoint();
7479   InstrElementSize.clear();
7480 
7481   return VectorizableTree[0]->VectorizedValue;
7482 }
7483 
7484 void BoUpSLP::optimizeGatherSequence() {
7485   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7486                     << " gather sequences instructions.\n");
7487   // LICM InsertElementInst sequences.
7488   for (Instruction *I : GatherShuffleSeq) {
7489     if (isDeleted(I))
7490       continue;
7491 
7492     // Check if this block is inside a loop.
7493     Loop *L = LI->getLoopFor(I->getParent());
7494     if (!L)
7495       continue;
7496 
7497     // Check if it has a preheader.
7498     BasicBlock *PreHeader = L->getLoopPreheader();
7499     if (!PreHeader)
7500       continue;
7501 
7502     // If the vector or the element that we insert into it are
7503     // instructions that are defined in this basic block then we can't
7504     // hoist this instruction.
7505     if (any_of(I->operands(), [L](Value *V) {
7506           auto *OpI = dyn_cast<Instruction>(V);
7507           return OpI && L->contains(OpI);
7508         }))
7509       continue;
7510 
7511     // We can hoist this instruction. Move it to the pre-header.
7512     I->moveBefore(PreHeader->getTerminator());
7513   }
7514 
7515   // Make a list of all reachable blocks in our CSE queue.
7516   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7517   CSEWorkList.reserve(CSEBlocks.size());
7518   for (BasicBlock *BB : CSEBlocks)
7519     if (DomTreeNode *N = DT->getNode(BB)) {
7520       assert(DT->isReachableFromEntry(N));
7521       CSEWorkList.push_back(N);
7522     }
7523 
7524   // Sort blocks by domination. This ensures we visit a block after all blocks
7525   // dominating it are visited.
7526   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7527     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7528            "Different nodes should have different DFS numbers");
7529     return A->getDFSNumIn() < B->getDFSNumIn();
7530   });
7531 
7532   // Less defined shuffles can be replaced by the more defined copies.
7533   // Between two shuffles one is less defined if it has the same vector operands
7534   // and its mask indeces are the same as in the first one or undefs. E.g.
7535   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7536   // poison, <0, 0, 0, 0>.
7537   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7538                                            SmallVectorImpl<int> &NewMask) {
7539     if (I1->getType() != I2->getType())
7540       return false;
7541     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7542     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7543     if (!SI1 || !SI2)
7544       return I1->isIdenticalTo(I2);
7545     if (SI1->isIdenticalTo(SI2))
7546       return true;
7547     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7548       if (SI1->getOperand(I) != SI2->getOperand(I))
7549         return false;
7550     // Check if the second instruction is more defined than the first one.
7551     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7552     ArrayRef<int> SM1 = SI1->getShuffleMask();
7553     // Count trailing undefs in the mask to check the final number of used
7554     // registers.
7555     unsigned LastUndefsCnt = 0;
7556     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7557       if (SM1[I] == UndefMaskElem)
7558         ++LastUndefsCnt;
7559       else
7560         LastUndefsCnt = 0;
7561       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7562           NewMask[I] != SM1[I])
7563         return false;
7564       if (NewMask[I] == UndefMaskElem)
7565         NewMask[I] = SM1[I];
7566     }
7567     // Check if the last undefs actually change the final number of used vector
7568     // registers.
7569     return SM1.size() - LastUndefsCnt > 1 &&
7570            TTI->getNumberOfParts(SI1->getType()) ==
7571                TTI->getNumberOfParts(
7572                    FixedVectorType::get(SI1->getType()->getElementType(),
7573                                         SM1.size() - LastUndefsCnt));
7574   };
7575   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7576   // instructions. TODO: We can further optimize this scan if we split the
7577   // instructions into different buckets based on the insert lane.
7578   SmallVector<Instruction *, 16> Visited;
7579   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7580     assert(*I &&
7581            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7582            "Worklist not sorted properly!");
7583     BasicBlock *BB = (*I)->getBlock();
7584     // For all instructions in blocks containing gather sequences:
7585     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7586       if (isDeleted(&In))
7587         continue;
7588       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7589           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7590         continue;
7591 
7592       // Check if we can replace this instruction with any of the
7593       // visited instructions.
7594       bool Replaced = false;
7595       for (Instruction *&V : Visited) {
7596         SmallVector<int> NewMask;
7597         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7598             DT->dominates(V->getParent(), In.getParent())) {
7599           In.replaceAllUsesWith(V);
7600           eraseInstruction(&In);
7601           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7602             if (!NewMask.empty())
7603               SI->setShuffleMask(NewMask);
7604           Replaced = true;
7605           break;
7606         }
7607         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7608             GatherShuffleSeq.contains(V) &&
7609             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7610             DT->dominates(In.getParent(), V->getParent())) {
7611           In.moveAfter(V);
7612           V->replaceAllUsesWith(&In);
7613           eraseInstruction(V);
7614           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7615             if (!NewMask.empty())
7616               SI->setShuffleMask(NewMask);
7617           V = &In;
7618           Replaced = true;
7619           break;
7620         }
7621       }
7622       if (!Replaced) {
7623         assert(!is_contained(Visited, &In));
7624         Visited.push_back(&In);
7625       }
7626     }
7627   }
7628   CSEBlocks.clear();
7629   GatherShuffleSeq.clear();
7630 }
7631 
7632 BoUpSLP::ScheduleData *
7633 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7634   ScheduleData *Bundle = nullptr;
7635   ScheduleData *PrevInBundle = nullptr;
7636   for (Value *V : VL) {
7637     ScheduleData *BundleMember = getScheduleData(V);
7638     assert(BundleMember &&
7639            "no ScheduleData for bundle member "
7640            "(maybe not in same basic block)");
7641     assert(BundleMember->isSchedulingEntity() &&
7642            "bundle member already part of other bundle");
7643     if (PrevInBundle) {
7644       PrevInBundle->NextInBundle = BundleMember;
7645     } else {
7646       Bundle = BundleMember;
7647     }
7648 
7649     // Group the instructions to a bundle.
7650     BundleMember->FirstInBundle = Bundle;
7651     PrevInBundle = BundleMember;
7652   }
7653   assert(Bundle && "Failed to find schedule bundle");
7654   return Bundle;
7655 }
7656 
7657 // Groups the instructions to a bundle (which is then a single scheduling entity)
7658 // and schedules instructions until the bundle gets ready.
7659 Optional<BoUpSLP::ScheduleData *>
7660 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7661                                             const InstructionsState &S) {
7662   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7663   // instructions.
7664   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7665     return nullptr;
7666 
7667   // Initialize the instruction bundle.
7668   Instruction *OldScheduleEnd = ScheduleEnd;
7669   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7670 
7671   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7672                                                          ScheduleData *Bundle) {
7673     // The scheduling region got new instructions at the lower end (or it is a
7674     // new region for the first bundle). This makes it necessary to
7675     // recalculate all dependencies.
7676     // It is seldom that this needs to be done a second time after adding the
7677     // initial bundle to the region.
7678     if (ScheduleEnd != OldScheduleEnd) {
7679       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7680         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7681       ReSchedule = true;
7682     }
7683     if (Bundle) {
7684       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7685                         << " in block " << BB->getName() << "\n");
7686       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7687     }
7688 
7689     if (ReSchedule) {
7690       resetSchedule();
7691       initialFillReadyList(ReadyInsts);
7692     }
7693 
7694     // Now try to schedule the new bundle or (if no bundle) just calculate
7695     // dependencies. As soon as the bundle is "ready" it means that there are no
7696     // cyclic dependencies and we can schedule it. Note that's important that we
7697     // don't "schedule" the bundle yet (see cancelScheduling).
7698     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7699            !ReadyInsts.empty()) {
7700       ScheduleData *Picked = ReadyInsts.pop_back_val();
7701       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7702              "must be ready to schedule");
7703       schedule(Picked, ReadyInsts);
7704     }
7705   };
7706 
7707   // Make sure that the scheduling region contains all
7708   // instructions of the bundle.
7709   for (Value *V : VL) {
7710     if (!extendSchedulingRegion(V, S)) {
7711       // If the scheduling region got new instructions at the lower end (or it
7712       // is a new region for the first bundle). This makes it necessary to
7713       // recalculate all dependencies.
7714       // Otherwise the compiler may crash trying to incorrectly calculate
7715       // dependencies and emit instruction in the wrong order at the actual
7716       // scheduling.
7717       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7718       return None;
7719     }
7720   }
7721 
7722   bool ReSchedule = false;
7723   for (Value *V : VL) {
7724     ScheduleData *BundleMember = getScheduleData(V);
7725     assert(BundleMember &&
7726            "no ScheduleData for bundle member (maybe not in same basic block)");
7727 
7728     // Make sure we don't leave the pieces of the bundle in the ready list when
7729     // whole bundle might not be ready.
7730     ReadyInsts.remove(BundleMember);
7731 
7732     if (!BundleMember->IsScheduled)
7733       continue;
7734     // A bundle member was scheduled as single instruction before and now
7735     // needs to be scheduled as part of the bundle. We just get rid of the
7736     // existing schedule.
7737     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7738                       << " was already scheduled\n");
7739     ReSchedule = true;
7740   }
7741 
7742   auto *Bundle = buildBundle(VL);
7743   TryScheduleBundleImpl(ReSchedule, Bundle);
7744   if (!Bundle->isReady()) {
7745     cancelScheduling(VL, S.OpValue);
7746     return None;
7747   }
7748   return Bundle;
7749 }
7750 
7751 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7752                                                 Value *OpValue) {
7753   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7754     return;
7755 
7756   ScheduleData *Bundle = getScheduleData(OpValue);
7757   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7758   assert(!Bundle->IsScheduled &&
7759          "Can't cancel bundle which is already scheduled");
7760   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7761          "tried to unbundle something which is not a bundle");
7762 
7763   // Remove the bundle from the ready list.
7764   if (Bundle->isReady())
7765     ReadyInsts.remove(Bundle);
7766 
7767   // Un-bundle: make single instructions out of the bundle.
7768   ScheduleData *BundleMember = Bundle;
7769   while (BundleMember) {
7770     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7771     BundleMember->FirstInBundle = BundleMember;
7772     ScheduleData *Next = BundleMember->NextInBundle;
7773     BundleMember->NextInBundle = nullptr;
7774     if (BundleMember->unscheduledDepsInBundle() == 0) {
7775       ReadyInsts.insert(BundleMember);
7776     }
7777     BundleMember = Next;
7778   }
7779 }
7780 
7781 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7782   // Allocate a new ScheduleData for the instruction.
7783   if (ChunkPos >= ChunkSize) {
7784     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7785     ChunkPos = 0;
7786   }
7787   return &(ScheduleDataChunks.back()[ChunkPos++]);
7788 }
7789 
7790 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7791                                                       const InstructionsState &S) {
7792   if (getScheduleData(V, isOneOf(S, V)))
7793     return true;
7794   Instruction *I = dyn_cast<Instruction>(V);
7795   assert(I && "bundle member must be an instruction");
7796   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7797          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7798          "be scheduled");
7799   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7800     ScheduleData *ISD = getScheduleData(I);
7801     if (!ISD)
7802       return false;
7803     assert(isInSchedulingRegion(ISD) &&
7804            "ScheduleData not in scheduling region");
7805     ScheduleData *SD = allocateScheduleDataChunks();
7806     SD->Inst = I;
7807     SD->init(SchedulingRegionID, S.OpValue);
7808     ExtraScheduleDataMap[I][S.OpValue] = SD;
7809     return true;
7810   };
7811   if (CheckScheduleForI(I))
7812     return true;
7813   if (!ScheduleStart) {
7814     // It's the first instruction in the new region.
7815     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7816     ScheduleStart = I;
7817     ScheduleEnd = I->getNextNode();
7818     if (isOneOf(S, I) != I)
7819       CheckScheduleForI(I);
7820     assert(ScheduleEnd && "tried to vectorize a terminator?");
7821     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7822     return true;
7823   }
7824   // Search up and down at the same time, because we don't know if the new
7825   // instruction is above or below the existing scheduling region.
7826   BasicBlock::reverse_iterator UpIter =
7827       ++ScheduleStart->getIterator().getReverse();
7828   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7829   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7830   BasicBlock::iterator LowerEnd = BB->end();
7831   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7832          &*DownIter != I) {
7833     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7834       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7835       return false;
7836     }
7837 
7838     ++UpIter;
7839     ++DownIter;
7840   }
7841   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7842     assert(I->getParent() == ScheduleStart->getParent() &&
7843            "Instruction is in wrong basic block.");
7844     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7845     ScheduleStart = I;
7846     if (isOneOf(S, I) != I)
7847       CheckScheduleForI(I);
7848     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7849                       << "\n");
7850     return true;
7851   }
7852   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7853          "Expected to reach top of the basic block or instruction down the "
7854          "lower end.");
7855   assert(I->getParent() == ScheduleEnd->getParent() &&
7856          "Instruction is in wrong basic block.");
7857   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7858                    nullptr);
7859   ScheduleEnd = I->getNextNode();
7860   if (isOneOf(S, I) != I)
7861     CheckScheduleForI(I);
7862   assert(ScheduleEnd && "tried to vectorize a terminator?");
7863   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7864   return true;
7865 }
7866 
7867 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7868                                                 Instruction *ToI,
7869                                                 ScheduleData *PrevLoadStore,
7870                                                 ScheduleData *NextLoadStore) {
7871   ScheduleData *CurrentLoadStore = PrevLoadStore;
7872   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7873     ScheduleData *SD = ScheduleDataMap[I];
7874     if (!SD) {
7875       SD = allocateScheduleDataChunks();
7876       ScheduleDataMap[I] = SD;
7877       SD->Inst = I;
7878     }
7879     assert(!isInSchedulingRegion(SD) &&
7880            "new ScheduleData already in scheduling region");
7881     SD->init(SchedulingRegionID, I);
7882 
7883     if (I->mayReadOrWriteMemory() &&
7884         (!isa<IntrinsicInst>(I) ||
7885          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7886           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7887               Intrinsic::pseudoprobe))) {
7888       // Update the linked list of memory accessing instructions.
7889       if (CurrentLoadStore) {
7890         CurrentLoadStore->NextLoadStore = SD;
7891       } else {
7892         FirstLoadStoreInRegion = SD;
7893       }
7894       CurrentLoadStore = SD;
7895     }
7896   }
7897   if (NextLoadStore) {
7898     if (CurrentLoadStore)
7899       CurrentLoadStore->NextLoadStore = NextLoadStore;
7900   } else {
7901     LastLoadStoreInRegion = CurrentLoadStore;
7902   }
7903 }
7904 
7905 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7906                                                      bool InsertInReadyList,
7907                                                      BoUpSLP *SLP) {
7908   assert(SD->isSchedulingEntity());
7909 
7910   SmallVector<ScheduleData *, 10> WorkList;
7911   WorkList.push_back(SD);
7912 
7913   while (!WorkList.empty()) {
7914     ScheduleData *SD = WorkList.pop_back_val();
7915     for (ScheduleData *BundleMember = SD; BundleMember;
7916          BundleMember = BundleMember->NextInBundle) {
7917       assert(isInSchedulingRegion(BundleMember));
7918       if (BundleMember->hasValidDependencies())
7919         continue;
7920 
7921       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7922                  << "\n");
7923       BundleMember->Dependencies = 0;
7924       BundleMember->resetUnscheduledDeps();
7925 
7926       // Handle def-use chain dependencies.
7927       if (BundleMember->OpValue != BundleMember->Inst) {
7928         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
7929           BundleMember->Dependencies++;
7930           ScheduleData *DestBundle = UseSD->FirstInBundle;
7931           if (!DestBundle->IsScheduled)
7932             BundleMember->incrementUnscheduledDeps(1);
7933           if (!DestBundle->hasValidDependencies())
7934             WorkList.push_back(DestBundle);
7935         }
7936       } else {
7937         for (User *U : BundleMember->Inst->users()) {
7938           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
7939             BundleMember->Dependencies++;
7940             ScheduleData *DestBundle = UseSD->FirstInBundle;
7941             if (!DestBundle->IsScheduled)
7942               BundleMember->incrementUnscheduledDeps(1);
7943             if (!DestBundle->hasValidDependencies())
7944               WorkList.push_back(DestBundle);
7945           }
7946         }
7947       }
7948 
7949       // Handle the memory dependencies (if any).
7950       ScheduleData *DepDest = BundleMember->NextLoadStore;
7951       if (!DepDest)
7952         continue;
7953       Instruction *SrcInst = BundleMember->Inst;
7954       assert(SrcInst->mayReadOrWriteMemory() &&
7955              "NextLoadStore list for non memory effecting bundle?");
7956       MemoryLocation SrcLoc = getLocation(SrcInst);
7957       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7958       unsigned numAliased = 0;
7959       unsigned DistToSrc = 1;
7960 
7961       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7962         assert(isInSchedulingRegion(DepDest));
7963 
7964         // We have two limits to reduce the complexity:
7965         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7966         //    SLP->isAliased (which is the expensive part in this loop).
7967         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7968         //    the whole loop (even if the loop is fast, it's quadratic).
7969         //    It's important for the loop break condition (see below) to
7970         //    check this limit even between two read-only instructions.
7971         if (DistToSrc >= MaxMemDepDistance ||
7972             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7973              (numAliased >= AliasedCheckLimit ||
7974               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7975 
7976           // We increment the counter only if the locations are aliased
7977           // (instead of counting all alias checks). This gives a better
7978           // balance between reduced runtime and accurate dependencies.
7979           numAliased++;
7980 
7981           DepDest->MemoryDependencies.push_back(BundleMember);
7982           BundleMember->Dependencies++;
7983           ScheduleData *DestBundle = DepDest->FirstInBundle;
7984           if (!DestBundle->IsScheduled) {
7985             BundleMember->incrementUnscheduledDeps(1);
7986           }
7987           if (!DestBundle->hasValidDependencies()) {
7988             WorkList.push_back(DestBundle);
7989           }
7990         }
7991 
7992         // Example, explaining the loop break condition: Let's assume our
7993         // starting instruction is i0 and MaxMemDepDistance = 3.
7994         //
7995         //                      +--------v--v--v
7996         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7997         //             +--------^--^--^
7998         //
7999         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8000         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8001         // Previously we already added dependencies from i3 to i6,i7,i8
8002         // (because of MaxMemDepDistance). As we added a dependency from
8003         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8004         // and we can abort this loop at i6.
8005         if (DistToSrc >= 2 * MaxMemDepDistance)
8006           break;
8007         DistToSrc++;
8008       }
8009     }
8010     if (InsertInReadyList && SD->isReady()) {
8011       ReadyInsts.insert(SD);
8012       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8013                         << "\n");
8014     }
8015   }
8016 }
8017 
8018 void BoUpSLP::BlockScheduling::resetSchedule() {
8019   assert(ScheduleStart &&
8020          "tried to reset schedule on block which has not been scheduled");
8021   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8022     doForAllOpcodes(I, [&](ScheduleData *SD) {
8023       assert(isInSchedulingRegion(SD) &&
8024              "ScheduleData not in scheduling region");
8025       SD->IsScheduled = false;
8026       SD->resetUnscheduledDeps();
8027     });
8028   }
8029   ReadyInsts.clear();
8030 }
8031 
8032 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8033   if (!BS->ScheduleStart)
8034     return;
8035 
8036   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8037 
8038   BS->resetSchedule();
8039 
8040   // For the real scheduling we use a more sophisticated ready-list: it is
8041   // sorted by the original instruction location. This lets the final schedule
8042   // be as  close as possible to the original instruction order.
8043   struct ScheduleDataCompare {
8044     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8045       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8046     }
8047   };
8048   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8049 
8050   // Ensure that all dependency data is updated and fill the ready-list with
8051   // initial instructions.
8052   int Idx = 0;
8053   int NumToSchedule = 0;
8054   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8055        I = I->getNextNode()) {
8056     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
8057       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8058               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
8059              "scheduler and vectorizer bundle mismatch");
8060       SD->FirstInBundle->SchedulingPriority = Idx++;
8061       if (SD->isSchedulingEntity()) {
8062         BS->calculateDependencies(SD, false, this);
8063         NumToSchedule++;
8064       }
8065     });
8066   }
8067   BS->initialFillReadyList(ReadyInsts);
8068 
8069   Instruction *LastScheduledInst = BS->ScheduleEnd;
8070   MemoryAccess *MemInsertPt = nullptr;
8071   if (MSSA) {
8072     for (auto I = LastScheduledInst->getIterator(); I != BS->BB->end(); I++) {
8073       if (auto *Access = MSSA->getMemoryAccess(&*I)) {
8074         MemInsertPt = Access;
8075         break;
8076       }
8077     }
8078   }
8079 
8080   // Do the "real" scheduling.
8081   while (!ReadyInsts.empty()) {
8082     ScheduleData *picked = *ReadyInsts.begin();
8083     ReadyInsts.erase(ReadyInsts.begin());
8084 
8085     // Move the scheduled instruction(s) to their dedicated places, if not
8086     // there yet.
8087     for (ScheduleData *BundleMember = picked; BundleMember;
8088          BundleMember = BundleMember->NextInBundle) {
8089       Instruction *pickedInst = BundleMember->Inst;
8090       if (pickedInst->getNextNode() != LastScheduledInst) {
8091         pickedInst->moveBefore(LastScheduledInst);
8092         if (MSSA) {
8093           MemorySSAUpdater MSSAU(MSSA);
8094           if (auto *Access = MSSA->getMemoryAccess(pickedInst)) {
8095             if (MemInsertPt)
8096               MSSAU.moveBefore(Access, cast<MemoryUseOrDef>(MemInsertPt));
8097             else
8098               MSSAU.moveToPlace(Access, BS->BB,
8099                                 MemorySSA::InsertionPlace::End);
8100           }
8101         }
8102       }
8103 
8104       LastScheduledInst = pickedInst;
8105       if (MSSA)
8106         if (auto *Access = MSSA->getMemoryAccess(LastScheduledInst))
8107           MemInsertPt = Access;
8108     }
8109 
8110     BS->schedule(picked, ReadyInsts);
8111     NumToSchedule--;
8112   }
8113   assert(NumToSchedule == 0 && "could not schedule all instructions");
8114 
8115   // Check that we didn't break any of our invariants.
8116 #ifdef EXPENSIVE_CHECKS
8117   BS->verify();
8118 #endif
8119 
8120 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8121   // Check that all schedulable entities got scheduled
8122   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8123     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8124       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8125         assert(SD->IsScheduled && "must be scheduled at this point");
8126       }
8127     });
8128   }
8129 #endif
8130 
8131   // Avoid duplicate scheduling of the block.
8132   BS->ScheduleStart = nullptr;
8133 }
8134 
8135 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8136   // If V is a store, just return the width of the stored value (or value
8137   // truncated just before storing) without traversing the expression tree.
8138   // This is the common case.
8139   if (auto *Store = dyn_cast<StoreInst>(V)) {
8140     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8141       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8142     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8143   }
8144 
8145   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8146     return getVectorElementSize(IEI->getOperand(1));
8147 
8148   auto E = InstrElementSize.find(V);
8149   if (E != InstrElementSize.end())
8150     return E->second;
8151 
8152   // If V is not a store, we can traverse the expression tree to find loads
8153   // that feed it. The type of the loaded value may indicate a more suitable
8154   // width than V's type. We want to base the vector element size on the width
8155   // of memory operations where possible.
8156   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8157   SmallPtrSet<Instruction *, 16> Visited;
8158   if (auto *I = dyn_cast<Instruction>(V)) {
8159     Worklist.emplace_back(I, I->getParent());
8160     Visited.insert(I);
8161   }
8162 
8163   // Traverse the expression tree in bottom-up order looking for loads. If we
8164   // encounter an instruction we don't yet handle, we give up.
8165   auto Width = 0u;
8166   while (!Worklist.empty()) {
8167     Instruction *I;
8168     BasicBlock *Parent;
8169     std::tie(I, Parent) = Worklist.pop_back_val();
8170 
8171     // We should only be looking at scalar instructions here. If the current
8172     // instruction has a vector type, skip.
8173     auto *Ty = I->getType();
8174     if (isa<VectorType>(Ty))
8175       continue;
8176 
8177     // If the current instruction is a load, update MaxWidth to reflect the
8178     // width of the loaded value.
8179     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8180         isa<ExtractValueInst>(I))
8181       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8182 
8183     // Otherwise, we need to visit the operands of the instruction. We only
8184     // handle the interesting cases from buildTree here. If an operand is an
8185     // instruction we haven't yet visited and from the same basic block as the
8186     // user or the use is a PHI node, we add it to the worklist.
8187     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8188              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8189              isa<UnaryOperator>(I)) {
8190       for (Use &U : I->operands())
8191         if (auto *J = dyn_cast<Instruction>(U.get()))
8192           if (Visited.insert(J).second &&
8193               (isa<PHINode>(I) || J->getParent() == Parent))
8194             Worklist.emplace_back(J, J->getParent());
8195     } else {
8196       break;
8197     }
8198   }
8199 
8200   // If we didn't encounter a memory access in the expression tree, or if we
8201   // gave up for some reason, just return the width of V. Otherwise, return the
8202   // maximum width we found.
8203   if (!Width) {
8204     if (auto *CI = dyn_cast<CmpInst>(V))
8205       V = CI->getOperand(0);
8206     Width = DL->getTypeSizeInBits(V->getType());
8207   }
8208 
8209   for (Instruction *I : Visited)
8210     InstrElementSize[I] = Width;
8211 
8212   return Width;
8213 }
8214 
8215 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8216 // smaller type with a truncation. We collect the values that will be demoted
8217 // in ToDemote and additional roots that require investigating in Roots.
8218 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8219                                   SmallVectorImpl<Value *> &ToDemote,
8220                                   SmallVectorImpl<Value *> &Roots) {
8221   // We can always demote constants.
8222   if (isa<Constant>(V)) {
8223     ToDemote.push_back(V);
8224     return true;
8225   }
8226 
8227   // If the value is not an instruction in the expression with only one use, it
8228   // cannot be demoted.
8229   auto *I = dyn_cast<Instruction>(V);
8230   if (!I || !I->hasOneUse() || !Expr.count(I))
8231     return false;
8232 
8233   switch (I->getOpcode()) {
8234 
8235   // We can always demote truncations and extensions. Since truncations can
8236   // seed additional demotion, we save the truncated value.
8237   case Instruction::Trunc:
8238     Roots.push_back(I->getOperand(0));
8239     break;
8240   case Instruction::ZExt:
8241   case Instruction::SExt:
8242     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8243         isa<InsertElementInst>(I->getOperand(0)))
8244       return false;
8245     break;
8246 
8247   // We can demote certain binary operations if we can demote both of their
8248   // operands.
8249   case Instruction::Add:
8250   case Instruction::Sub:
8251   case Instruction::Mul:
8252   case Instruction::And:
8253   case Instruction::Or:
8254   case Instruction::Xor:
8255     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8256         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8257       return false;
8258     break;
8259 
8260   // We can demote selects if we can demote their true and false values.
8261   case Instruction::Select: {
8262     SelectInst *SI = cast<SelectInst>(I);
8263     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8264         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8265       return false;
8266     break;
8267   }
8268 
8269   // We can demote phis if we can demote all their incoming operands. Note that
8270   // we don't need to worry about cycles since we ensure single use above.
8271   case Instruction::PHI: {
8272     PHINode *PN = cast<PHINode>(I);
8273     for (Value *IncValue : PN->incoming_values())
8274       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8275         return false;
8276     break;
8277   }
8278 
8279   // Otherwise, conservatively give up.
8280   default:
8281     return false;
8282   }
8283 
8284   // Record the value that we can demote.
8285   ToDemote.push_back(V);
8286   return true;
8287 }
8288 
8289 void BoUpSLP::computeMinimumValueSizes() {
8290   // If there are no external uses, the expression tree must be rooted by a
8291   // store. We can't demote in-memory values, so there is nothing to do here.
8292   if (ExternalUses.empty())
8293     return;
8294 
8295   // We only attempt to truncate integer expressions.
8296   auto &TreeRoot = VectorizableTree[0]->Scalars;
8297   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8298   if (!TreeRootIT)
8299     return;
8300 
8301   // If the expression is not rooted by a store, these roots should have
8302   // external uses. We will rely on InstCombine to rewrite the expression in
8303   // the narrower type. However, InstCombine only rewrites single-use values.
8304   // This means that if a tree entry other than a root is used externally, it
8305   // must have multiple uses and InstCombine will not rewrite it. The code
8306   // below ensures that only the roots are used externally.
8307   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8308   for (auto &EU : ExternalUses)
8309     if (!Expr.erase(EU.Scalar))
8310       return;
8311   if (!Expr.empty())
8312     return;
8313 
8314   // Collect the scalar values of the vectorizable expression. We will use this
8315   // context to determine which values can be demoted. If we see a truncation,
8316   // we mark it as seeding another demotion.
8317   for (auto &EntryPtr : VectorizableTree)
8318     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8319 
8320   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8321   // have a single external user that is not in the vectorizable tree.
8322   for (auto *Root : TreeRoot)
8323     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8324       return;
8325 
8326   // Conservatively determine if we can actually truncate the roots of the
8327   // expression. Collect the values that can be demoted in ToDemote and
8328   // additional roots that require investigating in Roots.
8329   SmallVector<Value *, 32> ToDemote;
8330   SmallVector<Value *, 4> Roots;
8331   for (auto *Root : TreeRoot)
8332     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8333       return;
8334 
8335   // The maximum bit width required to represent all the values that can be
8336   // demoted without loss of precision. It would be safe to truncate the roots
8337   // of the expression to this width.
8338   auto MaxBitWidth = 8u;
8339 
8340   // We first check if all the bits of the roots are demanded. If they're not,
8341   // we can truncate the roots to this narrower type.
8342   for (auto *Root : TreeRoot) {
8343     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8344     MaxBitWidth = std::max<unsigned>(
8345         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8346   }
8347 
8348   // True if the roots can be zero-extended back to their original type, rather
8349   // than sign-extended. We know that if the leading bits are not demanded, we
8350   // can safely zero-extend. So we initialize IsKnownPositive to True.
8351   bool IsKnownPositive = true;
8352 
8353   // If all the bits of the roots are demanded, we can try a little harder to
8354   // compute a narrower type. This can happen, for example, if the roots are
8355   // getelementptr indices. InstCombine promotes these indices to the pointer
8356   // width. Thus, all their bits are technically demanded even though the
8357   // address computation might be vectorized in a smaller type.
8358   //
8359   // We start by looking at each entry that can be demoted. We compute the
8360   // maximum bit width required to store the scalar by using ValueTracking to
8361   // compute the number of high-order bits we can truncate.
8362   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8363       llvm::all_of(TreeRoot, [](Value *R) {
8364         assert(R->hasOneUse() && "Root should have only one use!");
8365         return isa<GetElementPtrInst>(R->user_back());
8366       })) {
8367     MaxBitWidth = 8u;
8368 
8369     // Determine if the sign bit of all the roots is known to be zero. If not,
8370     // IsKnownPositive is set to False.
8371     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8372       KnownBits Known = computeKnownBits(R, *DL);
8373       return Known.isNonNegative();
8374     });
8375 
8376     // Determine the maximum number of bits required to store the scalar
8377     // values.
8378     for (auto *Scalar : ToDemote) {
8379       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8380       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8381       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8382     }
8383 
8384     // If we can't prove that the sign bit is zero, we must add one to the
8385     // maximum bit width to account for the unknown sign bit. This preserves
8386     // the existing sign bit so we can safely sign-extend the root back to the
8387     // original type. Otherwise, if we know the sign bit is zero, we will
8388     // zero-extend the root instead.
8389     //
8390     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8391     //        one to the maximum bit width will yield a larger-than-necessary
8392     //        type. In general, we need to add an extra bit only if we can't
8393     //        prove that the upper bit of the original type is equal to the
8394     //        upper bit of the proposed smaller type. If these two bits are the
8395     //        same (either zero or one) we know that sign-extending from the
8396     //        smaller type will result in the same value. Here, since we can't
8397     //        yet prove this, we are just making the proposed smaller type
8398     //        larger to ensure correctness.
8399     if (!IsKnownPositive)
8400       ++MaxBitWidth;
8401   }
8402 
8403   // Round MaxBitWidth up to the next power-of-two.
8404   if (!isPowerOf2_64(MaxBitWidth))
8405     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8406 
8407   // If the maximum bit width we compute is less than the with of the roots'
8408   // type, we can proceed with the narrowing. Otherwise, do nothing.
8409   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8410     return;
8411 
8412   // If we can truncate the root, we must collect additional values that might
8413   // be demoted as a result. That is, those seeded by truncations we will
8414   // modify.
8415   while (!Roots.empty())
8416     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8417 
8418   // Finally, map the values we can demote to the maximum bit with we computed.
8419   for (auto *Scalar : ToDemote)
8420     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8421 }
8422 
8423 namespace {
8424 
8425 /// The SLPVectorizer Pass.
8426 struct SLPVectorizer : public FunctionPass {
8427   SLPVectorizerPass Impl;
8428 
8429   /// Pass identification, replacement for typeid
8430   static char ID;
8431 
8432   explicit SLPVectorizer() : FunctionPass(ID) {
8433     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8434   }
8435 
8436   bool doInitialization(Module &M) override { return false; }
8437 
8438   bool runOnFunction(Function &F) override {
8439     if (skipFunction(F))
8440       return false;
8441 
8442     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8443     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8444     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8445     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8446     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8447     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8448     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8449     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8450     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8451     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8452 
8453     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, /*MSSA*/nullptr, ORE);
8454   }
8455 
8456   void getAnalysisUsage(AnalysisUsage &AU) const override {
8457     FunctionPass::getAnalysisUsage(AU);
8458     AU.addRequired<AssumptionCacheTracker>();
8459     AU.addRequired<ScalarEvolutionWrapperPass>();
8460     AU.addRequired<AAResultsWrapperPass>();
8461     AU.addRequired<TargetTransformInfoWrapperPass>();
8462     AU.addRequired<LoopInfoWrapperPass>();
8463     AU.addRequired<DominatorTreeWrapperPass>();
8464     AU.addRequired<DemandedBitsWrapperPass>();
8465     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8466     AU.addRequired<InjectTLIMappingsLegacy>();
8467     AU.addPreserved<LoopInfoWrapperPass>();
8468     AU.addPreserved<DominatorTreeWrapperPass>();
8469     AU.addPreserved<AAResultsWrapperPass>();
8470     AU.addPreserved<GlobalsAAWrapperPass>();
8471     AU.setPreservesCFG();
8472   }
8473 };
8474 
8475 } // end anonymous namespace
8476 
8477 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8478   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8479   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8480   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8481   auto *AA = &AM.getResult<AAManager>(F);
8482   auto *LI = &AM.getResult<LoopAnalysis>(F);
8483   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8484   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8485   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8486   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8487   auto *MSSA = EnableMSSAInSLPVectorizer ?
8488     &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : (MemorySSA*)nullptr;
8489 
8490   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, MSSA, ORE);
8491   if (!Changed)
8492     return PreservedAnalyses::all();
8493 
8494   PreservedAnalyses PA;
8495   PA.preserveSet<CFGAnalyses>();
8496   if (MSSA) {
8497 #ifdef EXPENSIVE_CHECKS
8498     MSSA->verifyMemorySSA();
8499 #endif
8500     PA.preserve<MemorySSAAnalysis>();
8501   }
8502   return PA;
8503 }
8504 
8505 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8506                                 TargetTransformInfo *TTI_,
8507                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8508                                 LoopInfo *LI_, DominatorTree *DT_,
8509                                 AssumptionCache *AC_, DemandedBits *DB_,
8510                                 MemorySSA *MSSA,
8511                                 OptimizationRemarkEmitter *ORE_) {
8512   if (!RunSLPVectorization)
8513     return false;
8514   SE = SE_;
8515   TTI = TTI_;
8516   TLI = TLI_;
8517   AA = AA_;
8518   LI = LI_;
8519   DT = DT_;
8520   AC = AC_;
8521   DB = DB_;
8522   DL = &F.getParent()->getDataLayout();
8523 
8524   Stores.clear();
8525   GEPs.clear();
8526   bool Changed = false;
8527 
8528   // If the target claims to have no vector registers don't attempt
8529   // vectorization.
8530   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8531     LLVM_DEBUG(
8532         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8533     return false;
8534   }
8535 
8536   // Don't vectorize when the attribute NoImplicitFloat is used.
8537   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8538     return false;
8539 
8540   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8541 
8542   // Use the bottom up slp vectorizer to construct chains that start with
8543   // store instructions.
8544   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, MSSA, DL, ORE_);
8545 
8546   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8547   // delete instructions.
8548 
8549   // Update DFS numbers now so that we can use them for ordering.
8550   DT->updateDFSNumbers();
8551 
8552   // Scan the blocks in the function in post order.
8553   for (auto BB : post_order(&F.getEntryBlock())) {
8554     collectSeedInstructions(BB);
8555 
8556     // Vectorize trees that end at stores.
8557     if (!Stores.empty()) {
8558       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8559                         << " underlying objects.\n");
8560       Changed |= vectorizeStoreChains(R);
8561     }
8562 
8563     // Vectorize trees that end at reductions.
8564     Changed |= vectorizeChainsInBlock(BB, R);
8565 
8566     // Vectorize the index computations of getelementptr instructions. This
8567     // is primarily intended to catch gather-like idioms ending at
8568     // non-consecutive loads.
8569     if (!GEPs.empty()) {
8570       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8571                         << " underlying objects.\n");
8572       Changed |= vectorizeGEPIndices(BB, R);
8573     }
8574   }
8575 
8576   if (Changed) {
8577     R.optimizeGatherSequence();
8578     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8579   }
8580   return Changed;
8581 }
8582 
8583 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8584                                             unsigned Idx) {
8585   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8586                     << "\n");
8587   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8588   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8589   unsigned VF = Chain.size();
8590 
8591   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8592     return false;
8593 
8594   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8595                     << "\n");
8596 
8597   R.buildTree(Chain);
8598   if (R.isTreeTinyAndNotFullyVectorizable())
8599     return false;
8600   if (R.isLoadCombineCandidate())
8601     return false;
8602   R.reorderTopToBottom();
8603   R.reorderBottomToTop();
8604   R.buildExternalUses();
8605 
8606   R.computeMinimumValueSizes();
8607 
8608   InstructionCost Cost = R.getTreeCost();
8609 
8610   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8611   if (Cost < -SLPCostThreshold) {
8612     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8613 
8614     using namespace ore;
8615 
8616     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8617                                         cast<StoreInst>(Chain[0]))
8618                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8619                      << " and with tree size "
8620                      << NV("TreeSize", R.getTreeSize()));
8621 
8622     R.vectorizeTree();
8623     return true;
8624   }
8625 
8626   return false;
8627 }
8628 
8629 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8630                                         BoUpSLP &R) {
8631   // We may run into multiple chains that merge into a single chain. We mark the
8632   // stores that we vectorized so that we don't visit the same store twice.
8633   BoUpSLP::ValueSet VectorizedStores;
8634   bool Changed = false;
8635 
8636   int E = Stores.size();
8637   SmallBitVector Tails(E, false);
8638   int MaxIter = MaxStoreLookup.getValue();
8639   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8640       E, std::make_pair(E, INT_MAX));
8641   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8642   int IterCnt;
8643   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8644                                   &CheckedPairs,
8645                                   &ConsecutiveChain](int K, int Idx) {
8646     if (IterCnt >= MaxIter)
8647       return true;
8648     if (CheckedPairs[Idx].test(K))
8649       return ConsecutiveChain[K].second == 1 &&
8650              ConsecutiveChain[K].first == Idx;
8651     ++IterCnt;
8652     CheckedPairs[Idx].set(K);
8653     CheckedPairs[K].set(Idx);
8654     Optional<int> Diff = getPointersDiff(
8655         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8656         Stores[Idx]->getValueOperand()->getType(),
8657         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8658     if (!Diff || *Diff == 0)
8659       return false;
8660     int Val = *Diff;
8661     if (Val < 0) {
8662       if (ConsecutiveChain[Idx].second > -Val) {
8663         Tails.set(K);
8664         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8665       }
8666       return false;
8667     }
8668     if (ConsecutiveChain[K].second <= Val)
8669       return false;
8670 
8671     Tails.set(Idx);
8672     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8673     return Val == 1;
8674   };
8675   // Do a quadratic search on all of the given stores in reverse order and find
8676   // all of the pairs of stores that follow each other.
8677   for (int Idx = E - 1; Idx >= 0; --Idx) {
8678     // If a store has multiple consecutive store candidates, search according
8679     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8680     // This is because usually pairing with immediate succeeding or preceding
8681     // candidate create the best chance to find slp vectorization opportunity.
8682     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8683     IterCnt = 0;
8684     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8685       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8686           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8687         break;
8688   }
8689 
8690   // Tracks if we tried to vectorize stores starting from the given tail
8691   // already.
8692   SmallBitVector TriedTails(E, false);
8693   // For stores that start but don't end a link in the chain:
8694   for (int Cnt = E; Cnt > 0; --Cnt) {
8695     int I = Cnt - 1;
8696     if (ConsecutiveChain[I].first == E || Tails.test(I))
8697       continue;
8698     // We found a store instr that starts a chain. Now follow the chain and try
8699     // to vectorize it.
8700     BoUpSLP::ValueList Operands;
8701     // Collect the chain into a list.
8702     while (I != E && !VectorizedStores.count(Stores[I])) {
8703       Operands.push_back(Stores[I]);
8704       Tails.set(I);
8705       if (ConsecutiveChain[I].second != 1) {
8706         // Mark the new end in the chain and go back, if required. It might be
8707         // required if the original stores come in reversed order, for example.
8708         if (ConsecutiveChain[I].first != E &&
8709             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8710             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8711           TriedTails.set(I);
8712           Tails.reset(ConsecutiveChain[I].first);
8713           if (Cnt < ConsecutiveChain[I].first + 2)
8714             Cnt = ConsecutiveChain[I].first + 2;
8715         }
8716         break;
8717       }
8718       // Move to the next value in the chain.
8719       I = ConsecutiveChain[I].first;
8720     }
8721     assert(!Operands.empty() && "Expected non-empty list of stores.");
8722 
8723     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8724     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8725     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8726 
8727     unsigned MinVF = R.getMinVF(EltSize);
8728     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8729                               MaxElts);
8730 
8731     // FIXME: Is division-by-2 the correct step? Should we assert that the
8732     // register size is a power-of-2?
8733     unsigned StartIdx = 0;
8734     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8735       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8736         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8737         if (!VectorizedStores.count(Slice.front()) &&
8738             !VectorizedStores.count(Slice.back()) &&
8739             vectorizeStoreChain(Slice, R, Cnt)) {
8740           // Mark the vectorized stores so that we don't vectorize them again.
8741           VectorizedStores.insert(Slice.begin(), Slice.end());
8742           Changed = true;
8743           // If we vectorized initial block, no need to try to vectorize it
8744           // again.
8745           if (Cnt == StartIdx)
8746             StartIdx += Size;
8747           Cnt += Size;
8748           continue;
8749         }
8750         ++Cnt;
8751       }
8752       // Check if the whole array was vectorized already - exit.
8753       if (StartIdx >= Operands.size())
8754         break;
8755     }
8756   }
8757 
8758   return Changed;
8759 }
8760 
8761 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8762   // Initialize the collections. We will make a single pass over the block.
8763   Stores.clear();
8764   GEPs.clear();
8765 
8766   // Visit the store and getelementptr instructions in BB and organize them in
8767   // Stores and GEPs according to the underlying objects of their pointer
8768   // operands.
8769   for (Instruction &I : *BB) {
8770     // Ignore store instructions that are volatile or have a pointer operand
8771     // that doesn't point to a scalar type.
8772     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8773       if (!SI->isSimple())
8774         continue;
8775       if (!isValidElementType(SI->getValueOperand()->getType()))
8776         continue;
8777       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8778     }
8779 
8780     // Ignore getelementptr instructions that have more than one index, a
8781     // constant index, or a pointer operand that doesn't point to a scalar
8782     // type.
8783     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8784       auto Idx = GEP->idx_begin()->get();
8785       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8786         continue;
8787       if (!isValidElementType(Idx->getType()))
8788         continue;
8789       if (GEP->getType()->isVectorTy())
8790         continue;
8791       GEPs[GEP->getPointerOperand()].push_back(GEP);
8792     }
8793   }
8794 }
8795 
8796 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8797   if (!A || !B)
8798     return false;
8799   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8800     return false;
8801   Value *VL[] = {A, B};
8802   return tryToVectorizeList(VL, R);
8803 }
8804 
8805 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8806                                            bool LimitForRegisterSize) {
8807   if (VL.size() < 2)
8808     return false;
8809 
8810   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8811                     << VL.size() << ".\n");
8812 
8813   // Check that all of the parts are instructions of the same type,
8814   // we permit an alternate opcode via InstructionsState.
8815   InstructionsState S = getSameOpcode(VL);
8816   if (!S.getOpcode())
8817     return false;
8818 
8819   Instruction *I0 = cast<Instruction>(S.OpValue);
8820   // Make sure invalid types (including vector type) are rejected before
8821   // determining vectorization factor for scalar instructions.
8822   for (Value *V : VL) {
8823     Type *Ty = V->getType();
8824     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8825       // NOTE: the following will give user internal llvm type name, which may
8826       // not be useful.
8827       R.getORE()->emit([&]() {
8828         std::string type_str;
8829         llvm::raw_string_ostream rso(type_str);
8830         Ty->print(rso);
8831         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8832                << "Cannot SLP vectorize list: type "
8833                << rso.str() + " is unsupported by vectorizer";
8834       });
8835       return false;
8836     }
8837   }
8838 
8839   unsigned Sz = R.getVectorElementSize(I0);
8840   unsigned MinVF = R.getMinVF(Sz);
8841   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8842   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8843   if (MaxVF < 2) {
8844     R.getORE()->emit([&]() {
8845       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8846              << "Cannot SLP vectorize list: vectorization factor "
8847              << "less than 2 is not supported";
8848     });
8849     return false;
8850   }
8851 
8852   bool Changed = false;
8853   bool CandidateFound = false;
8854   InstructionCost MinCost = SLPCostThreshold.getValue();
8855   Type *ScalarTy = VL[0]->getType();
8856   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8857     ScalarTy = IE->getOperand(1)->getType();
8858 
8859   unsigned NextInst = 0, MaxInst = VL.size();
8860   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8861     // No actual vectorization should happen, if number of parts is the same as
8862     // provided vectorization factor (i.e. the scalar type is used for vector
8863     // code during codegen).
8864     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8865     if (TTI->getNumberOfParts(VecTy) == VF)
8866       continue;
8867     for (unsigned I = NextInst; I < MaxInst; ++I) {
8868       unsigned OpsWidth = 0;
8869 
8870       if (I + VF > MaxInst)
8871         OpsWidth = MaxInst - I;
8872       else
8873         OpsWidth = VF;
8874 
8875       if (!isPowerOf2_32(OpsWidth))
8876         continue;
8877 
8878       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8879           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8880         break;
8881 
8882       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8883       // Check that a previous iteration of this loop did not delete the Value.
8884       if (llvm::any_of(Ops, [&R](Value *V) {
8885             auto *I = dyn_cast<Instruction>(V);
8886             return I && R.isDeleted(I);
8887           }))
8888         continue;
8889 
8890       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8891                         << "\n");
8892 
8893       R.buildTree(Ops);
8894       if (R.isTreeTinyAndNotFullyVectorizable())
8895         continue;
8896       R.reorderTopToBottom();
8897       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
8898       R.buildExternalUses();
8899 
8900       R.computeMinimumValueSizes();
8901       InstructionCost Cost = R.getTreeCost();
8902       CandidateFound = true;
8903       MinCost = std::min(MinCost, Cost);
8904 
8905       if (Cost < -SLPCostThreshold) {
8906         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8907         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8908                                                     cast<Instruction>(Ops[0]))
8909                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8910                                  << " and with tree size "
8911                                  << ore::NV("TreeSize", R.getTreeSize()));
8912 
8913         R.vectorizeTree();
8914         // Move to the next bundle.
8915         I += VF - 1;
8916         NextInst = I + 1;
8917         Changed = true;
8918       }
8919     }
8920   }
8921 
8922   if (!Changed && CandidateFound) {
8923     R.getORE()->emit([&]() {
8924       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8925              << "List vectorization was possible but not beneficial with cost "
8926              << ore::NV("Cost", MinCost) << " >= "
8927              << ore::NV("Treshold", -SLPCostThreshold);
8928     });
8929   } else if (!Changed) {
8930     R.getORE()->emit([&]() {
8931       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8932              << "Cannot SLP vectorize list: vectorization was impossible"
8933              << " with available vectorization factors";
8934     });
8935   }
8936   return Changed;
8937 }
8938 
8939 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8940   if (!I)
8941     return false;
8942 
8943   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8944     return false;
8945 
8946   Value *P = I->getParent();
8947 
8948   // Vectorize in current basic block only.
8949   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8950   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8951   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8952     return false;
8953 
8954   // Try to vectorize V.
8955   if (tryToVectorizePair(Op0, Op1, R))
8956     return true;
8957 
8958   auto *A = dyn_cast<BinaryOperator>(Op0);
8959   auto *B = dyn_cast<BinaryOperator>(Op1);
8960   // Try to skip B.
8961   if (B && B->hasOneUse()) {
8962     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8963     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8964     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8965       return true;
8966     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8967       return true;
8968   }
8969 
8970   // Try to skip A.
8971   if (A && A->hasOneUse()) {
8972     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8973     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8974     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8975       return true;
8976     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8977       return true;
8978   }
8979   return false;
8980 }
8981 
8982 namespace {
8983 
8984 /// Model horizontal reductions.
8985 ///
8986 /// A horizontal reduction is a tree of reduction instructions that has values
8987 /// that can be put into a vector as its leaves. For example:
8988 ///
8989 /// mul mul mul mul
8990 ///  \  /    \  /
8991 ///   +       +
8992 ///    \     /
8993 ///       +
8994 /// This tree has "mul" as its leaf values and "+" as its reduction
8995 /// instructions. A reduction can feed into a store or a binary operation
8996 /// feeding a phi.
8997 ///    ...
8998 ///    \  /
8999 ///     +
9000 ///     |
9001 ///  phi +=
9002 ///
9003 ///  Or:
9004 ///    ...
9005 ///    \  /
9006 ///     +
9007 ///     |
9008 ///   *p =
9009 ///
9010 class HorizontalReduction {
9011   using ReductionOpsType = SmallVector<Value *, 16>;
9012   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9013   ReductionOpsListType ReductionOps;
9014   SmallVector<Value *, 32> ReducedVals;
9015   // Use map vector to make stable output.
9016   MapVector<Instruction *, Value *> ExtraArgs;
9017   WeakTrackingVH ReductionRoot;
9018   /// The type of reduction operation.
9019   RecurKind RdxKind;
9020 
9021   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9022 
9023   static bool isCmpSelMinMax(Instruction *I) {
9024     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9025            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9026   }
9027 
9028   // And/or are potentially poison-safe logical patterns like:
9029   // select x, y, false
9030   // select x, true, y
9031   static bool isBoolLogicOp(Instruction *I) {
9032     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9033            match(I, m_LogicalOr(m_Value(), m_Value()));
9034   }
9035 
9036   /// Checks if instruction is associative and can be vectorized.
9037   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9038     if (Kind == RecurKind::None)
9039       return false;
9040 
9041     // Integer ops that map to select instructions or intrinsics are fine.
9042     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9043         isBoolLogicOp(I))
9044       return true;
9045 
9046     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9047       // FP min/max are associative except for NaN and -0.0. We do not
9048       // have to rule out -0.0 here because the intrinsic semantics do not
9049       // specify a fixed result for it.
9050       return I->getFastMathFlags().noNaNs();
9051     }
9052 
9053     return I->isAssociative();
9054   }
9055 
9056   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9057     // Poison-safe 'or' takes the form: select X, true, Y
9058     // To make that work with the normal operand processing, we skip the
9059     // true value operand.
9060     // TODO: Change the code and data structures to handle this without a hack.
9061     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9062       return I->getOperand(2);
9063     return I->getOperand(Index);
9064   }
9065 
9066   /// Checks if the ParentStackElem.first should be marked as a reduction
9067   /// operation with an extra argument or as extra argument itself.
9068   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9069                     Value *ExtraArg) {
9070     if (ExtraArgs.count(ParentStackElem.first)) {
9071       ExtraArgs[ParentStackElem.first] = nullptr;
9072       // We ran into something like:
9073       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9074       // The whole ParentStackElem.first should be considered as an extra value
9075       // in this case.
9076       // Do not perform analysis of remaining operands of ParentStackElem.first
9077       // instruction, this whole instruction is an extra argument.
9078       ParentStackElem.second = INVALID_OPERAND_INDEX;
9079     } else {
9080       // We ran into something like:
9081       // ParentStackElem.first += ... + ExtraArg + ...
9082       ExtraArgs[ParentStackElem.first] = ExtraArg;
9083     }
9084   }
9085 
9086   /// Creates reduction operation with the current opcode.
9087   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9088                          Value *RHS, const Twine &Name, bool UseSelect) {
9089     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9090     switch (Kind) {
9091     case RecurKind::Or:
9092       if (UseSelect &&
9093           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9094         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9095       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9096                                  Name);
9097     case RecurKind::And:
9098       if (UseSelect &&
9099           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9100         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9101       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9102                                  Name);
9103     case RecurKind::Add:
9104     case RecurKind::Mul:
9105     case RecurKind::Xor:
9106     case RecurKind::FAdd:
9107     case RecurKind::FMul:
9108       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9109                                  Name);
9110     case RecurKind::FMax:
9111       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9112     case RecurKind::FMin:
9113       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9114     case RecurKind::SMax:
9115       if (UseSelect) {
9116         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9117         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9118       }
9119       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9120     case RecurKind::SMin:
9121       if (UseSelect) {
9122         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9123         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9124       }
9125       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9126     case RecurKind::UMax:
9127       if (UseSelect) {
9128         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9129         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9130       }
9131       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9132     case RecurKind::UMin:
9133       if (UseSelect) {
9134         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9135         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9136       }
9137       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9138     default:
9139       llvm_unreachable("Unknown reduction operation.");
9140     }
9141   }
9142 
9143   /// Creates reduction operation with the current opcode with the IR flags
9144   /// from \p ReductionOps.
9145   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9146                          Value *RHS, const Twine &Name,
9147                          const ReductionOpsListType &ReductionOps) {
9148     bool UseSelect = ReductionOps.size() == 2 ||
9149                      // Logical or/and.
9150                      (ReductionOps.size() == 1 &&
9151                       isa<SelectInst>(ReductionOps.front().front()));
9152     assert((!UseSelect || ReductionOps.size() != 2 ||
9153             isa<SelectInst>(ReductionOps[1][0])) &&
9154            "Expected cmp + select pairs for reduction");
9155     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9156     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9157       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9158         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9159         propagateIRFlags(Op, ReductionOps[1]);
9160         return Op;
9161       }
9162     }
9163     propagateIRFlags(Op, ReductionOps[0]);
9164     return Op;
9165   }
9166 
9167   /// Creates reduction operation with the current opcode with the IR flags
9168   /// from \p I.
9169   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9170                          Value *RHS, const Twine &Name, Instruction *I) {
9171     auto *SelI = dyn_cast<SelectInst>(I);
9172     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9173     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9174       if (auto *Sel = dyn_cast<SelectInst>(Op))
9175         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9176     }
9177     propagateIRFlags(Op, I);
9178     return Op;
9179   }
9180 
9181   static RecurKind getRdxKind(Instruction *I) {
9182     assert(I && "Expected instruction for reduction matching");
9183     if (match(I, m_Add(m_Value(), m_Value())))
9184       return RecurKind::Add;
9185     if (match(I, m_Mul(m_Value(), m_Value())))
9186       return RecurKind::Mul;
9187     if (match(I, m_And(m_Value(), m_Value())) ||
9188         match(I, m_LogicalAnd(m_Value(), m_Value())))
9189       return RecurKind::And;
9190     if (match(I, m_Or(m_Value(), m_Value())) ||
9191         match(I, m_LogicalOr(m_Value(), m_Value())))
9192       return RecurKind::Or;
9193     if (match(I, m_Xor(m_Value(), m_Value())))
9194       return RecurKind::Xor;
9195     if (match(I, m_FAdd(m_Value(), m_Value())))
9196       return RecurKind::FAdd;
9197     if (match(I, m_FMul(m_Value(), m_Value())))
9198       return RecurKind::FMul;
9199 
9200     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9201       return RecurKind::FMax;
9202     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9203       return RecurKind::FMin;
9204 
9205     // This matches either cmp+select or intrinsics. SLP is expected to handle
9206     // either form.
9207     // TODO: If we are canonicalizing to intrinsics, we can remove several
9208     //       special-case paths that deal with selects.
9209     if (match(I, m_SMax(m_Value(), m_Value())))
9210       return RecurKind::SMax;
9211     if (match(I, m_SMin(m_Value(), m_Value())))
9212       return RecurKind::SMin;
9213     if (match(I, m_UMax(m_Value(), m_Value())))
9214       return RecurKind::UMax;
9215     if (match(I, m_UMin(m_Value(), m_Value())))
9216       return RecurKind::UMin;
9217 
9218     if (auto *Select = dyn_cast<SelectInst>(I)) {
9219       // Try harder: look for min/max pattern based on instructions producing
9220       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9221       // During the intermediate stages of SLP, it's very common to have
9222       // pattern like this (since optimizeGatherSequence is run only once
9223       // at the end):
9224       // %1 = extractelement <2 x i32> %a, i32 0
9225       // %2 = extractelement <2 x i32> %a, i32 1
9226       // %cond = icmp sgt i32 %1, %2
9227       // %3 = extractelement <2 x i32> %a, i32 0
9228       // %4 = extractelement <2 x i32> %a, i32 1
9229       // %select = select i1 %cond, i32 %3, i32 %4
9230       CmpInst::Predicate Pred;
9231       Instruction *L1;
9232       Instruction *L2;
9233 
9234       Value *LHS = Select->getTrueValue();
9235       Value *RHS = Select->getFalseValue();
9236       Value *Cond = Select->getCondition();
9237 
9238       // TODO: Support inverse predicates.
9239       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9240         if (!isa<ExtractElementInst>(RHS) ||
9241             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9242           return RecurKind::None;
9243       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9244         if (!isa<ExtractElementInst>(LHS) ||
9245             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9246           return RecurKind::None;
9247       } else {
9248         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9249           return RecurKind::None;
9250         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9251             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9252             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9253           return RecurKind::None;
9254       }
9255 
9256       switch (Pred) {
9257       default:
9258         return RecurKind::None;
9259       case CmpInst::ICMP_SGT:
9260       case CmpInst::ICMP_SGE:
9261         return RecurKind::SMax;
9262       case CmpInst::ICMP_SLT:
9263       case CmpInst::ICMP_SLE:
9264         return RecurKind::SMin;
9265       case CmpInst::ICMP_UGT:
9266       case CmpInst::ICMP_UGE:
9267         return RecurKind::UMax;
9268       case CmpInst::ICMP_ULT:
9269       case CmpInst::ICMP_ULE:
9270         return RecurKind::UMin;
9271       }
9272     }
9273     return RecurKind::None;
9274   }
9275 
9276   /// Get the index of the first operand.
9277   static unsigned getFirstOperandIndex(Instruction *I) {
9278     return isCmpSelMinMax(I) ? 1 : 0;
9279   }
9280 
9281   /// Total number of operands in the reduction operation.
9282   static unsigned getNumberOfOperands(Instruction *I) {
9283     return isCmpSelMinMax(I) ? 3 : 2;
9284   }
9285 
9286   /// Checks if the instruction is in basic block \p BB.
9287   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9288   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9289     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9290       auto *Sel = cast<SelectInst>(I);
9291       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9292       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9293     }
9294     return I->getParent() == BB;
9295   }
9296 
9297   /// Expected number of uses for reduction operations/reduced values.
9298   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9299     if (IsCmpSelMinMax) {
9300       // SelectInst must be used twice while the condition op must have single
9301       // use only.
9302       if (auto *Sel = dyn_cast<SelectInst>(I))
9303         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9304       return I->hasNUses(2);
9305     }
9306 
9307     // Arithmetic reduction operation must be used once only.
9308     return I->hasOneUse();
9309   }
9310 
9311   /// Initializes the list of reduction operations.
9312   void initReductionOps(Instruction *I) {
9313     if (isCmpSelMinMax(I))
9314       ReductionOps.assign(2, ReductionOpsType());
9315     else
9316       ReductionOps.assign(1, ReductionOpsType());
9317   }
9318 
9319   /// Add all reduction operations for the reduction instruction \p I.
9320   void addReductionOps(Instruction *I) {
9321     if (isCmpSelMinMax(I)) {
9322       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9323       ReductionOps[1].emplace_back(I);
9324     } else {
9325       ReductionOps[0].emplace_back(I);
9326     }
9327   }
9328 
9329   static Value *getLHS(RecurKind Kind, Instruction *I) {
9330     if (Kind == RecurKind::None)
9331       return nullptr;
9332     return I->getOperand(getFirstOperandIndex(I));
9333   }
9334   static Value *getRHS(RecurKind Kind, Instruction *I) {
9335     if (Kind == RecurKind::None)
9336       return nullptr;
9337     return I->getOperand(getFirstOperandIndex(I) + 1);
9338   }
9339 
9340 public:
9341   HorizontalReduction() = default;
9342 
9343   /// Try to find a reduction tree.
9344   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9345     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9346            "Phi needs to use the binary operator");
9347     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9348             isa<IntrinsicInst>(Inst)) &&
9349            "Expected binop, select, or intrinsic for reduction matching");
9350     RdxKind = getRdxKind(Inst);
9351 
9352     // We could have a initial reductions that is not an add.
9353     //  r *= v1 + v2 + v3 + v4
9354     // In such a case start looking for a tree rooted in the first '+'.
9355     if (Phi) {
9356       if (getLHS(RdxKind, Inst) == Phi) {
9357         Phi = nullptr;
9358         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9359         if (!Inst)
9360           return false;
9361         RdxKind = getRdxKind(Inst);
9362       } else if (getRHS(RdxKind, Inst) == Phi) {
9363         Phi = nullptr;
9364         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9365         if (!Inst)
9366           return false;
9367         RdxKind = getRdxKind(Inst);
9368       }
9369     }
9370 
9371     if (!isVectorizable(RdxKind, Inst))
9372       return false;
9373 
9374     // Analyze "regular" integer/FP types for reductions - no target-specific
9375     // types or pointers.
9376     Type *Ty = Inst->getType();
9377     if (!isValidElementType(Ty) || Ty->isPointerTy())
9378       return false;
9379 
9380     // Though the ultimate reduction may have multiple uses, its condition must
9381     // have only single use.
9382     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9383       if (!Sel->getCondition()->hasOneUse())
9384         return false;
9385 
9386     ReductionRoot = Inst;
9387 
9388     // The opcode for leaf values that we perform a reduction on.
9389     // For example: load(x) + load(y) + load(z) + fptoui(w)
9390     // The leaf opcode for 'w' does not match, so we don't include it as a
9391     // potential candidate for the reduction.
9392     unsigned LeafOpcode = 0;
9393 
9394     // Post-order traverse the reduction tree starting at Inst. We only handle
9395     // true trees containing binary operators or selects.
9396     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9397     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9398     initReductionOps(Inst);
9399     while (!Stack.empty()) {
9400       Instruction *TreeN = Stack.back().first;
9401       unsigned EdgeToVisit = Stack.back().second++;
9402       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9403       bool IsReducedValue = TreeRdxKind != RdxKind;
9404 
9405       // Postorder visit.
9406       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9407         if (IsReducedValue)
9408           ReducedVals.push_back(TreeN);
9409         else {
9410           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9411           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9412             // Check if TreeN is an extra argument of its parent operation.
9413             if (Stack.size() <= 1) {
9414               // TreeN can't be an extra argument as it is a root reduction
9415               // operation.
9416               return false;
9417             }
9418             // Yes, TreeN is an extra argument, do not add it to a list of
9419             // reduction operations.
9420             // Stack[Stack.size() - 2] always points to the parent operation.
9421             markExtraArg(Stack[Stack.size() - 2], TreeN);
9422             ExtraArgs.erase(TreeN);
9423           } else
9424             addReductionOps(TreeN);
9425         }
9426         // Retract.
9427         Stack.pop_back();
9428         continue;
9429       }
9430 
9431       // Visit operands.
9432       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9433       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9434       if (!EdgeInst) {
9435         // Edge value is not a reduction instruction or a leaf instruction.
9436         // (It may be a constant, function argument, or something else.)
9437         markExtraArg(Stack.back(), EdgeVal);
9438         continue;
9439       }
9440       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9441       // Continue analysis if the next operand is a reduction operation or
9442       // (possibly) a leaf value. If the leaf value opcode is not set,
9443       // the first met operation != reduction operation is considered as the
9444       // leaf opcode.
9445       // Only handle trees in the current basic block.
9446       // Each tree node needs to have minimal number of users except for the
9447       // ultimate reduction.
9448       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9449       if (EdgeInst != Phi && EdgeInst != Inst &&
9450           hasSameParent(EdgeInst, Inst->getParent()) &&
9451           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9452           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9453         if (IsRdxInst) {
9454           // We need to be able to reassociate the reduction operations.
9455           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9456             // I is an extra argument for TreeN (its parent operation).
9457             markExtraArg(Stack.back(), EdgeInst);
9458             continue;
9459           }
9460         } else if (!LeafOpcode) {
9461           LeafOpcode = EdgeInst->getOpcode();
9462         }
9463         Stack.push_back(
9464             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9465         continue;
9466       }
9467       // I is an extra argument for TreeN (its parent operation).
9468       markExtraArg(Stack.back(), EdgeInst);
9469     }
9470     return true;
9471   }
9472 
9473   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9474   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9475     // If there are a sufficient number of reduction values, reduce
9476     // to a nearby power-of-2. We can safely generate oversized
9477     // vectors and rely on the backend to split them to legal sizes.
9478     unsigned NumReducedVals = ReducedVals.size();
9479     if (NumReducedVals < 4)
9480       return nullptr;
9481 
9482     // Intersect the fast-math-flags from all reduction operations.
9483     FastMathFlags RdxFMF;
9484     RdxFMF.set();
9485     for (ReductionOpsType &RdxOp : ReductionOps) {
9486       for (Value *RdxVal : RdxOp) {
9487         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9488           RdxFMF &= FPMO->getFastMathFlags();
9489       }
9490     }
9491 
9492     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9493     Builder.setFastMathFlags(RdxFMF);
9494 
9495     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9496     // The same extra argument may be used several times, so log each attempt
9497     // to use it.
9498     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9499       assert(Pair.first && "DebugLoc must be set.");
9500       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9501     }
9502 
9503     // The compare instruction of a min/max is the insertion point for new
9504     // instructions and may be replaced with a new compare instruction.
9505     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9506       assert(isa<SelectInst>(RdxRootInst) &&
9507              "Expected min/max reduction to have select root instruction");
9508       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9509       assert(isa<Instruction>(ScalarCond) &&
9510              "Expected min/max reduction to have compare condition");
9511       return cast<Instruction>(ScalarCond);
9512     };
9513 
9514     // The reduction root is used as the insertion point for new instructions,
9515     // so set it as externally used to prevent it from being deleted.
9516     ExternallyUsedValues[ReductionRoot];
9517     SmallVector<Value *, 16> IgnoreList;
9518     for (ReductionOpsType &RdxOp : ReductionOps)
9519       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9520 
9521     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9522     if (NumReducedVals > ReduxWidth) {
9523       // In the loop below, we are building a tree based on a window of
9524       // 'ReduxWidth' values.
9525       // If the operands of those values have common traits (compare predicate,
9526       // constant operand, etc), then we want to group those together to
9527       // minimize the cost of the reduction.
9528 
9529       // TODO: This should be extended to count common operands for
9530       //       compares and binops.
9531 
9532       // Step 1: Count the number of times each compare predicate occurs.
9533       SmallDenseMap<unsigned, unsigned> PredCountMap;
9534       for (Value *RdxVal : ReducedVals) {
9535         CmpInst::Predicate Pred;
9536         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9537           ++PredCountMap[Pred];
9538       }
9539       // Step 2: Sort the values so the most common predicates come first.
9540       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9541         CmpInst::Predicate PredA, PredB;
9542         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9543             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9544           return PredCountMap[PredA] > PredCountMap[PredB];
9545         }
9546         return false;
9547       });
9548     }
9549 
9550     Value *VectorizedTree = nullptr;
9551     unsigned i = 0;
9552     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9553       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9554       V.buildTree(VL, IgnoreList);
9555       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9556         break;
9557       if (V.isLoadCombineReductionCandidate(RdxKind))
9558         break;
9559       V.reorderTopToBottom();
9560       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9561       V.buildExternalUses(ExternallyUsedValues);
9562 
9563       // For a poison-safe boolean logic reduction, do not replace select
9564       // instructions with logic ops. All reduced values will be frozen (see
9565       // below) to prevent leaking poison.
9566       if (isa<SelectInst>(ReductionRoot) &&
9567           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9568           NumReducedVals != ReduxWidth)
9569         break;
9570 
9571       V.computeMinimumValueSizes();
9572 
9573       // Estimate cost.
9574       InstructionCost TreeCost =
9575           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9576       InstructionCost ReductionCost =
9577           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9578       InstructionCost Cost = TreeCost + ReductionCost;
9579       if (!Cost.isValid()) {
9580         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9581         return nullptr;
9582       }
9583       if (Cost >= -SLPCostThreshold) {
9584         V.getORE()->emit([&]() {
9585           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9586                                           cast<Instruction>(VL[0]))
9587                  << "Vectorizing horizontal reduction is possible"
9588                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9589                  << " and threshold "
9590                  << ore::NV("Threshold", -SLPCostThreshold);
9591         });
9592         break;
9593       }
9594 
9595       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9596                         << Cost << ". (HorRdx)\n");
9597       V.getORE()->emit([&]() {
9598         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9599                                   cast<Instruction>(VL[0]))
9600                << "Vectorized horizontal reduction with cost "
9601                << ore::NV("Cost", Cost) << " and with tree size "
9602                << ore::NV("TreeSize", V.getTreeSize());
9603       });
9604 
9605       // Vectorize a tree.
9606       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9607       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9608 
9609       // Emit a reduction. If the root is a select (min/max idiom), the insert
9610       // point is the compare condition of that select.
9611       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9612       if (isCmpSelMinMax(RdxRootInst))
9613         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9614       else
9615         Builder.SetInsertPoint(RdxRootInst);
9616 
9617       // To prevent poison from leaking across what used to be sequential, safe,
9618       // scalar boolean logic operations, the reduction operand must be frozen.
9619       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9620         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9621 
9622       Value *ReducedSubTree =
9623           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9624 
9625       if (!VectorizedTree) {
9626         // Initialize the final value in the reduction.
9627         VectorizedTree = ReducedSubTree;
9628       } else {
9629         // Update the final value in the reduction.
9630         Builder.SetCurrentDebugLocation(Loc);
9631         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9632                                   ReducedSubTree, "op.rdx", ReductionOps);
9633       }
9634       i += ReduxWidth;
9635       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9636     }
9637 
9638     if (VectorizedTree) {
9639       // Finish the reduction.
9640       for (; i < NumReducedVals; ++i) {
9641         auto *I = cast<Instruction>(ReducedVals[i]);
9642         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9643         VectorizedTree =
9644             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9645       }
9646       for (auto &Pair : ExternallyUsedValues) {
9647         // Add each externally used value to the final reduction.
9648         for (auto *I : Pair.second) {
9649           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9650           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9651                                     Pair.first, "op.extra", I);
9652         }
9653       }
9654 
9655       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9656 
9657       // Mark all scalar reduction ops for deletion, they are replaced by the
9658       // vector reductions.
9659       V.eraseInstructions(IgnoreList);
9660     }
9661     return VectorizedTree;
9662   }
9663 
9664   unsigned numReductionValues() const { return ReducedVals.size(); }
9665 
9666 private:
9667   /// Calculate the cost of a reduction.
9668   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9669                                    Value *FirstReducedVal, unsigned ReduxWidth,
9670                                    FastMathFlags FMF) {
9671     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9672     Type *ScalarTy = FirstReducedVal->getType();
9673     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9674     InstructionCost VectorCost, ScalarCost;
9675     switch (RdxKind) {
9676     case RecurKind::Add:
9677     case RecurKind::Mul:
9678     case RecurKind::Or:
9679     case RecurKind::And:
9680     case RecurKind::Xor:
9681     case RecurKind::FAdd:
9682     case RecurKind::FMul: {
9683       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9684       VectorCost =
9685           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9686       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9687       break;
9688     }
9689     case RecurKind::FMax:
9690     case RecurKind::FMin: {
9691       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9692       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9693       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9694                                                /*IsUnsigned=*/false, CostKind);
9695       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9696       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9697                                            SclCondTy, RdxPred, CostKind) +
9698                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9699                                            SclCondTy, RdxPred, CostKind);
9700       break;
9701     }
9702     case RecurKind::SMax:
9703     case RecurKind::SMin:
9704     case RecurKind::UMax:
9705     case RecurKind::UMin: {
9706       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9707       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9708       bool IsUnsigned =
9709           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9710       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9711                                                CostKind);
9712       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9713       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9714                                            SclCondTy, RdxPred, CostKind) +
9715                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9716                                            SclCondTy, RdxPred, CostKind);
9717       break;
9718     }
9719     default:
9720       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9721     }
9722 
9723     // Scalar cost is repeated for N-1 elements.
9724     ScalarCost *= (ReduxWidth - 1);
9725     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9726                       << " for reduction that starts with " << *FirstReducedVal
9727                       << " (It is a splitting reduction)\n");
9728     return VectorCost - ScalarCost;
9729   }
9730 
9731   /// Emit a horizontal reduction of the vectorized value.
9732   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9733                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9734     assert(VectorizedValue && "Need to have a vectorized tree node");
9735     assert(isPowerOf2_32(ReduxWidth) &&
9736            "We only handle power-of-two reductions for now");
9737     assert(RdxKind != RecurKind::FMulAdd &&
9738            "A call to the llvm.fmuladd intrinsic is not handled yet");
9739 
9740     ++NumVectorInstructions;
9741     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9742   }
9743 };
9744 
9745 } // end anonymous namespace
9746 
9747 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9748   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9749     return cast<FixedVectorType>(IE->getType())->getNumElements();
9750 
9751   unsigned AggregateSize = 1;
9752   auto *IV = cast<InsertValueInst>(InsertInst);
9753   Type *CurrentType = IV->getType();
9754   do {
9755     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9756       for (auto *Elt : ST->elements())
9757         if (Elt != ST->getElementType(0)) // check homogeneity
9758           return None;
9759       AggregateSize *= ST->getNumElements();
9760       CurrentType = ST->getElementType(0);
9761     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9762       AggregateSize *= AT->getNumElements();
9763       CurrentType = AT->getElementType();
9764     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9765       AggregateSize *= VT->getNumElements();
9766       return AggregateSize;
9767     } else if (CurrentType->isSingleValueType()) {
9768       return AggregateSize;
9769     } else {
9770       return None;
9771     }
9772   } while (true);
9773 }
9774 
9775 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9776                                    TargetTransformInfo *TTI,
9777                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9778                                    SmallVectorImpl<Value *> &InsertElts,
9779                                    unsigned OperandOffset) {
9780   do {
9781     Value *InsertedOperand = LastInsertInst->getOperand(1);
9782     Optional<unsigned> OperandIndex =
9783         getInsertIndex(LastInsertInst, OperandOffset);
9784     if (!OperandIndex)
9785       return;
9786     if (isa<InsertElementInst>(InsertedOperand) ||
9787         isa<InsertValueInst>(InsertedOperand)) {
9788       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9789                              BuildVectorOpds, InsertElts, *OperandIndex);
9790 
9791     } else {
9792       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9793       InsertElts[*OperandIndex] = LastInsertInst;
9794     }
9795     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9796   } while (LastInsertInst != nullptr &&
9797            (isa<InsertValueInst>(LastInsertInst) ||
9798             isa<InsertElementInst>(LastInsertInst)) &&
9799            LastInsertInst->hasOneUse());
9800 }
9801 
9802 /// Recognize construction of vectors like
9803 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9804 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9805 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9806 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9807 ///  starting from the last insertelement or insertvalue instruction.
9808 ///
9809 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9810 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9811 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9812 ///
9813 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9814 ///
9815 /// \return true if it matches.
9816 static bool findBuildAggregate(Instruction *LastInsertInst,
9817                                TargetTransformInfo *TTI,
9818                                SmallVectorImpl<Value *> &BuildVectorOpds,
9819                                SmallVectorImpl<Value *> &InsertElts) {
9820 
9821   assert((isa<InsertElementInst>(LastInsertInst) ||
9822           isa<InsertValueInst>(LastInsertInst)) &&
9823          "Expected insertelement or insertvalue instruction!");
9824 
9825   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9826          "Expected empty result vectors!");
9827 
9828   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9829   if (!AggregateSize)
9830     return false;
9831   BuildVectorOpds.resize(*AggregateSize);
9832   InsertElts.resize(*AggregateSize);
9833 
9834   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
9835   llvm::erase_value(BuildVectorOpds, nullptr);
9836   llvm::erase_value(InsertElts, nullptr);
9837   if (BuildVectorOpds.size() >= 2)
9838     return true;
9839 
9840   return false;
9841 }
9842 
9843 /// Try and get a reduction value from a phi node.
9844 ///
9845 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9846 /// if they come from either \p ParentBB or a containing loop latch.
9847 ///
9848 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9849 /// if not possible.
9850 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9851                                 BasicBlock *ParentBB, LoopInfo *LI) {
9852   // There are situations where the reduction value is not dominated by the
9853   // reduction phi. Vectorizing such cases has been reported to cause
9854   // miscompiles. See PR25787.
9855   auto DominatedReduxValue = [&](Value *R) {
9856     return isa<Instruction>(R) &&
9857            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9858   };
9859 
9860   Value *Rdx = nullptr;
9861 
9862   // Return the incoming value if it comes from the same BB as the phi node.
9863   if (P->getIncomingBlock(0) == ParentBB) {
9864     Rdx = P->getIncomingValue(0);
9865   } else if (P->getIncomingBlock(1) == ParentBB) {
9866     Rdx = P->getIncomingValue(1);
9867   }
9868 
9869   if (Rdx && DominatedReduxValue(Rdx))
9870     return Rdx;
9871 
9872   // Otherwise, check whether we have a loop latch to look at.
9873   Loop *BBL = LI->getLoopFor(ParentBB);
9874   if (!BBL)
9875     return nullptr;
9876   BasicBlock *BBLatch = BBL->getLoopLatch();
9877   if (!BBLatch)
9878     return nullptr;
9879 
9880   // There is a loop latch, return the incoming value if it comes from
9881   // that. This reduction pattern occasionally turns up.
9882   if (P->getIncomingBlock(0) == BBLatch) {
9883     Rdx = P->getIncomingValue(0);
9884   } else if (P->getIncomingBlock(1) == BBLatch) {
9885     Rdx = P->getIncomingValue(1);
9886   }
9887 
9888   if (Rdx && DominatedReduxValue(Rdx))
9889     return Rdx;
9890 
9891   return nullptr;
9892 }
9893 
9894 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9895   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9896     return true;
9897   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9898     return true;
9899   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9900     return true;
9901   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9902     return true;
9903   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9904     return true;
9905   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9906     return true;
9907   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9908     return true;
9909   return false;
9910 }
9911 
9912 /// Attempt to reduce a horizontal reduction.
9913 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9914 /// with reduction operators \a Root (or one of its operands) in a basic block
9915 /// \a BB, then check if it can be done. If horizontal reduction is not found
9916 /// and root instruction is a binary operation, vectorization of the operands is
9917 /// attempted.
9918 /// \returns true if a horizontal reduction was matched and reduced or operands
9919 /// of one of the binary instruction were vectorized.
9920 /// \returns false if a horizontal reduction was not matched (or not possible)
9921 /// or no vectorization of any binary operation feeding \a Root instruction was
9922 /// performed.
9923 static bool tryToVectorizeHorReductionOrInstOperands(
9924     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9925     TargetTransformInfo *TTI,
9926     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9927   if (!ShouldVectorizeHor)
9928     return false;
9929 
9930   if (!Root)
9931     return false;
9932 
9933   if (Root->getParent() != BB || isa<PHINode>(Root))
9934     return false;
9935   // Start analysis starting from Root instruction. If horizontal reduction is
9936   // found, try to vectorize it. If it is not a horizontal reduction or
9937   // vectorization is not possible or not effective, and currently analyzed
9938   // instruction is a binary operation, try to vectorize the operands, using
9939   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9940   // the same procedure considering each operand as a possible root of the
9941   // horizontal reduction.
9942   // Interrupt the process if the Root instruction itself was vectorized or all
9943   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9944   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9945   // CmpInsts so we can skip extra attempts in
9946   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9947   std::queue<std::pair<Instruction *, unsigned>> Stack;
9948   Stack.emplace(Root, 0);
9949   SmallPtrSet<Value *, 8> VisitedInstrs;
9950   SmallVector<WeakTrackingVH> PostponedInsts;
9951   bool Res = false;
9952   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9953                                      Value *&B1) -> Value * {
9954     bool IsBinop = matchRdxBop(Inst, B0, B1);
9955     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9956     if (IsBinop || IsSelect) {
9957       HorizontalReduction HorRdx;
9958       if (HorRdx.matchAssociativeReduction(P, Inst))
9959         return HorRdx.tryToReduce(R, TTI);
9960     }
9961     return nullptr;
9962   };
9963   while (!Stack.empty()) {
9964     Instruction *Inst;
9965     unsigned Level;
9966     std::tie(Inst, Level) = Stack.front();
9967     Stack.pop();
9968     // Do not try to analyze instruction that has already been vectorized.
9969     // This may happen when we vectorize instruction operands on a previous
9970     // iteration while stack was populated before that happened.
9971     if (R.isDeleted(Inst))
9972       continue;
9973     Value *B0 = nullptr, *B1 = nullptr;
9974     if (Value *V = TryToReduce(Inst, B0, B1)) {
9975       Res = true;
9976       // Set P to nullptr to avoid re-analysis of phi node in
9977       // matchAssociativeReduction function unless this is the root node.
9978       P = nullptr;
9979       if (auto *I = dyn_cast<Instruction>(V)) {
9980         // Try to find another reduction.
9981         Stack.emplace(I, Level);
9982         continue;
9983       }
9984     } else {
9985       bool IsBinop = B0 && B1;
9986       if (P && IsBinop) {
9987         Inst = dyn_cast<Instruction>(B0);
9988         if (Inst == P)
9989           Inst = dyn_cast<Instruction>(B1);
9990         if (!Inst) {
9991           // Set P to nullptr to avoid re-analysis of phi node in
9992           // matchAssociativeReduction function unless this is the root node.
9993           P = nullptr;
9994           continue;
9995         }
9996       }
9997       // Set P to nullptr to avoid re-analysis of phi node in
9998       // matchAssociativeReduction function unless this is the root node.
9999       P = nullptr;
10000       // Do not try to vectorize CmpInst operands, this is done separately.
10001       // Final attempt for binop args vectorization should happen after the loop
10002       // to try to find reductions.
10003       if (!isa<CmpInst>(Inst))
10004         PostponedInsts.push_back(Inst);
10005     }
10006 
10007     // Try to vectorize operands.
10008     // Continue analysis for the instruction from the same basic block only to
10009     // save compile time.
10010     if (++Level < RecursionMaxDepth)
10011       for (auto *Op : Inst->operand_values())
10012         if (VisitedInstrs.insert(Op).second)
10013           if (auto *I = dyn_cast<Instruction>(Op))
10014             // Do not try to vectorize CmpInst operands,  this is done
10015             // separately.
10016             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10017                 I->getParent() == BB)
10018               Stack.emplace(I, Level);
10019   }
10020   // Try to vectorized binops where reductions were not found.
10021   for (Value *V : PostponedInsts)
10022     if (auto *Inst = dyn_cast<Instruction>(V))
10023       if (!R.isDeleted(Inst))
10024         Res |= Vectorize(Inst, R);
10025   return Res;
10026 }
10027 
10028 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10029                                                  BasicBlock *BB, BoUpSLP &R,
10030                                                  TargetTransformInfo *TTI) {
10031   auto *I = dyn_cast_or_null<Instruction>(V);
10032   if (!I)
10033     return false;
10034 
10035   if (!isa<BinaryOperator>(I))
10036     P = nullptr;
10037   // Try to match and vectorize a horizontal reduction.
10038   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10039     return tryToVectorize(I, R);
10040   };
10041   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10042                                                   ExtraVectorization);
10043 }
10044 
10045 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10046                                                  BasicBlock *BB, BoUpSLP &R) {
10047   const DataLayout &DL = BB->getModule()->getDataLayout();
10048   if (!R.canMapToVector(IVI->getType(), DL))
10049     return false;
10050 
10051   SmallVector<Value *, 16> BuildVectorOpds;
10052   SmallVector<Value *, 16> BuildVectorInsts;
10053   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10054     return false;
10055 
10056   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10057   // Aggregate value is unlikely to be processed in vector register.
10058   return tryToVectorizeList(BuildVectorOpds, R);
10059 }
10060 
10061 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10062                                                    BasicBlock *BB, BoUpSLP &R) {
10063   SmallVector<Value *, 16> BuildVectorInsts;
10064   SmallVector<Value *, 16> BuildVectorOpds;
10065   SmallVector<int> Mask;
10066   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10067       (llvm::all_of(
10068            BuildVectorOpds,
10069            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10070        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10071     return false;
10072 
10073   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10074   return tryToVectorizeList(BuildVectorInsts, R);
10075 }
10076 
10077 template <typename T>
10078 static bool
10079 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10080                        function_ref<unsigned(T *)> Limit,
10081                        function_ref<bool(T *, T *)> Comparator,
10082                        function_ref<bool(T *, T *)> AreCompatible,
10083                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10084                        bool LimitForRegisterSize) {
10085   bool Changed = false;
10086   // Sort by type, parent, operands.
10087   stable_sort(Incoming, Comparator);
10088 
10089   // Try to vectorize elements base on their type.
10090   SmallVector<T *> Candidates;
10091   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10092     // Look for the next elements with the same type, parent and operand
10093     // kinds.
10094     auto *SameTypeIt = IncIt;
10095     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10096       ++SameTypeIt;
10097 
10098     // Try to vectorize them.
10099     unsigned NumElts = (SameTypeIt - IncIt);
10100     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10101                       << NumElts << ")\n");
10102     // The vectorization is a 3-state attempt:
10103     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10104     // size of maximal register at first.
10105     // 2. Try to vectorize remaining instructions with the same type, if
10106     // possible. This may result in the better vectorization results rather than
10107     // if we try just to vectorize instructions with the same/alternate opcodes.
10108     // 3. Final attempt to try to vectorize all instructions with the
10109     // same/alternate ops only, this may result in some extra final
10110     // vectorization.
10111     if (NumElts > 1 &&
10112         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10113       // Success start over because instructions might have been changed.
10114       Changed = true;
10115     } else if (NumElts < Limit(*IncIt) &&
10116                (Candidates.empty() ||
10117                 Candidates.front()->getType() == (*IncIt)->getType())) {
10118       Candidates.append(IncIt, std::next(IncIt, NumElts));
10119     }
10120     // Final attempt to vectorize instructions with the same types.
10121     if (Candidates.size() > 1 &&
10122         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10123       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10124         // Success start over because instructions might have been changed.
10125         Changed = true;
10126       } else if (LimitForRegisterSize) {
10127         // Try to vectorize using small vectors.
10128         for (auto *It = Candidates.begin(), *End = Candidates.end();
10129              It != End;) {
10130           auto *SameTypeIt = It;
10131           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10132             ++SameTypeIt;
10133           unsigned NumElts = (SameTypeIt - It);
10134           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10135                                             /*LimitForRegisterSize=*/false))
10136             Changed = true;
10137           It = SameTypeIt;
10138         }
10139       }
10140       Candidates.clear();
10141     }
10142 
10143     // Start over at the next instruction of a different type (or the end).
10144     IncIt = SameTypeIt;
10145   }
10146   return Changed;
10147 }
10148 
10149 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10150 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10151 /// operands. If IsCompatibility is false, function implements strict weak
10152 /// ordering relation between two cmp instructions, returning true if the first
10153 /// instruction is "less" than the second, i.e. its predicate is less than the
10154 /// predicate of the second or the operands IDs are less than the operands IDs
10155 /// of the second cmp instruction.
10156 template <bool IsCompatibility>
10157 static bool compareCmp(Value *V, Value *V2,
10158                        function_ref<bool(Instruction *)> IsDeleted) {
10159   auto *CI1 = cast<CmpInst>(V);
10160   auto *CI2 = cast<CmpInst>(V2);
10161   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10162     return false;
10163   if (CI1->getOperand(0)->getType()->getTypeID() <
10164       CI2->getOperand(0)->getType()->getTypeID())
10165     return !IsCompatibility;
10166   if (CI1->getOperand(0)->getType()->getTypeID() >
10167       CI2->getOperand(0)->getType()->getTypeID())
10168     return false;
10169   CmpInst::Predicate Pred1 = CI1->getPredicate();
10170   CmpInst::Predicate Pred2 = CI2->getPredicate();
10171   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10172   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10173   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10174   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10175   if (BasePred1 < BasePred2)
10176     return !IsCompatibility;
10177   if (BasePred1 > BasePred2)
10178     return false;
10179   // Compare operands.
10180   bool LEPreds = Pred1 <= Pred2;
10181   bool GEPreds = Pred1 >= Pred2;
10182   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10183     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10184     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10185     if (Op1->getValueID() < Op2->getValueID())
10186       return !IsCompatibility;
10187     if (Op1->getValueID() > Op2->getValueID())
10188       return false;
10189     if (auto *I1 = dyn_cast<Instruction>(Op1))
10190       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10191         if (I1->getParent() != I2->getParent())
10192           return false;
10193         InstructionsState S = getSameOpcode({I1, I2});
10194         if (S.getOpcode())
10195           continue;
10196         return false;
10197       }
10198   }
10199   return IsCompatibility;
10200 }
10201 
10202 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10203     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10204     bool AtTerminator) {
10205   bool OpsChanged = false;
10206   SmallVector<Instruction *, 4> PostponedCmps;
10207   for (auto *I : reverse(Instructions)) {
10208     if (R.isDeleted(I))
10209       continue;
10210     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10211       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10212     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10213       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10214     else if (isa<CmpInst>(I))
10215       PostponedCmps.push_back(I);
10216   }
10217   if (AtTerminator) {
10218     // Try to find reductions first.
10219     for (Instruction *I : PostponedCmps) {
10220       if (R.isDeleted(I))
10221         continue;
10222       for (Value *Op : I->operands())
10223         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10224     }
10225     // Try to vectorize operands as vector bundles.
10226     for (Instruction *I : PostponedCmps) {
10227       if (R.isDeleted(I))
10228         continue;
10229       OpsChanged |= tryToVectorize(I, R);
10230     }
10231     // Try to vectorize list of compares.
10232     // Sort by type, compare predicate, etc.
10233     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10234       return compareCmp<false>(V, V2,
10235                                [&R](Instruction *I) { return R.isDeleted(I); });
10236     };
10237 
10238     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10239       if (V1 == V2)
10240         return true;
10241       return compareCmp<true>(V1, V2,
10242                               [&R](Instruction *I) { return R.isDeleted(I); });
10243     };
10244     auto Limit = [&R](Value *V) {
10245       unsigned EltSize = R.getVectorElementSize(V);
10246       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10247     };
10248 
10249     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10250     OpsChanged |= tryToVectorizeSequence<Value>(
10251         Vals, Limit, CompareSorter, AreCompatibleCompares,
10252         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10253           // Exclude possible reductions from other blocks.
10254           bool ArePossiblyReducedInOtherBlock =
10255               any_of(Candidates, [](Value *V) {
10256                 return any_of(V->users(), [V](User *U) {
10257                   return isa<SelectInst>(U) &&
10258                          cast<SelectInst>(U)->getParent() !=
10259                              cast<Instruction>(V)->getParent();
10260                 });
10261               });
10262           if (ArePossiblyReducedInOtherBlock)
10263             return false;
10264           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10265         },
10266         /*LimitForRegisterSize=*/true);
10267     Instructions.clear();
10268   } else {
10269     // Insert in reverse order since the PostponedCmps vector was filled in
10270     // reverse order.
10271     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10272   }
10273   return OpsChanged;
10274 }
10275 
10276 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10277   bool Changed = false;
10278   SmallVector<Value *, 4> Incoming;
10279   SmallPtrSet<Value *, 16> VisitedInstrs;
10280   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10281   // node. Allows better to identify the chains that can be vectorized in the
10282   // better way.
10283   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10284   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10285     assert(isValidElementType(V1->getType()) &&
10286            isValidElementType(V2->getType()) &&
10287            "Expected vectorizable types only.");
10288     // It is fine to compare type IDs here, since we expect only vectorizable
10289     // types, like ints, floats and pointers, we don't care about other type.
10290     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10291       return true;
10292     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10293       return false;
10294     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10295     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10296     if (Opcodes1.size() < Opcodes2.size())
10297       return true;
10298     if (Opcodes1.size() > Opcodes2.size())
10299       return false;
10300     Optional<bool> ConstOrder;
10301     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10302       // Undefs are compatible with any other value.
10303       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10304         if (!ConstOrder)
10305           ConstOrder =
10306               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10307         continue;
10308       }
10309       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10310         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10311           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10312           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10313           if (!NodeI1)
10314             return NodeI2 != nullptr;
10315           if (!NodeI2)
10316             return false;
10317           assert((NodeI1 == NodeI2) ==
10318                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10319                  "Different nodes should have different DFS numbers");
10320           if (NodeI1 != NodeI2)
10321             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10322           InstructionsState S = getSameOpcode({I1, I2});
10323           if (S.getOpcode())
10324             continue;
10325           return I1->getOpcode() < I2->getOpcode();
10326         }
10327       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10328         if (!ConstOrder)
10329           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10330         continue;
10331       }
10332       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10333         return true;
10334       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10335         return false;
10336     }
10337     return ConstOrder && *ConstOrder;
10338   };
10339   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10340     if (V1 == V2)
10341       return true;
10342     if (V1->getType() != V2->getType())
10343       return false;
10344     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10345     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10346     if (Opcodes1.size() != Opcodes2.size())
10347       return false;
10348     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10349       // Undefs are compatible with any other value.
10350       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10351         continue;
10352       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10353         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10354           if (I1->getParent() != I2->getParent())
10355             return false;
10356           InstructionsState S = getSameOpcode({I1, I2});
10357           if (S.getOpcode())
10358             continue;
10359           return false;
10360         }
10361       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10362         continue;
10363       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10364         return false;
10365     }
10366     return true;
10367   };
10368   auto Limit = [&R](Value *V) {
10369     unsigned EltSize = R.getVectorElementSize(V);
10370     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10371   };
10372 
10373   bool HaveVectorizedPhiNodes = false;
10374   do {
10375     // Collect the incoming values from the PHIs.
10376     Incoming.clear();
10377     for (Instruction &I : *BB) {
10378       PHINode *P = dyn_cast<PHINode>(&I);
10379       if (!P)
10380         break;
10381 
10382       // No need to analyze deleted, vectorized and non-vectorizable
10383       // instructions.
10384       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10385           isValidElementType(P->getType()))
10386         Incoming.push_back(P);
10387     }
10388 
10389     // Find the corresponding non-phi nodes for better matching when trying to
10390     // build the tree.
10391     for (Value *V : Incoming) {
10392       SmallVectorImpl<Value *> &Opcodes =
10393           PHIToOpcodes.try_emplace(V).first->getSecond();
10394       if (!Opcodes.empty())
10395         continue;
10396       SmallVector<Value *, 4> Nodes(1, V);
10397       SmallPtrSet<Value *, 4> Visited;
10398       while (!Nodes.empty()) {
10399         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10400         if (!Visited.insert(PHI).second)
10401           continue;
10402         for (Value *V : PHI->incoming_values()) {
10403           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10404             Nodes.push_back(PHI1);
10405             continue;
10406           }
10407           Opcodes.emplace_back(V);
10408         }
10409       }
10410     }
10411 
10412     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10413         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10414         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10415           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10416         },
10417         /*LimitForRegisterSize=*/true);
10418     Changed |= HaveVectorizedPhiNodes;
10419     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10420   } while (HaveVectorizedPhiNodes);
10421 
10422   VisitedInstrs.clear();
10423 
10424   SmallVector<Instruction *, 8> PostProcessInstructions;
10425   SmallDenseSet<Instruction *, 4> KeyNodes;
10426   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10427     // Skip instructions with scalable type. The num of elements is unknown at
10428     // compile-time for scalable type.
10429     if (isa<ScalableVectorType>(it->getType()))
10430       continue;
10431 
10432     // Skip instructions marked for the deletion.
10433     if (R.isDeleted(&*it))
10434       continue;
10435     // We may go through BB multiple times so skip the one we have checked.
10436     if (!VisitedInstrs.insert(&*it).second) {
10437       if (it->use_empty() && KeyNodes.contains(&*it) &&
10438           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10439                                       it->isTerminator())) {
10440         // We would like to start over since some instructions are deleted
10441         // and the iterator may become invalid value.
10442         Changed = true;
10443         it = BB->begin();
10444         e = BB->end();
10445       }
10446       continue;
10447     }
10448 
10449     if (isa<DbgInfoIntrinsic>(it))
10450       continue;
10451 
10452     // Try to vectorize reductions that use PHINodes.
10453     if (PHINode *P = dyn_cast<PHINode>(it)) {
10454       // Check that the PHI is a reduction PHI.
10455       if (P->getNumIncomingValues() == 2) {
10456         // Try to match and vectorize a horizontal reduction.
10457         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10458                                      TTI)) {
10459           Changed = true;
10460           it = BB->begin();
10461           e = BB->end();
10462           continue;
10463         }
10464       }
10465       // Try to vectorize the incoming values of the PHI, to catch reductions
10466       // that feed into PHIs.
10467       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10468         // Skip if the incoming block is the current BB for now. Also, bypass
10469         // unreachable IR for efficiency and to avoid crashing.
10470         // TODO: Collect the skipped incoming values and try to vectorize them
10471         // after processing BB.
10472         if (BB == P->getIncomingBlock(I) ||
10473             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10474           continue;
10475 
10476         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10477                                             P->getIncomingBlock(I), R, TTI);
10478       }
10479       continue;
10480     }
10481 
10482     // Ran into an instruction without users, like terminator, or function call
10483     // with ignored return value, store. Ignore unused instructions (basing on
10484     // instruction type, except for CallInst and InvokeInst).
10485     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10486                             isa<InvokeInst>(it))) {
10487       KeyNodes.insert(&*it);
10488       bool OpsChanged = false;
10489       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10490         for (auto *V : it->operand_values()) {
10491           // Try to match and vectorize a horizontal reduction.
10492           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10493         }
10494       }
10495       // Start vectorization of post-process list of instructions from the
10496       // top-tree instructions to try to vectorize as many instructions as
10497       // possible.
10498       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10499                                                 it->isTerminator());
10500       if (OpsChanged) {
10501         // We would like to start over since some instructions are deleted
10502         // and the iterator may become invalid value.
10503         Changed = true;
10504         it = BB->begin();
10505         e = BB->end();
10506         continue;
10507       }
10508     }
10509 
10510     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10511         isa<InsertValueInst>(it))
10512       PostProcessInstructions.push_back(&*it);
10513   }
10514 
10515   return Changed;
10516 }
10517 
10518 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10519   auto Changed = false;
10520   for (auto &Entry : GEPs) {
10521     // If the getelementptr list has fewer than two elements, there's nothing
10522     // to do.
10523     if (Entry.second.size() < 2)
10524       continue;
10525 
10526     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10527                       << Entry.second.size() << ".\n");
10528 
10529     // Process the GEP list in chunks suitable for the target's supported
10530     // vector size. If a vector register can't hold 1 element, we are done. We
10531     // are trying to vectorize the index computations, so the maximum number of
10532     // elements is based on the size of the index expression, rather than the
10533     // size of the GEP itself (the target's pointer size).
10534     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10535     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10536     if (MaxVecRegSize < EltSize)
10537       continue;
10538 
10539     unsigned MaxElts = MaxVecRegSize / EltSize;
10540     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10541       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10542       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10543 
10544       // Initialize a set a candidate getelementptrs. Note that we use a
10545       // SetVector here to preserve program order. If the index computations
10546       // are vectorizable and begin with loads, we want to minimize the chance
10547       // of having to reorder them later.
10548       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10549 
10550       // Some of the candidates may have already been vectorized after we
10551       // initially collected them. If so, they are marked as deleted, so remove
10552       // them from the set of candidates.
10553       Candidates.remove_if(
10554           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10555 
10556       // Remove from the set of candidates all pairs of getelementptrs with
10557       // constant differences. Such getelementptrs are likely not good
10558       // candidates for vectorization in a bottom-up phase since one can be
10559       // computed from the other. We also ensure all candidate getelementptr
10560       // indices are unique.
10561       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10562         auto *GEPI = GEPList[I];
10563         if (!Candidates.count(GEPI))
10564           continue;
10565         auto *SCEVI = SE->getSCEV(GEPList[I]);
10566         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10567           auto *GEPJ = GEPList[J];
10568           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10569           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10570             Candidates.remove(GEPI);
10571             Candidates.remove(GEPJ);
10572           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10573             Candidates.remove(GEPJ);
10574           }
10575         }
10576       }
10577 
10578       // We break out of the above computation as soon as we know there are
10579       // fewer than two candidates remaining.
10580       if (Candidates.size() < 2)
10581         continue;
10582 
10583       // Add the single, non-constant index of each candidate to the bundle. We
10584       // ensured the indices met these constraints when we originally collected
10585       // the getelementptrs.
10586       SmallVector<Value *, 16> Bundle(Candidates.size());
10587       auto BundleIndex = 0u;
10588       for (auto *V : Candidates) {
10589         auto *GEP = cast<GetElementPtrInst>(V);
10590         auto *GEPIdx = GEP->idx_begin()->get();
10591         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10592         Bundle[BundleIndex++] = GEPIdx;
10593       }
10594 
10595       // Try and vectorize the indices. We are currently only interested in
10596       // gather-like cases of the form:
10597       //
10598       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10599       //
10600       // where the loads of "a", the loads of "b", and the subtractions can be
10601       // performed in parallel. It's likely that detecting this pattern in a
10602       // bottom-up phase will be simpler and less costly than building a
10603       // full-blown top-down phase beginning at the consecutive loads.
10604       Changed |= tryToVectorizeList(Bundle, R);
10605     }
10606   }
10607   return Changed;
10608 }
10609 
10610 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10611   bool Changed = false;
10612   // Sort by type, base pointers and values operand. Value operands must be
10613   // compatible (have the same opcode, same parent), otherwise it is
10614   // definitely not profitable to try to vectorize them.
10615   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10616     if (V->getPointerOperandType()->getTypeID() <
10617         V2->getPointerOperandType()->getTypeID())
10618       return true;
10619     if (V->getPointerOperandType()->getTypeID() >
10620         V2->getPointerOperandType()->getTypeID())
10621       return false;
10622     // UndefValues are compatible with all other values.
10623     if (isa<UndefValue>(V->getValueOperand()) ||
10624         isa<UndefValue>(V2->getValueOperand()))
10625       return false;
10626     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10627       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10628         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10629             DT->getNode(I1->getParent());
10630         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10631             DT->getNode(I2->getParent());
10632         assert(NodeI1 && "Should only process reachable instructions");
10633         assert(NodeI1 && "Should only process reachable instructions");
10634         assert((NodeI1 == NodeI2) ==
10635                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10636                "Different nodes should have different DFS numbers");
10637         if (NodeI1 != NodeI2)
10638           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10639         InstructionsState S = getSameOpcode({I1, I2});
10640         if (S.getOpcode())
10641           return false;
10642         return I1->getOpcode() < I2->getOpcode();
10643       }
10644     if (isa<Constant>(V->getValueOperand()) &&
10645         isa<Constant>(V2->getValueOperand()))
10646       return false;
10647     return V->getValueOperand()->getValueID() <
10648            V2->getValueOperand()->getValueID();
10649   };
10650 
10651   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10652     if (V1 == V2)
10653       return true;
10654     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10655       return false;
10656     // Undefs are compatible with any other value.
10657     if (isa<UndefValue>(V1->getValueOperand()) ||
10658         isa<UndefValue>(V2->getValueOperand()))
10659       return true;
10660     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10661       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10662         if (I1->getParent() != I2->getParent())
10663           return false;
10664         InstructionsState S = getSameOpcode({I1, I2});
10665         return S.getOpcode() > 0;
10666       }
10667     if (isa<Constant>(V1->getValueOperand()) &&
10668         isa<Constant>(V2->getValueOperand()))
10669       return true;
10670     return V1->getValueOperand()->getValueID() ==
10671            V2->getValueOperand()->getValueID();
10672   };
10673   auto Limit = [&R, this](StoreInst *SI) {
10674     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10675     return R.getMinVF(EltSize);
10676   };
10677 
10678   // Attempt to sort and vectorize each of the store-groups.
10679   for (auto &Pair : Stores) {
10680     if (Pair.second.size() < 2)
10681       continue;
10682 
10683     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10684                       << Pair.second.size() << ".\n");
10685 
10686     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10687       continue;
10688 
10689     Changed |= tryToVectorizeSequence<StoreInst>(
10690         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10691         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10692           return vectorizeStores(Candidates, R);
10693         },
10694         /*LimitForRegisterSize=*/false);
10695   }
10696   return Changed;
10697 }
10698 
10699 char SLPVectorizer::ID = 0;
10700 
10701 static const char lv_name[] = "SLP Vectorizer";
10702 
10703 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10704 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10705 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10706 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10707 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10708 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10709 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10710 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10711 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10712 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10713 
10714 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10715