1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 // Limit the number of alias checks. The limit is chosen so that
172 // it has no negative effect on the llvm benchmarks.
173 static const unsigned AliasedCheckLimit = 10;
174 
175 // Another limit for the alias checks: The maximum distance between load/store
176 // instructions where alias checks are done.
177 // This limit is useful for very large basic blocks.
178 static const unsigned MaxMemDepDistance = 160;
179 
180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
181 /// regions to be handled.
182 static const int MinScheduleRegionSize = 16;
183 
184 /// Predicate for the element types that the SLP vectorizer supports.
185 ///
186 /// The most important thing to filter here are types which are invalid in LLVM
187 /// vectors. We also filter target specific types which have absolutely no
188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
189 /// avoids spending time checking the cost model and realizing that they will
190 /// be inevitably scalarized.
191 static bool isValidElementType(Type *Ty) {
192   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
193          !Ty->isPPC_FP128Ty();
194 }
195 
196 /// \returns True if the value is a constant (but not globals/constant
197 /// expressions).
198 static bool isConstant(Value *V) {
199   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
200 }
201 
202 /// Checks if \p V is one of vector-like instructions, i.e. undef,
203 /// insertelement/extractelement with constant indices for fixed vector type or
204 /// extractvalue instruction.
205 static bool isVectorLikeInstWithConstOps(Value *V) {
206   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
207       !isa<ExtractValueInst, UndefValue>(V))
208     return false;
209   auto *I = dyn_cast<Instruction>(V);
210   if (!I || isa<ExtractValueInst>(I))
211     return true;
212   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
213     return false;
214   if (isa<ExtractElementInst>(I))
215     return isConstant(I->getOperand(1));
216   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
217   return isConstant(I->getOperand(2));
218 }
219 
220 /// \returns true if all of the instructions in \p VL are in the same block or
221 /// false otherwise.
222 static bool allSameBlock(ArrayRef<Value *> VL) {
223   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
224   if (!I0)
225     return false;
226   if (all_of(VL, isVectorLikeInstWithConstOps))
227     return true;
228 
229   BasicBlock *BB = I0->getParent();
230   for (int I = 1, E = VL.size(); I < E; I++) {
231     auto *II = dyn_cast<Instruction>(VL[I]);
232     if (!II)
233       return false;
234 
235     if (BB != II->getParent())
236       return false;
237   }
238   return true;
239 }
240 
241 /// \returns True if all of the values in \p VL are constants (but not
242 /// globals/constant expressions).
243 static bool allConstant(ArrayRef<Value *> VL) {
244   // Constant expressions and globals can't be vectorized like normal integer/FP
245   // constants.
246   return all_of(VL, isConstant);
247 }
248 
249 /// \returns True if all of the values in \p VL are identical or some of them
250 /// are UndefValue.
251 static bool isSplat(ArrayRef<Value *> VL) {
252   Value *FirstNonUndef = nullptr;
253   for (Value *V : VL) {
254     if (isa<UndefValue>(V))
255       continue;
256     if (!FirstNonUndef) {
257       FirstNonUndef = V;
258       continue;
259     }
260     if (V != FirstNonUndef)
261       return false;
262   }
263   return FirstNonUndef != nullptr;
264 }
265 
266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
267 static bool isCommutative(Instruction *I) {
268   if (auto *Cmp = dyn_cast<CmpInst>(I))
269     return Cmp->isCommutative();
270   if (auto *BO = dyn_cast<BinaryOperator>(I))
271     return BO->isCommutative();
272   // TODO: This should check for generic Instruction::isCommutative(), but
273   //       we need to confirm that the caller code correctly handles Intrinsics
274   //       for example (does not have 2 operands).
275   return false;
276 }
277 
278 /// Checks if the given value is actually an undefined constant vector.
279 static bool isUndefVector(const Value *V) {
280   if (isa<UndefValue>(V))
281     return true;
282   auto *C = dyn_cast<Constant>(V);
283   if (!C)
284     return false;
285   if (!C->containsUndefOrPoisonElement())
286     return false;
287   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
288   if (!VecTy)
289     return false;
290   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
291     if (Constant *Elem = C->getAggregateElement(I))
292       if (!isa<UndefValue>(Elem))
293         return false;
294   }
295   return true;
296 }
297 
298 /// Checks if the vector of instructions can be represented as a shuffle, like:
299 /// %x0 = extractelement <4 x i8> %x, i32 0
300 /// %x3 = extractelement <4 x i8> %x, i32 3
301 /// %y1 = extractelement <4 x i8> %y, i32 1
302 /// %y2 = extractelement <4 x i8> %y, i32 2
303 /// %x0x0 = mul i8 %x0, %x0
304 /// %x3x3 = mul i8 %x3, %x3
305 /// %y1y1 = mul i8 %y1, %y1
306 /// %y2y2 = mul i8 %y2, %y2
307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
311 /// ret <4 x i8> %ins4
312 /// can be transformed into:
313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
314 ///                                                         i32 6>
315 /// %2 = mul <4 x i8> %1, %1
316 /// ret <4 x i8> %2
317 /// We convert this initially to something like:
318 /// %x0 = extractelement <4 x i8> %x, i32 0
319 /// %x3 = extractelement <4 x i8> %x, i32 3
320 /// %y1 = extractelement <4 x i8> %y, i32 1
321 /// %y2 = extractelement <4 x i8> %y, i32 2
322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
326 /// %5 = mul <4 x i8> %4, %4
327 /// %6 = extractelement <4 x i8> %5, i32 0
328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
329 /// %7 = extractelement <4 x i8> %5, i32 1
330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
331 /// %8 = extractelement <4 x i8> %5, i32 2
332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
333 /// %9 = extractelement <4 x i8> %5, i32 3
334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
335 /// ret <4 x i8> %ins4
336 /// InstCombiner transforms this into a shuffle and vector mul
337 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
338 /// TODO: Can we split off and reuse the shuffle mask detection from
339 /// TargetTransformInfo::getInstructionThroughput?
340 static Optional<TargetTransformInfo::ShuffleKind>
341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
342   const auto *It =
343       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
344   if (It == VL.end())
345     return None;
346   auto *EI0 = cast<ExtractElementInst>(*It);
347   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
348     return None;
349   unsigned Size =
350       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
351   Value *Vec1 = nullptr;
352   Value *Vec2 = nullptr;
353   enum ShuffleMode { Unknown, Select, Permute };
354   ShuffleMode CommonShuffleMode = Unknown;
355   Mask.assign(VL.size(), UndefMaskElem);
356   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
357     // Undef can be represented as an undef element in a vector.
358     if (isa<UndefValue>(VL[I]))
359       continue;
360     auto *EI = cast<ExtractElementInst>(VL[I]);
361     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
362       return None;
363     auto *Vec = EI->getVectorOperand();
364     // We can extractelement from undef or poison vector.
365     if (isUndefVector(Vec))
366       continue;
367     // All vector operands must have the same number of vector elements.
368     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
369       return None;
370     if (isa<UndefValue>(EI->getIndexOperand()))
371       continue;
372     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
373     if (!Idx)
374       return None;
375     // Undefined behavior if Idx is negative or >= Size.
376     if (Idx->getValue().uge(Size))
377       continue;
378     unsigned IntIdx = Idx->getValue().getZExtValue();
379     Mask[I] = IntIdx;
380     // For correct shuffling we have to have at most 2 different vector operands
381     // in all extractelement instructions.
382     if (!Vec1 || Vec1 == Vec) {
383       Vec1 = Vec;
384     } else if (!Vec2 || Vec2 == Vec) {
385       Vec2 = Vec;
386       Mask[I] += Size;
387     } else {
388       return None;
389     }
390     if (CommonShuffleMode == Permute)
391       continue;
392     // If the extract index is not the same as the operation number, it is a
393     // permutation.
394     if (IntIdx != I) {
395       CommonShuffleMode = Permute;
396       continue;
397     }
398     CommonShuffleMode = Select;
399   }
400   // If we're not crossing lanes in different vectors, consider it as blending.
401   if (CommonShuffleMode == Select && Vec2)
402     return TargetTransformInfo::SK_Select;
403   // If Vec2 was never used, we have a permutation of a single vector, otherwise
404   // we have permutation of 2 vectors.
405   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
406               : TargetTransformInfo::SK_PermuteSingleSrc;
407 }
408 
409 namespace {
410 
411 /// Main data required for vectorization of instructions.
412 struct InstructionsState {
413   /// The very first instruction in the list with the main opcode.
414   Value *OpValue = nullptr;
415 
416   /// The main/alternate instruction.
417   Instruction *MainOp = nullptr;
418   Instruction *AltOp = nullptr;
419 
420   /// The main/alternate opcodes for the list of instructions.
421   unsigned getOpcode() const {
422     return MainOp ? MainOp->getOpcode() : 0;
423   }
424 
425   unsigned getAltOpcode() const {
426     return AltOp ? AltOp->getOpcode() : 0;
427   }
428 
429   /// Some of the instructions in the list have alternate opcodes.
430   bool isAltShuffle() const { return AltOp != MainOp; }
431 
432   bool isOpcodeOrAlt(Instruction *I) const {
433     unsigned CheckedOpcode = I->getOpcode();
434     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
435   }
436 
437   InstructionsState() = delete;
438   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
439       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
440 };
441 
442 } // end anonymous namespace
443 
444 /// Chooses the correct key for scheduling data. If \p Op has the same (or
445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
446 /// OpValue.
447 static Value *isOneOf(const InstructionsState &S, Value *Op) {
448   auto *I = dyn_cast<Instruction>(Op);
449   if (I && S.isOpcodeOrAlt(I))
450     return Op;
451   return S.OpValue;
452 }
453 
454 /// \returns true if \p Opcode is allowed as part of of the main/alternate
455 /// instruction for SLP vectorization.
456 ///
457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
458 /// "shuffled out" lane would result in division by zero.
459 static bool isValidForAlternation(unsigned Opcode) {
460   if (Instruction::isIntDivRem(Opcode))
461     return false;
462 
463   return true;
464 }
465 
466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
467                                        unsigned BaseIndex = 0);
468 
469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
470 /// compatible instructions or constants, or just some other regular values.
471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
472                                 Value *Op1) {
473   return (isConstant(BaseOp0) && isConstant(Op0)) ||
474          (isConstant(BaseOp1) && isConstant(Op1)) ||
475          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
476           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
477          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
478          getSameOpcode({BaseOp1, Op1}).getOpcode();
479 }
480 
481 /// \returns analysis of the Instructions in \p VL described in
482 /// InstructionsState, the Opcode that we suppose the whole list
483 /// could be vectorized even if its structure is diverse.
484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
485                                        unsigned BaseIndex) {
486   // Make sure these are all Instructions.
487   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
488     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
489 
490   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
491   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
492   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
493   CmpInst::Predicate BasePred =
494       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
495               : CmpInst::BAD_ICMP_PREDICATE;
496   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
497   unsigned AltOpcode = Opcode;
498   unsigned AltIndex = BaseIndex;
499 
500   // Check for one alternate opcode from another BinaryOperator.
501   // TODO - generalize to support all operators (types, calls etc.).
502   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
503     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
504     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
505       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
506         continue;
507       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
508           isValidForAlternation(Opcode)) {
509         AltOpcode = InstOpcode;
510         AltIndex = Cnt;
511         continue;
512       }
513     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
514       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
515       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
516       if (Ty0 == Ty1) {
517         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518           continue;
519         if (Opcode == AltOpcode) {
520           assert(isValidForAlternation(Opcode) &&
521                  isValidForAlternation(InstOpcode) &&
522                  "Cast isn't safe for alternation, logic needs to be updated!");
523           AltOpcode = InstOpcode;
524           AltIndex = Cnt;
525           continue;
526         }
527       }
528     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
529       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
530       auto *Inst = cast<Instruction>(VL[Cnt]);
531       Type *Ty0 = BaseInst->getOperand(0)->getType();
532       Type *Ty1 = Inst->getOperand(0)->getType();
533       if (Ty0 == Ty1) {
534         Value *BaseOp0 = BaseInst->getOperand(0);
535         Value *BaseOp1 = BaseInst->getOperand(1);
536         Value *Op0 = Inst->getOperand(0);
537         Value *Op1 = Inst->getOperand(1);
538         CmpInst::Predicate CurrentPred =
539             cast<CmpInst>(VL[Cnt])->getPredicate();
540         CmpInst::Predicate SwappedCurrentPred =
541             CmpInst::getSwappedPredicate(CurrentPred);
542         // Check for compatible operands. If the corresponding operands are not
543         // compatible - need to perform alternate vectorization.
544         if (InstOpcode == Opcode) {
545           if (BasePred == CurrentPred &&
546               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
547             continue;
548           if (BasePred == SwappedCurrentPred &&
549               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
550             continue;
551           if (E == 2 &&
552               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
553             continue;
554           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
555           CmpInst::Predicate AltPred = AltInst->getPredicate();
556           Value *AltOp0 = AltInst->getOperand(0);
557           Value *AltOp1 = AltInst->getOperand(1);
558           // Check if operands are compatible with alternate operands.
559           if (AltPred == CurrentPred &&
560               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
561             continue;
562           if (AltPred == SwappedCurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
564             continue;
565         }
566         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
567           assert(isValidForAlternation(Opcode) &&
568                  isValidForAlternation(InstOpcode) &&
569                  "Cast isn't safe for alternation, logic needs to be updated!");
570           AltIndex = Cnt;
571           continue;
572         }
573         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
574         CmpInst::Predicate AltPred = AltInst->getPredicate();
575         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
576             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
577           continue;
578       }
579     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
580       continue;
581     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
582   }
583 
584   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
585                            cast<Instruction>(VL[AltIndex]));
586 }
587 
588 /// \returns true if all of the values in \p VL have the same type or false
589 /// otherwise.
590 static bool allSameType(ArrayRef<Value *> VL) {
591   Type *Ty = VL[0]->getType();
592   for (int i = 1, e = VL.size(); i < e; i++)
593     if (VL[i]->getType() != Ty)
594       return false;
595 
596   return true;
597 }
598 
599 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
600 static Optional<unsigned> getExtractIndex(Instruction *E) {
601   unsigned Opcode = E->getOpcode();
602   assert((Opcode == Instruction::ExtractElement ||
603           Opcode == Instruction::ExtractValue) &&
604          "Expected extractelement or extractvalue instruction.");
605   if (Opcode == Instruction::ExtractElement) {
606     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
607     if (!CI)
608       return None;
609     return CI->getZExtValue();
610   }
611   ExtractValueInst *EI = cast<ExtractValueInst>(E);
612   if (EI->getNumIndices() != 1)
613     return None;
614   return *EI->idx_begin();
615 }
616 
617 /// \returns True if in-tree use also needs extract. This refers to
618 /// possible scalar operand in vectorized instruction.
619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
620                                     TargetLibraryInfo *TLI) {
621   unsigned Opcode = UserInst->getOpcode();
622   switch (Opcode) {
623   case Instruction::Load: {
624     LoadInst *LI = cast<LoadInst>(UserInst);
625     return (LI->getPointerOperand() == Scalar);
626   }
627   case Instruction::Store: {
628     StoreInst *SI = cast<StoreInst>(UserInst);
629     return (SI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Call: {
632     CallInst *CI = cast<CallInst>(UserInst);
633     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
634     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
635       if (hasVectorInstrinsicScalarOpd(ID, i))
636         return (CI->getArgOperand(i) == Scalar);
637     }
638     LLVM_FALLTHROUGH;
639   }
640   default:
641     return false;
642   }
643 }
644 
645 /// \returns the AA location that is being access by the instruction.
646 static MemoryLocation getLocation(Instruction *I) {
647   if (StoreInst *SI = dyn_cast<StoreInst>(I))
648     return MemoryLocation::get(SI);
649   if (LoadInst *LI = dyn_cast<LoadInst>(I))
650     return MemoryLocation::get(LI);
651   return MemoryLocation();
652 }
653 
654 /// \returns True if the instruction is not a volatile or atomic load/store.
655 static bool isSimple(Instruction *I) {
656   if (LoadInst *LI = dyn_cast<LoadInst>(I))
657     return LI->isSimple();
658   if (StoreInst *SI = dyn_cast<StoreInst>(I))
659     return SI->isSimple();
660   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
661     return !MI->isVolatile();
662   return true;
663 }
664 
665 /// Shuffles \p Mask in accordance with the given \p SubMask.
666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
667   if (SubMask.empty())
668     return;
669   if (Mask.empty()) {
670     Mask.append(SubMask.begin(), SubMask.end());
671     return;
672   }
673   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
674   int TermValue = std::min(Mask.size(), SubMask.size());
675   for (int I = 0, E = SubMask.size(); I < E; ++I) {
676     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
677         Mask[SubMask[I]] >= TermValue)
678       continue;
679     NewMask[I] = Mask[SubMask[I]];
680   }
681   Mask.swap(NewMask);
682 }
683 
684 /// Order may have elements assigned special value (size) which is out of
685 /// bounds. Such indices only appear on places which correspond to undef values
686 /// (see canReuseExtract for details) and used in order to avoid undef values
687 /// have effect on operands ordering.
688 /// The first loop below simply finds all unused indices and then the next loop
689 /// nest assigns these indices for undef values positions.
690 /// As an example below Order has two undef positions and they have assigned
691 /// values 3 and 7 respectively:
692 /// before:  6 9 5 4 9 2 1 0
693 /// after:   6 3 5 4 7 2 1 0
694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
695   const unsigned Sz = Order.size();
696   SmallBitVector UnusedIndices(Sz, /*t=*/true);
697   SmallBitVector MaskedIndices(Sz);
698   for (unsigned I = 0; I < Sz; ++I) {
699     if (Order[I] < Sz)
700       UnusedIndices.reset(Order[I]);
701     else
702       MaskedIndices.set(I);
703   }
704   if (MaskedIndices.none())
705     return;
706   assert(UnusedIndices.count() == MaskedIndices.count() &&
707          "Non-synced masked/available indices.");
708   int Idx = UnusedIndices.find_first();
709   int MIdx = MaskedIndices.find_first();
710   while (MIdx >= 0) {
711     assert(Idx >= 0 && "Indices must be synced.");
712     Order[MIdx] = Idx;
713     Idx = UnusedIndices.find_next(Idx);
714     MIdx = MaskedIndices.find_next(MIdx);
715   }
716 }
717 
718 namespace llvm {
719 
720 static void inversePermutation(ArrayRef<unsigned> Indices,
721                                SmallVectorImpl<int> &Mask) {
722   Mask.clear();
723   const unsigned E = Indices.size();
724   Mask.resize(E, UndefMaskElem);
725   for (unsigned I = 0; I < E; ++I)
726     Mask[Indices[I]] = I;
727 }
728 
729 /// \returns inserting index of InsertElement or InsertValue instruction,
730 /// using Offset as base offset for index.
731 static Optional<unsigned> getInsertIndex(Value *InsertInst,
732                                          unsigned Offset = 0) {
733   int Index = Offset;
734   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
735     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
736       auto *VT = cast<FixedVectorType>(IE->getType());
737       if (CI->getValue().uge(VT->getNumElements()))
738         return None;
739       Index *= VT->getNumElements();
740       Index += CI->getZExtValue();
741       return Index;
742     }
743     return None;
744   }
745 
746   auto *IV = cast<InsertValueInst>(InsertInst);
747   Type *CurrentType = IV->getType();
748   for (unsigned I : IV->indices()) {
749     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
750       Index *= ST->getNumElements();
751       CurrentType = ST->getElementType(I);
752     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
753       Index *= AT->getNumElements();
754       CurrentType = AT->getElementType();
755     } else {
756       return None;
757     }
758     Index += I;
759   }
760   return Index;
761 }
762 
763 /// Reorders the list of scalars in accordance with the given \p Mask.
764 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
765                            ArrayRef<int> Mask) {
766   assert(!Mask.empty() && "Expected non-empty mask.");
767   SmallVector<Value *> Prev(Scalars.size(),
768                             UndefValue::get(Scalars.front()->getType()));
769   Prev.swap(Scalars);
770   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
771     if (Mask[I] != UndefMaskElem)
772       Scalars[Mask[I]] = Prev[I];
773 }
774 
775 namespace slpvectorizer {
776 
777 /// Bottom Up SLP Vectorizer.
778 class BoUpSLP {
779   struct TreeEntry;
780   struct ScheduleData;
781 
782 public:
783   using ValueList = SmallVector<Value *, 8>;
784   using InstrList = SmallVector<Instruction *, 16>;
785   using ValueSet = SmallPtrSet<Value *, 16>;
786   using StoreList = SmallVector<StoreInst *, 8>;
787   using ExtraValueToDebugLocsMap =
788       MapVector<Value *, SmallVector<Instruction *, 2>>;
789   using OrdersType = SmallVector<unsigned, 4>;
790 
791   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
792           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
793           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
794           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
795       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
796         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
797     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
798     // Use the vector register size specified by the target unless overridden
799     // by a command-line option.
800     // TODO: It would be better to limit the vectorization factor based on
801     //       data type rather than just register size. For example, x86 AVX has
802     //       256-bit registers, but it does not support integer operations
803     //       at that width (that requires AVX2).
804     if (MaxVectorRegSizeOption.getNumOccurrences())
805       MaxVecRegSize = MaxVectorRegSizeOption;
806     else
807       MaxVecRegSize =
808           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
809               .getFixedSize();
810 
811     if (MinVectorRegSizeOption.getNumOccurrences())
812       MinVecRegSize = MinVectorRegSizeOption;
813     else
814       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
815   }
816 
817   /// Vectorize the tree that starts with the elements in \p VL.
818   /// Returns the vectorized root.
819   Value *vectorizeTree();
820 
821   /// Vectorize the tree but with the list of externally used values \p
822   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
823   /// generated extractvalue instructions.
824   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
825 
826   /// \returns the cost incurred by unwanted spills and fills, caused by
827   /// holding live values over call sites.
828   InstructionCost getSpillCost() const;
829 
830   /// \returns the vectorization cost of the subtree that starts at \p VL.
831   /// A negative number means that this is profitable.
832   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
833 
834   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
835   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
836   void buildTree(ArrayRef<Value *> Roots,
837                  ArrayRef<Value *> UserIgnoreLst = None);
838 
839   /// Builds external uses of the vectorized scalars, i.e. the list of
840   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
841   /// ExternallyUsedValues contains additional list of external uses to handle
842   /// vectorization of reductions.
843   void
844   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
845 
846   /// Clear the internal data structures that are created by 'buildTree'.
847   void deleteTree() {
848     VectorizableTree.clear();
849     ScalarToTreeEntry.clear();
850     MustGather.clear();
851     ExternalUses.clear();
852     for (auto &Iter : BlocksSchedules) {
853       BlockScheduling *BS = Iter.second.get();
854       BS->clear();
855     }
856     MinBWs.clear();
857     InstrElementSize.clear();
858   }
859 
860   unsigned getTreeSize() const { return VectorizableTree.size(); }
861 
862   /// Perform LICM and CSE on the newly generated gather sequences.
863   void optimizeGatherSequence();
864 
865   /// Checks if the specified gather tree entry \p TE can be represented as a
866   /// shuffled vector entry + (possibly) permutation with other gathers. It
867   /// implements the checks only for possibly ordered scalars (Loads,
868   /// ExtractElement, ExtractValue), which can be part of the graph.
869   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
870 
871   /// Gets reordering data for the given tree entry. If the entry is vectorized
872   /// - just return ReorderIndices, otherwise check if the scalars can be
873   /// reordered and return the most optimal order.
874   /// \param TopToBottom If true, include the order of vectorized stores and
875   /// insertelement nodes, otherwise skip them.
876   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
877 
878   /// Reorders the current graph to the most profitable order starting from the
879   /// root node to the leaf nodes. The best order is chosen only from the nodes
880   /// of the same size (vectorization factor). Smaller nodes are considered
881   /// parts of subgraph with smaller VF and they are reordered independently. We
882   /// can make it because we still need to extend smaller nodes to the wider VF
883   /// and we can merge reordering shuffles with the widening shuffles.
884   void reorderTopToBottom();
885 
886   /// Reorders the current graph to the most profitable order starting from
887   /// leaves to the root. It allows to rotate small subgraphs and reduce the
888   /// number of reshuffles if the leaf nodes use the same order. In this case we
889   /// can merge the orders and just shuffle user node instead of shuffling its
890   /// operands. Plus, even the leaf nodes have different orders, it allows to
891   /// sink reordering in the graph closer to the root node and merge it later
892   /// during analysis.
893   void reorderBottomToTop(bool IgnoreReorder = false);
894 
895   /// \return The vector element size in bits to use when vectorizing the
896   /// expression tree ending at \p V. If V is a store, the size is the width of
897   /// the stored value. Otherwise, the size is the width of the largest loaded
898   /// value reaching V. This method is used by the vectorizer to calculate
899   /// vectorization factors.
900   unsigned getVectorElementSize(Value *V);
901 
902   /// Compute the minimum type sizes required to represent the entries in a
903   /// vectorizable tree.
904   void computeMinimumValueSizes();
905 
906   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
907   unsigned getMaxVecRegSize() const {
908     return MaxVecRegSize;
909   }
910 
911   // \returns minimum vector register size as set by cl::opt.
912   unsigned getMinVecRegSize() const {
913     return MinVecRegSize;
914   }
915 
916   unsigned getMinVF(unsigned Sz) const {
917     return std::max(2U, getMinVecRegSize() / Sz);
918   }
919 
920   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
921     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
922       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
923     return MaxVF ? MaxVF : UINT_MAX;
924   }
925 
926   /// Check if homogeneous aggregate is isomorphic to some VectorType.
927   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
928   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
929   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
930   ///
931   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
932   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
933 
934   /// \returns True if the VectorizableTree is both tiny and not fully
935   /// vectorizable. We do not vectorize such trees.
936   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
937 
938   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
939   /// can be load combined in the backend. Load combining may not be allowed in
940   /// the IR optimizer, so we do not want to alter the pattern. For example,
941   /// partially transforming a scalar bswap() pattern into vector code is
942   /// effectively impossible for the backend to undo.
943   /// TODO: If load combining is allowed in the IR optimizer, this analysis
944   ///       may not be necessary.
945   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
946 
947   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
948   /// can be load combined in the backend. Load combining may not be allowed in
949   /// the IR optimizer, so we do not want to alter the pattern. For example,
950   /// partially transforming a scalar bswap() pattern into vector code is
951   /// effectively impossible for the backend to undo.
952   /// TODO: If load combining is allowed in the IR optimizer, this analysis
953   ///       may not be necessary.
954   bool isLoadCombineCandidate() const;
955 
956   OptimizationRemarkEmitter *getORE() { return ORE; }
957 
958   /// This structure holds any data we need about the edges being traversed
959   /// during buildTree_rec(). We keep track of:
960   /// (i) the user TreeEntry index, and
961   /// (ii) the index of the edge.
962   struct EdgeInfo {
963     EdgeInfo() = default;
964     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
965         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
966     /// The user TreeEntry.
967     TreeEntry *UserTE = nullptr;
968     /// The operand index of the use.
969     unsigned EdgeIdx = UINT_MAX;
970 #ifndef NDEBUG
971     friend inline raw_ostream &operator<<(raw_ostream &OS,
972                                           const BoUpSLP::EdgeInfo &EI) {
973       EI.dump(OS);
974       return OS;
975     }
976     /// Debug print.
977     void dump(raw_ostream &OS) const {
978       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
979          << " EdgeIdx:" << EdgeIdx << "}";
980     }
981     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
982 #endif
983   };
984 
985   /// A helper data structure to hold the operands of a vector of instructions.
986   /// This supports a fixed vector length for all operand vectors.
987   class VLOperands {
988     /// For each operand we need (i) the value, and (ii) the opcode that it
989     /// would be attached to if the expression was in a left-linearized form.
990     /// This is required to avoid illegal operand reordering.
991     /// For example:
992     /// \verbatim
993     ///                         0 Op1
994     ///                         |/
995     /// Op1 Op2   Linearized    + Op2
996     ///   \ /     ---------->   |/
997     ///    -                    -
998     ///
999     /// Op1 - Op2            (0 + Op1) - Op2
1000     /// \endverbatim
1001     ///
1002     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1003     ///
1004     /// Another way to think of this is to track all the operations across the
1005     /// path from the operand all the way to the root of the tree and to
1006     /// calculate the operation that corresponds to this path. For example, the
1007     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1008     /// corresponding operation is a '-' (which matches the one in the
1009     /// linearized tree, as shown above).
1010     ///
1011     /// For lack of a better term, we refer to this operation as Accumulated
1012     /// Path Operation (APO).
1013     struct OperandData {
1014       OperandData() = default;
1015       OperandData(Value *V, bool APO, bool IsUsed)
1016           : V(V), APO(APO), IsUsed(IsUsed) {}
1017       /// The operand value.
1018       Value *V = nullptr;
1019       /// TreeEntries only allow a single opcode, or an alternate sequence of
1020       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1021       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1022       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1023       /// (e.g., Add/Mul)
1024       bool APO = false;
1025       /// Helper data for the reordering function.
1026       bool IsUsed = false;
1027     };
1028 
1029     /// During operand reordering, we are trying to select the operand at lane
1030     /// that matches best with the operand at the neighboring lane. Our
1031     /// selection is based on the type of value we are looking for. For example,
1032     /// if the neighboring lane has a load, we need to look for a load that is
1033     /// accessing a consecutive address. These strategies are summarized in the
1034     /// 'ReorderingMode' enumerator.
1035     enum class ReorderingMode {
1036       Load,     ///< Matching loads to consecutive memory addresses
1037       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1038       Constant, ///< Matching constants
1039       Splat,    ///< Matching the same instruction multiple times (broadcast)
1040       Failed,   ///< We failed to create a vectorizable group
1041     };
1042 
1043     using OperandDataVec = SmallVector<OperandData, 2>;
1044 
1045     /// A vector of operand vectors.
1046     SmallVector<OperandDataVec, 4> OpsVec;
1047 
1048     const DataLayout &DL;
1049     ScalarEvolution &SE;
1050     const BoUpSLP &R;
1051 
1052     /// \returns the operand data at \p OpIdx and \p Lane.
1053     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1054       return OpsVec[OpIdx][Lane];
1055     }
1056 
1057     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1058     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1059       return OpsVec[OpIdx][Lane];
1060     }
1061 
1062     /// Clears the used flag for all entries.
1063     void clearUsed() {
1064       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1065            OpIdx != NumOperands; ++OpIdx)
1066         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1067              ++Lane)
1068           OpsVec[OpIdx][Lane].IsUsed = false;
1069     }
1070 
1071     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1072     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1073       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1074     }
1075 
1076     // The hard-coded scores listed here are not very important, though it shall
1077     // be higher for better matches to improve the resulting cost. When
1078     // computing the scores of matching one sub-tree with another, we are
1079     // basically counting the number of values that are matching. So even if all
1080     // scores are set to 1, we would still get a decent matching result.
1081     // However, sometimes we have to break ties. For example we may have to
1082     // choose between matching loads vs matching opcodes. This is what these
1083     // scores are helping us with: they provide the order of preference. Also,
1084     // this is important if the scalar is externally used or used in another
1085     // tree entry node in the different lane.
1086 
1087     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1088     static const int ScoreConsecutiveLoads = 4;
1089     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1090     static const int ScoreReversedLoads = 3;
1091     /// ExtractElementInst from same vector and consecutive indexes.
1092     static const int ScoreConsecutiveExtracts = 4;
1093     /// ExtractElementInst from same vector and reversed indices.
1094     static const int ScoreReversedExtracts = 3;
1095     /// Constants.
1096     static const int ScoreConstants = 2;
1097     /// Instructions with the same opcode.
1098     static const int ScoreSameOpcode = 2;
1099     /// Instructions with alt opcodes (e.g, add + sub).
1100     static const int ScoreAltOpcodes = 1;
1101     /// Identical instructions (a.k.a. splat or broadcast).
1102     static const int ScoreSplat = 1;
1103     /// Matching with an undef is preferable to failing.
1104     static const int ScoreUndef = 1;
1105     /// Score for failing to find a decent match.
1106     static const int ScoreFail = 0;
1107     /// Score if all users are vectorized.
1108     static const int ScoreAllUserVectorized = 1;
1109 
1110     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1111     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1112     /// MainAltOps.
1113     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1114                                ScalarEvolution &SE, int NumLanes,
1115                                ArrayRef<Value *> MainAltOps) {
1116       if (V1 == V2)
1117         return VLOperands::ScoreSplat;
1118 
1119       auto *LI1 = dyn_cast<LoadInst>(V1);
1120       auto *LI2 = dyn_cast<LoadInst>(V2);
1121       if (LI1 && LI2) {
1122         if (LI1->getParent() != LI2->getParent())
1123           return VLOperands::ScoreFail;
1124 
1125         Optional<int> Dist = getPointersDiff(
1126             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1127             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1128         if (!Dist || *Dist == 0)
1129           return VLOperands::ScoreFail;
1130         // The distance is too large - still may be profitable to use masked
1131         // loads/gathers.
1132         if (std::abs(*Dist) > NumLanes / 2)
1133           return VLOperands::ScoreAltOpcodes;
1134         // This still will detect consecutive loads, but we might have "holes"
1135         // in some cases. It is ok for non-power-2 vectorization and may produce
1136         // better results. It should not affect current vectorization.
1137         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1138                            : VLOperands::ScoreReversedLoads;
1139       }
1140 
1141       auto *C1 = dyn_cast<Constant>(V1);
1142       auto *C2 = dyn_cast<Constant>(V2);
1143       if (C1 && C2)
1144         return VLOperands::ScoreConstants;
1145 
1146       // Extracts from consecutive indexes of the same vector better score as
1147       // the extracts could be optimized away.
1148       Value *EV1;
1149       ConstantInt *Ex1Idx;
1150       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1151         // Undefs are always profitable for extractelements.
1152         if (isa<UndefValue>(V2))
1153           return VLOperands::ScoreConsecutiveExtracts;
1154         Value *EV2 = nullptr;
1155         ConstantInt *Ex2Idx = nullptr;
1156         if (match(V2,
1157                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1158                                                          m_Undef())))) {
1159           // Undefs are always profitable for extractelements.
1160           if (!Ex2Idx)
1161             return VLOperands::ScoreConsecutiveExtracts;
1162           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1163             return VLOperands::ScoreConsecutiveExtracts;
1164           if (EV2 == EV1) {
1165             int Idx1 = Ex1Idx->getZExtValue();
1166             int Idx2 = Ex2Idx->getZExtValue();
1167             int Dist = Idx2 - Idx1;
1168             // The distance is too large - still may be profitable to use
1169             // shuffles.
1170             if (std::abs(Dist) == 0)
1171               return VLOperands::ScoreSplat;
1172             if (std::abs(Dist) > NumLanes / 2)
1173               return VLOperands::ScoreSameOpcode;
1174             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1175                               : VLOperands::ScoreReversedExtracts;
1176           }
1177           return VLOperands::ScoreAltOpcodes;
1178         }
1179         return VLOperands::ScoreFail;
1180       }
1181 
1182       auto *I1 = dyn_cast<Instruction>(V1);
1183       auto *I2 = dyn_cast<Instruction>(V2);
1184       if (I1 && I2) {
1185         if (I1->getParent() != I2->getParent())
1186           return VLOperands::ScoreFail;
1187         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1188         Ops.push_back(I1);
1189         Ops.push_back(I2);
1190         InstructionsState S = getSameOpcode(Ops);
1191         // Note: Only consider instructions with <= 2 operands to avoid
1192         // complexity explosion.
1193         if (S.getOpcode() &&
1194             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1195              !S.isAltShuffle()) &&
1196             all_of(Ops, [&S](Value *V) {
1197               return cast<Instruction>(V)->getNumOperands() ==
1198                      S.MainOp->getNumOperands();
1199             }))
1200           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1201                                   : VLOperands::ScoreSameOpcode;
1202       }
1203 
1204       if (isa<UndefValue>(V2))
1205         return VLOperands::ScoreUndef;
1206 
1207       return VLOperands::ScoreFail;
1208     }
1209 
1210     /// \param Lane lane of the operands under analysis.
1211     /// \param OpIdx operand index in \p Lane lane we're looking the best
1212     /// candidate for.
1213     /// \param Idx operand index of the current candidate value.
1214     /// \returns The additional score due to possible broadcasting of the
1215     /// elements in the lane. It is more profitable to have power-of-2 unique
1216     /// elements in the lane, it will be vectorized with higher probability
1217     /// after removing duplicates. Currently the SLP vectorizer supports only
1218     /// vectorization of the power-of-2 number of unique scalars.
1219     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1220       Value *IdxLaneV = getData(Idx, Lane).V;
1221       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1222         return 0;
1223       SmallPtrSet<Value *, 4> Uniques;
1224       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1225         if (Ln == Lane)
1226           continue;
1227         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1228         if (!isa<Instruction>(OpIdxLnV))
1229           return 0;
1230         Uniques.insert(OpIdxLnV);
1231       }
1232       int UniquesCount = Uniques.size();
1233       int UniquesCntWithIdxLaneV =
1234           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1235       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1236       int UniquesCntWithOpIdxLaneV =
1237           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1238       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1239         return 0;
1240       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1241               UniquesCntWithOpIdxLaneV) -
1242              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1243     }
1244 
1245     /// \param Lane lane of the operands under analysis.
1246     /// \param OpIdx operand index in \p Lane lane we're looking the best
1247     /// candidate for.
1248     /// \param Idx operand index of the current candidate value.
1249     /// \returns The additional score for the scalar which users are all
1250     /// vectorized.
1251     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1252       Value *IdxLaneV = getData(Idx, Lane).V;
1253       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1254       // Do not care about number of uses for vector-like instructions
1255       // (extractelement/extractvalue with constant indices), they are extracts
1256       // themselves and already externally used. Vectorization of such
1257       // instructions does not add extra extractelement instruction, just may
1258       // remove it.
1259       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1260           isVectorLikeInstWithConstOps(OpIdxLaneV))
1261         return VLOperands::ScoreAllUserVectorized;
1262       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1263       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1264         return 0;
1265       return R.areAllUsersVectorized(IdxLaneI, None)
1266                  ? VLOperands::ScoreAllUserVectorized
1267                  : 0;
1268     }
1269 
1270     /// Go through the operands of \p LHS and \p RHS recursively until \p
1271     /// MaxLevel, and return the cummulative score. For example:
1272     /// \verbatim
1273     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1274     ///     \ /         \ /         \ /        \ /
1275     ///      +           +           +          +
1276     ///     G1          G2          G3         G4
1277     /// \endverbatim
1278     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1279     /// each level recursively, accumulating the score. It starts from matching
1280     /// the additions at level 0, then moves on to the loads (level 1). The
1281     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1282     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1283     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1284     /// Please note that the order of the operands does not matter, as we
1285     /// evaluate the score of all profitable combinations of operands. In
1286     /// other words the score of G1 and G4 is the same as G1 and G2. This
1287     /// heuristic is based on ideas described in:
1288     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1289     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1290     ///   Luís F. W. Góes
1291     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1292                            ArrayRef<Value *> MainAltOps) {
1293 
1294       // Get the shallow score of V1 and V2.
1295       int ShallowScoreAtThisLevel =
1296           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1297 
1298       // If reached MaxLevel,
1299       //  or if V1 and V2 are not instructions,
1300       //  or if they are SPLAT,
1301       //  or if they are not consecutive,
1302       //  or if profitable to vectorize loads or extractelements, early return
1303       //  the current cost.
1304       auto *I1 = dyn_cast<Instruction>(LHS);
1305       auto *I2 = dyn_cast<Instruction>(RHS);
1306       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1307           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1308           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1309             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1310             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1311            ShallowScoreAtThisLevel))
1312         return ShallowScoreAtThisLevel;
1313       assert(I1 && I2 && "Should have early exited.");
1314 
1315       // Contains the I2 operand indexes that got matched with I1 operands.
1316       SmallSet<unsigned, 4> Op2Used;
1317 
1318       // Recursion towards the operands of I1 and I2. We are trying all possible
1319       // operand pairs, and keeping track of the best score.
1320       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1321            OpIdx1 != NumOperands1; ++OpIdx1) {
1322         // Try to pair op1I with the best operand of I2.
1323         int MaxTmpScore = 0;
1324         unsigned MaxOpIdx2 = 0;
1325         bool FoundBest = false;
1326         // If I2 is commutative try all combinations.
1327         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1328         unsigned ToIdx = isCommutative(I2)
1329                              ? I2->getNumOperands()
1330                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1331         assert(FromIdx <= ToIdx && "Bad index");
1332         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1333           // Skip operands already paired with OpIdx1.
1334           if (Op2Used.count(OpIdx2))
1335             continue;
1336           // Recursively calculate the cost at each level
1337           int TmpScore =
1338               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1339                                  CurrLevel + 1, MaxLevel, None);
1340           // Look for the best score.
1341           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1342             MaxTmpScore = TmpScore;
1343             MaxOpIdx2 = OpIdx2;
1344             FoundBest = true;
1345           }
1346         }
1347         if (FoundBest) {
1348           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1349           Op2Used.insert(MaxOpIdx2);
1350           ShallowScoreAtThisLevel += MaxTmpScore;
1351         }
1352       }
1353       return ShallowScoreAtThisLevel;
1354     }
1355 
1356     /// Score scaling factor for fully compatible instructions but with
1357     /// different number of external uses. Allows better selection of the
1358     /// instructions with less external uses.
1359     static const int ScoreScaleFactor = 10;
1360 
1361     /// \Returns the look-ahead score, which tells us how much the sub-trees
1362     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1363     /// score. This helps break ties in an informed way when we cannot decide on
1364     /// the order of the operands by just considering the immediate
1365     /// predecessors.
1366     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1367                           int Lane, unsigned OpIdx, unsigned Idx,
1368                           bool &IsUsed) {
1369       int Score =
1370           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1371       if (Score) {
1372         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1373         if (Score <= -SplatScore) {
1374           // Set the minimum score for splat-like sequence to avoid setting
1375           // failed state.
1376           Score = 1;
1377         } else {
1378           Score += SplatScore;
1379           // Scale score to see the difference between different operands
1380           // and similar operands but all vectorized/not all vectorized
1381           // uses. It does not affect actual selection of the best
1382           // compatible operand in general, just allows to select the
1383           // operand with all vectorized uses.
1384           Score *= ScoreScaleFactor;
1385           Score += getExternalUseScore(Lane, OpIdx, Idx);
1386           IsUsed = true;
1387         }
1388       }
1389       return Score;
1390     }
1391 
1392     /// Best defined scores per lanes between the passes. Used to choose the
1393     /// best operand (with the highest score) between the passes.
1394     /// The key - {Operand Index, Lane}.
1395     /// The value - the best score between the passes for the lane and the
1396     /// operand.
1397     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1398         BestScoresPerLanes;
1399 
1400     // Search all operands in Ops[*][Lane] for the one that matches best
1401     // Ops[OpIdx][LastLane] and return its opreand index.
1402     // If no good match can be found, return None.
1403     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1404                                       ArrayRef<ReorderingMode> ReorderingModes,
1405                                       ArrayRef<Value *> MainAltOps) {
1406       unsigned NumOperands = getNumOperands();
1407 
1408       // The operand of the previous lane at OpIdx.
1409       Value *OpLastLane = getData(OpIdx, LastLane).V;
1410 
1411       // Our strategy mode for OpIdx.
1412       ReorderingMode RMode = ReorderingModes[OpIdx];
1413       if (RMode == ReorderingMode::Failed)
1414         return None;
1415 
1416       // The linearized opcode of the operand at OpIdx, Lane.
1417       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1418 
1419       // The best operand index and its score.
1420       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1421       // are using the score to differentiate between the two.
1422       struct BestOpData {
1423         Optional<unsigned> Idx = None;
1424         unsigned Score = 0;
1425       } BestOp;
1426       BestOp.Score =
1427           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1428               .first->second;
1429 
1430       // Track if the operand must be marked as used. If the operand is set to
1431       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1432       // want to reestimate the operands again on the following iterations).
1433       bool IsUsed =
1434           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1435       // Iterate through all unused operands and look for the best.
1436       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1437         // Get the operand at Idx and Lane.
1438         OperandData &OpData = getData(Idx, Lane);
1439         Value *Op = OpData.V;
1440         bool OpAPO = OpData.APO;
1441 
1442         // Skip already selected operands.
1443         if (OpData.IsUsed)
1444           continue;
1445 
1446         // Skip if we are trying to move the operand to a position with a
1447         // different opcode in the linearized tree form. This would break the
1448         // semantics.
1449         if (OpAPO != OpIdxAPO)
1450           continue;
1451 
1452         // Look for an operand that matches the current mode.
1453         switch (RMode) {
1454         case ReorderingMode::Load:
1455         case ReorderingMode::Constant:
1456         case ReorderingMode::Opcode: {
1457           bool LeftToRight = Lane > LastLane;
1458           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1459           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1460           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1461                                         OpIdx, Idx, IsUsed);
1462           if (Score > static_cast<int>(BestOp.Score)) {
1463             BestOp.Idx = Idx;
1464             BestOp.Score = Score;
1465             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1466           }
1467           break;
1468         }
1469         case ReorderingMode::Splat:
1470           if (Op == OpLastLane)
1471             BestOp.Idx = Idx;
1472           break;
1473         case ReorderingMode::Failed:
1474           llvm_unreachable("Not expected Failed reordering mode.");
1475         }
1476       }
1477 
1478       if (BestOp.Idx) {
1479         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1480         return BestOp.Idx;
1481       }
1482       // If we could not find a good match return None.
1483       return None;
1484     }
1485 
1486     /// Helper for reorderOperandVecs.
1487     /// \returns the lane that we should start reordering from. This is the one
1488     /// which has the least number of operands that can freely move about or
1489     /// less profitable because it already has the most optimal set of operands.
1490     unsigned getBestLaneToStartReordering() const {
1491       unsigned Min = UINT_MAX;
1492       unsigned SameOpNumber = 0;
1493       // std::pair<unsigned, unsigned> is used to implement a simple voting
1494       // algorithm and choose the lane with the least number of operands that
1495       // can freely move about or less profitable because it already has the
1496       // most optimal set of operands. The first unsigned is a counter for
1497       // voting, the second unsigned is the counter of lanes with instructions
1498       // with same/alternate opcodes and same parent basic block.
1499       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1500       // Try to be closer to the original results, if we have multiple lanes
1501       // with same cost. If 2 lanes have the same cost, use the one with the
1502       // lowest index.
1503       for (int I = getNumLanes(); I > 0; --I) {
1504         unsigned Lane = I - 1;
1505         OperandsOrderData NumFreeOpsHash =
1506             getMaxNumOperandsThatCanBeReordered(Lane);
1507         // Compare the number of operands that can move and choose the one with
1508         // the least number.
1509         if (NumFreeOpsHash.NumOfAPOs < Min) {
1510           Min = NumFreeOpsHash.NumOfAPOs;
1511           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1512           HashMap.clear();
1513           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1514         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1515                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1516           // Select the most optimal lane in terms of number of operands that
1517           // should be moved around.
1518           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1519           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1520         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1521                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1522           auto It = HashMap.find(NumFreeOpsHash.Hash);
1523           if (It == HashMap.end())
1524             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1525           else
1526             ++It->second.first;
1527         }
1528       }
1529       // Select the lane with the minimum counter.
1530       unsigned BestLane = 0;
1531       unsigned CntMin = UINT_MAX;
1532       for (const auto &Data : reverse(HashMap)) {
1533         if (Data.second.first < CntMin) {
1534           CntMin = Data.second.first;
1535           BestLane = Data.second.second;
1536         }
1537       }
1538       return BestLane;
1539     }
1540 
1541     /// Data structure that helps to reorder operands.
1542     struct OperandsOrderData {
1543       /// The best number of operands with the same APOs, which can be
1544       /// reordered.
1545       unsigned NumOfAPOs = UINT_MAX;
1546       /// Number of operands with the same/alternate instruction opcode and
1547       /// parent.
1548       unsigned NumOpsWithSameOpcodeParent = 0;
1549       /// Hash for the actual operands ordering.
1550       /// Used to count operands, actually their position id and opcode
1551       /// value. It is used in the voting mechanism to find the lane with the
1552       /// least number of operands that can freely move about or less profitable
1553       /// because it already has the most optimal set of operands. Can be
1554       /// replaced with SmallVector<unsigned> instead but hash code is faster
1555       /// and requires less memory.
1556       unsigned Hash = 0;
1557     };
1558     /// \returns the maximum number of operands that are allowed to be reordered
1559     /// for \p Lane and the number of compatible instructions(with the same
1560     /// parent/opcode). This is used as a heuristic for selecting the first lane
1561     /// to start operand reordering.
1562     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1563       unsigned CntTrue = 0;
1564       unsigned NumOperands = getNumOperands();
1565       // Operands with the same APO can be reordered. We therefore need to count
1566       // how many of them we have for each APO, like this: Cnt[APO] = x.
1567       // Since we only have two APOs, namely true and false, we can avoid using
1568       // a map. Instead we can simply count the number of operands that
1569       // correspond to one of them (in this case the 'true' APO), and calculate
1570       // the other by subtracting it from the total number of operands.
1571       // Operands with the same instruction opcode and parent are more
1572       // profitable since we don't need to move them in many cases, with a high
1573       // probability such lane already can be vectorized effectively.
1574       bool AllUndefs = true;
1575       unsigned NumOpsWithSameOpcodeParent = 0;
1576       Instruction *OpcodeI = nullptr;
1577       BasicBlock *Parent = nullptr;
1578       unsigned Hash = 0;
1579       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1580         const OperandData &OpData = getData(OpIdx, Lane);
1581         if (OpData.APO)
1582           ++CntTrue;
1583         // Use Boyer-Moore majority voting for finding the majority opcode and
1584         // the number of times it occurs.
1585         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1586           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1587               I->getParent() != Parent) {
1588             if (NumOpsWithSameOpcodeParent == 0) {
1589               NumOpsWithSameOpcodeParent = 1;
1590               OpcodeI = I;
1591               Parent = I->getParent();
1592             } else {
1593               --NumOpsWithSameOpcodeParent;
1594             }
1595           } else {
1596             ++NumOpsWithSameOpcodeParent;
1597           }
1598         }
1599         Hash = hash_combine(
1600             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1601         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1602       }
1603       if (AllUndefs)
1604         return {};
1605       OperandsOrderData Data;
1606       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1607       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1608       Data.Hash = Hash;
1609       return Data;
1610     }
1611 
1612     /// Go through the instructions in VL and append their operands.
1613     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1614       assert(!VL.empty() && "Bad VL");
1615       assert((empty() || VL.size() == getNumLanes()) &&
1616              "Expected same number of lanes");
1617       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1618       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1619       OpsVec.resize(NumOperands);
1620       unsigned NumLanes = VL.size();
1621       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1622         OpsVec[OpIdx].resize(NumLanes);
1623         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1624           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1625           // Our tree has just 3 nodes: the root and two operands.
1626           // It is therefore trivial to get the APO. We only need to check the
1627           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1628           // RHS operand. The LHS operand of both add and sub is never attached
1629           // to an inversese operation in the linearized form, therefore its APO
1630           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1631 
1632           // Since operand reordering is performed on groups of commutative
1633           // operations or alternating sequences (e.g., +, -), we can safely
1634           // tell the inverse operations by checking commutativity.
1635           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1636           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1637           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1638                                  APO, false};
1639         }
1640       }
1641     }
1642 
1643     /// \returns the number of operands.
1644     unsigned getNumOperands() const { return OpsVec.size(); }
1645 
1646     /// \returns the number of lanes.
1647     unsigned getNumLanes() const { return OpsVec[0].size(); }
1648 
1649     /// \returns the operand value at \p OpIdx and \p Lane.
1650     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1651       return getData(OpIdx, Lane).V;
1652     }
1653 
1654     /// \returns true if the data structure is empty.
1655     bool empty() const { return OpsVec.empty(); }
1656 
1657     /// Clears the data.
1658     void clear() { OpsVec.clear(); }
1659 
1660     /// \Returns true if there are enough operands identical to \p Op to fill
1661     /// the whole vector.
1662     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1663     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1664       bool OpAPO = getData(OpIdx, Lane).APO;
1665       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1666         if (Ln == Lane)
1667           continue;
1668         // This is set to true if we found a candidate for broadcast at Lane.
1669         bool FoundCandidate = false;
1670         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1671           OperandData &Data = getData(OpI, Ln);
1672           if (Data.APO != OpAPO || Data.IsUsed)
1673             continue;
1674           if (Data.V == Op) {
1675             FoundCandidate = true;
1676             Data.IsUsed = true;
1677             break;
1678           }
1679         }
1680         if (!FoundCandidate)
1681           return false;
1682       }
1683       return true;
1684     }
1685 
1686   public:
1687     /// Initialize with all the operands of the instruction vector \p RootVL.
1688     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1689                ScalarEvolution &SE, const BoUpSLP &R)
1690         : DL(DL), SE(SE), R(R) {
1691       // Append all the operands of RootVL.
1692       appendOperandsOfVL(RootVL);
1693     }
1694 
1695     /// \Returns a value vector with the operands across all lanes for the
1696     /// opearnd at \p OpIdx.
1697     ValueList getVL(unsigned OpIdx) const {
1698       ValueList OpVL(OpsVec[OpIdx].size());
1699       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1700              "Expected same num of lanes across all operands");
1701       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1702         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1703       return OpVL;
1704     }
1705 
1706     // Performs operand reordering for 2 or more operands.
1707     // The original operands are in OrigOps[OpIdx][Lane].
1708     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1709     void reorder() {
1710       unsigned NumOperands = getNumOperands();
1711       unsigned NumLanes = getNumLanes();
1712       // Each operand has its own mode. We are using this mode to help us select
1713       // the instructions for each lane, so that they match best with the ones
1714       // we have selected so far.
1715       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1716 
1717       // This is a greedy single-pass algorithm. We are going over each lane
1718       // once and deciding on the best order right away with no back-tracking.
1719       // However, in order to increase its effectiveness, we start with the lane
1720       // that has operands that can move the least. For example, given the
1721       // following lanes:
1722       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1723       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1724       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1725       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1726       // we will start at Lane 1, since the operands of the subtraction cannot
1727       // be reordered. Then we will visit the rest of the lanes in a circular
1728       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1729 
1730       // Find the first lane that we will start our search from.
1731       unsigned FirstLane = getBestLaneToStartReordering();
1732 
1733       // Initialize the modes.
1734       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1735         Value *OpLane0 = getValue(OpIdx, FirstLane);
1736         // Keep track if we have instructions with all the same opcode on one
1737         // side.
1738         if (isa<LoadInst>(OpLane0))
1739           ReorderingModes[OpIdx] = ReorderingMode::Load;
1740         else if (isa<Instruction>(OpLane0)) {
1741           // Check if OpLane0 should be broadcast.
1742           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1743             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1744           else
1745             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1746         }
1747         else if (isa<Constant>(OpLane0))
1748           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1749         else if (isa<Argument>(OpLane0))
1750           // Our best hope is a Splat. It may save some cost in some cases.
1751           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1752         else
1753           // NOTE: This should be unreachable.
1754           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1755       }
1756 
1757       // Check that we don't have same operands. No need to reorder if operands
1758       // are just perfect diamond or shuffled diamond match. Do not do it only
1759       // for possible broadcasts or non-power of 2 number of scalars (just for
1760       // now).
1761       auto &&SkipReordering = [this]() {
1762         SmallPtrSet<Value *, 4> UniqueValues;
1763         ArrayRef<OperandData> Op0 = OpsVec.front();
1764         for (const OperandData &Data : Op0)
1765           UniqueValues.insert(Data.V);
1766         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1767           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1768                 return !UniqueValues.contains(Data.V);
1769               }))
1770             return false;
1771         }
1772         // TODO: Check if we can remove a check for non-power-2 number of
1773         // scalars after full support of non-power-2 vectorization.
1774         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1775       };
1776 
1777       // If the initial strategy fails for any of the operand indexes, then we
1778       // perform reordering again in a second pass. This helps avoid assigning
1779       // high priority to the failed strategy, and should improve reordering for
1780       // the non-failed operand indexes.
1781       for (int Pass = 0; Pass != 2; ++Pass) {
1782         // Check if no need to reorder operands since they're are perfect or
1783         // shuffled diamond match.
1784         // Need to to do it to avoid extra external use cost counting for
1785         // shuffled matches, which may cause regressions.
1786         if (SkipReordering())
1787           break;
1788         // Skip the second pass if the first pass did not fail.
1789         bool StrategyFailed = false;
1790         // Mark all operand data as free to use.
1791         clearUsed();
1792         // We keep the original operand order for the FirstLane, so reorder the
1793         // rest of the lanes. We are visiting the nodes in a circular fashion,
1794         // using FirstLane as the center point and increasing the radius
1795         // distance.
1796         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1797         for (unsigned I = 0; I < NumOperands; ++I)
1798           MainAltOps[I].push_back(getData(I, FirstLane).V);
1799 
1800         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1801           // Visit the lane on the right and then the lane on the left.
1802           for (int Direction : {+1, -1}) {
1803             int Lane = FirstLane + Direction * Distance;
1804             if (Lane < 0 || Lane >= (int)NumLanes)
1805               continue;
1806             int LastLane = Lane - Direction;
1807             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1808                    "Out of bounds");
1809             // Look for a good match for each operand.
1810             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1811               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1812               Optional<unsigned> BestIdx = getBestOperand(
1813                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1814               // By not selecting a value, we allow the operands that follow to
1815               // select a better matching value. We will get a non-null value in
1816               // the next run of getBestOperand().
1817               if (BestIdx) {
1818                 // Swap the current operand with the one returned by
1819                 // getBestOperand().
1820                 swap(OpIdx, BestIdx.getValue(), Lane);
1821               } else {
1822                 // We failed to find a best operand, set mode to 'Failed'.
1823                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1824                 // Enable the second pass.
1825                 StrategyFailed = true;
1826               }
1827               // Try to get the alternate opcode and follow it during analysis.
1828               if (MainAltOps[OpIdx].size() != 2) {
1829                 OperandData &AltOp = getData(OpIdx, Lane);
1830                 InstructionsState OpS =
1831                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1832                 if (OpS.getOpcode() && OpS.isAltShuffle())
1833                   MainAltOps[OpIdx].push_back(AltOp.V);
1834               }
1835             }
1836           }
1837         }
1838         // Skip second pass if the strategy did not fail.
1839         if (!StrategyFailed)
1840           break;
1841       }
1842     }
1843 
1844 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1845     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1846       switch (RMode) {
1847       case ReorderingMode::Load:
1848         return "Load";
1849       case ReorderingMode::Opcode:
1850         return "Opcode";
1851       case ReorderingMode::Constant:
1852         return "Constant";
1853       case ReorderingMode::Splat:
1854         return "Splat";
1855       case ReorderingMode::Failed:
1856         return "Failed";
1857       }
1858       llvm_unreachable("Unimplemented Reordering Type");
1859     }
1860 
1861     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1862                                                    raw_ostream &OS) {
1863       return OS << getModeStr(RMode);
1864     }
1865 
1866     /// Debug print.
1867     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1868       printMode(RMode, dbgs());
1869     }
1870 
1871     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1872       return printMode(RMode, OS);
1873     }
1874 
1875     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1876       const unsigned Indent = 2;
1877       unsigned Cnt = 0;
1878       for (const OperandDataVec &OpDataVec : OpsVec) {
1879         OS << "Operand " << Cnt++ << "\n";
1880         for (const OperandData &OpData : OpDataVec) {
1881           OS.indent(Indent) << "{";
1882           if (Value *V = OpData.V)
1883             OS << *V;
1884           else
1885             OS << "null";
1886           OS << ", APO:" << OpData.APO << "}\n";
1887         }
1888         OS << "\n";
1889       }
1890       return OS;
1891     }
1892 
1893     /// Debug print.
1894     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1895 #endif
1896   };
1897 
1898   /// Checks if the instruction is marked for deletion.
1899   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1900 
1901   /// Marks values operands for later deletion by replacing them with Undefs.
1902   void eraseInstructions(ArrayRef<Value *> AV);
1903 
1904   ~BoUpSLP();
1905 
1906 private:
1907   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1908   /// reordering (i.e. the operands can be reordered because they have only one
1909   /// user and reordarable).
1910   /// \param NonVectorized List of all gather nodes that require reordering
1911   /// (e.g., gather of extractlements or partially vectorizable loads).
1912   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1913   /// reordering, subset of \p NonVectorized.
1914   bool
1915   canReorderOperands(TreeEntry *UserTE,
1916                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1917                      ArrayRef<TreeEntry *> ReorderableGathers,
1918                      SmallVectorImpl<TreeEntry *> &GatherOps);
1919 
1920   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1921   /// if any. If it is not vectorized (gather node), returns nullptr.
1922   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1923     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1924     TreeEntry *TE = nullptr;
1925     const auto *It = find_if(VL, [this, &TE](Value *V) {
1926       TE = getTreeEntry(V);
1927       return TE;
1928     });
1929     if (It != VL.end() && TE->isSame(VL))
1930       return TE;
1931     return nullptr;
1932   }
1933 
1934   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1935   /// if any. If it is not vectorized (gather node), returns nullptr.
1936   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
1937                                         unsigned OpIdx) const {
1938     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
1939         const_cast<TreeEntry *>(UserTE), OpIdx);
1940   }
1941 
1942   /// Checks if all users of \p I are the part of the vectorization tree.
1943   bool areAllUsersVectorized(Instruction *I,
1944                              ArrayRef<Value *> VectorizedVals) const;
1945 
1946   /// \returns the cost of the vectorizable entry.
1947   InstructionCost getEntryCost(const TreeEntry *E,
1948                                ArrayRef<Value *> VectorizedVals);
1949 
1950   /// This is the recursive part of buildTree.
1951   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1952                      const EdgeInfo &EI);
1953 
1954   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1955   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1956   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1957   /// returns false, setting \p CurrentOrder to either an empty vector or a
1958   /// non-identity permutation that allows to reuse extract instructions.
1959   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1960                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1961 
1962   /// Vectorize a single entry in the tree.
1963   Value *vectorizeTree(TreeEntry *E);
1964 
1965   /// Vectorize a single entry in the tree, starting in \p VL.
1966   Value *vectorizeTree(ArrayRef<Value *> VL);
1967 
1968   /// Create a new vector from a list of scalar values.  Produces a sequence
1969   /// which exploits values reused across lanes, and arranges the inserts
1970   /// for ease of later optimization.
1971   Value *createBuildVector(ArrayRef<Value *> VL);
1972 
1973   /// \returns the scalarization cost for this type. Scalarization in this
1974   /// context means the creation of vectors from a group of scalars. If \p
1975   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
1976   /// vector elements.
1977   InstructionCost getGatherCost(FixedVectorType *Ty,
1978                                 const APInt &ShuffledIndices,
1979                                 bool NeedToShuffle) const;
1980 
1981   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1982   /// tree entries.
1983   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1984   /// previous tree entries. \p Mask is filled with the shuffle mask.
1985   Optional<TargetTransformInfo::ShuffleKind>
1986   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1987                         SmallVectorImpl<const TreeEntry *> &Entries);
1988 
1989   /// \returns the scalarization cost for this list of values. Assuming that
1990   /// this subtree gets vectorized, we may need to extract the values from the
1991   /// roots. This method calculates the cost of extracting the values.
1992   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1993 
1994   /// Set the Builder insert point to one after the last instruction in
1995   /// the bundle
1996   void setInsertPointAfterBundle(const TreeEntry *E);
1997 
1998   /// \returns a vector from a collection of scalars in \p VL.
1999   Value *gather(ArrayRef<Value *> VL);
2000 
2001   /// \returns whether the VectorizableTree is fully vectorizable and will
2002   /// be beneficial even the tree height is tiny.
2003   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2004 
2005   /// Reorder commutative or alt operands to get better probability of
2006   /// generating vectorized code.
2007   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2008                                              SmallVectorImpl<Value *> &Left,
2009                                              SmallVectorImpl<Value *> &Right,
2010                                              const DataLayout &DL,
2011                                              ScalarEvolution &SE,
2012                                              const BoUpSLP &R);
2013   struct TreeEntry {
2014     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2015     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2016 
2017     /// \returns true if the scalars in VL are equal to this entry.
2018     bool isSame(ArrayRef<Value *> VL) const {
2019       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2020         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2021           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2022         return VL.size() == Mask.size() &&
2023                std::equal(VL.begin(), VL.end(), Mask.begin(),
2024                           [Scalars](Value *V, int Idx) {
2025                             return (isa<UndefValue>(V) &&
2026                                     Idx == UndefMaskElem) ||
2027                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2028                           });
2029       };
2030       if (!ReorderIndices.empty()) {
2031         // TODO: implement matching if the nodes are just reordered, still can
2032         // treat the vector as the same if the list of scalars matches VL
2033         // directly, without reordering.
2034         SmallVector<int> Mask;
2035         inversePermutation(ReorderIndices, Mask);
2036         if (VL.size() == Scalars.size())
2037           return IsSame(Scalars, Mask);
2038         if (VL.size() == ReuseShuffleIndices.size()) {
2039           ::addMask(Mask, ReuseShuffleIndices);
2040           return IsSame(Scalars, Mask);
2041         }
2042         return false;
2043       }
2044       return IsSame(Scalars, ReuseShuffleIndices);
2045     }
2046 
2047     /// \returns true if current entry has same operands as \p TE.
2048     bool hasEqualOperands(const TreeEntry &TE) const {
2049       if (TE.getNumOperands() != getNumOperands())
2050         return false;
2051       SmallBitVector Used(getNumOperands());
2052       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2053         unsigned PrevCount = Used.count();
2054         for (unsigned K = 0; K < E; ++K) {
2055           if (Used.test(K))
2056             continue;
2057           if (getOperand(K) == TE.getOperand(I)) {
2058             Used.set(K);
2059             break;
2060           }
2061         }
2062         // Check if we actually found the matching operand.
2063         if (PrevCount == Used.count())
2064           return false;
2065       }
2066       return true;
2067     }
2068 
2069     /// \return Final vectorization factor for the node. Defined by the total
2070     /// number of vectorized scalars, including those, used several times in the
2071     /// entry and counted in the \a ReuseShuffleIndices, if any.
2072     unsigned getVectorFactor() const {
2073       if (!ReuseShuffleIndices.empty())
2074         return ReuseShuffleIndices.size();
2075       return Scalars.size();
2076     };
2077 
2078     /// A vector of scalars.
2079     ValueList Scalars;
2080 
2081     /// The Scalars are vectorized into this value. It is initialized to Null.
2082     Value *VectorizedValue = nullptr;
2083 
2084     /// Do we need to gather this sequence or vectorize it
2085     /// (either with vector instruction or with scatter/gather
2086     /// intrinsics for store/load)?
2087     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2088     EntryState State;
2089 
2090     /// Does this sequence require some shuffling?
2091     SmallVector<int, 4> ReuseShuffleIndices;
2092 
2093     /// Does this entry require reordering?
2094     SmallVector<unsigned, 4> ReorderIndices;
2095 
2096     /// Points back to the VectorizableTree.
2097     ///
2098     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2099     /// to be a pointer and needs to be able to initialize the child iterator.
2100     /// Thus we need a reference back to the container to translate the indices
2101     /// to entries.
2102     VecTreeTy &Container;
2103 
2104     /// The TreeEntry index containing the user of this entry.  We can actually
2105     /// have multiple users so the data structure is not truly a tree.
2106     SmallVector<EdgeInfo, 1> UserTreeIndices;
2107 
2108     /// The index of this treeEntry in VectorizableTree.
2109     int Idx = -1;
2110 
2111   private:
2112     /// The operands of each instruction in each lane Operands[op_index][lane].
2113     /// Note: This helps avoid the replication of the code that performs the
2114     /// reordering of operands during buildTree_rec() and vectorizeTree().
2115     SmallVector<ValueList, 2> Operands;
2116 
2117     /// The main/alternate instruction.
2118     Instruction *MainOp = nullptr;
2119     Instruction *AltOp = nullptr;
2120 
2121   public:
2122     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2123     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2124       if (Operands.size() < OpIdx + 1)
2125         Operands.resize(OpIdx + 1);
2126       assert(Operands[OpIdx].empty() && "Already resized?");
2127       assert(OpVL.size() <= Scalars.size() &&
2128              "Number of operands is greater than the number of scalars.");
2129       Operands[OpIdx].resize(OpVL.size());
2130       copy(OpVL, Operands[OpIdx].begin());
2131     }
2132 
2133     /// Set the operands of this bundle in their original order.
2134     void setOperandsInOrder() {
2135       assert(Operands.empty() && "Already initialized?");
2136       auto *I0 = cast<Instruction>(Scalars[0]);
2137       Operands.resize(I0->getNumOperands());
2138       unsigned NumLanes = Scalars.size();
2139       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2140            OpIdx != NumOperands; ++OpIdx) {
2141         Operands[OpIdx].resize(NumLanes);
2142         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2143           auto *I = cast<Instruction>(Scalars[Lane]);
2144           assert(I->getNumOperands() == NumOperands &&
2145                  "Expected same number of operands");
2146           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2147         }
2148       }
2149     }
2150 
2151     /// Reorders operands of the node to the given mask \p Mask.
2152     void reorderOperands(ArrayRef<int> Mask) {
2153       for (ValueList &Operand : Operands)
2154         reorderScalars(Operand, Mask);
2155     }
2156 
2157     /// \returns the \p OpIdx operand of this TreeEntry.
2158     ValueList &getOperand(unsigned OpIdx) {
2159       assert(OpIdx < Operands.size() && "Off bounds");
2160       return Operands[OpIdx];
2161     }
2162 
2163     /// \returns the \p OpIdx operand of this TreeEntry.
2164     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2165       assert(OpIdx < Operands.size() && "Off bounds");
2166       return Operands[OpIdx];
2167     }
2168 
2169     /// \returns the number of operands.
2170     unsigned getNumOperands() const { return Operands.size(); }
2171 
2172     /// \return the single \p OpIdx operand.
2173     Value *getSingleOperand(unsigned OpIdx) const {
2174       assert(OpIdx < Operands.size() && "Off bounds");
2175       assert(!Operands[OpIdx].empty() && "No operand available");
2176       return Operands[OpIdx][0];
2177     }
2178 
2179     /// Some of the instructions in the list have alternate opcodes.
2180     bool isAltShuffle() const { return MainOp != AltOp; }
2181 
2182     bool isOpcodeOrAlt(Instruction *I) const {
2183       unsigned CheckedOpcode = I->getOpcode();
2184       return (getOpcode() == CheckedOpcode ||
2185               getAltOpcode() == CheckedOpcode);
2186     }
2187 
2188     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2189     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2190     /// \p OpValue.
2191     Value *isOneOf(Value *Op) const {
2192       auto *I = dyn_cast<Instruction>(Op);
2193       if (I && isOpcodeOrAlt(I))
2194         return Op;
2195       return MainOp;
2196     }
2197 
2198     void setOperations(const InstructionsState &S) {
2199       MainOp = S.MainOp;
2200       AltOp = S.AltOp;
2201     }
2202 
2203     Instruction *getMainOp() const {
2204       return MainOp;
2205     }
2206 
2207     Instruction *getAltOp() const {
2208       return AltOp;
2209     }
2210 
2211     /// The main/alternate opcodes for the list of instructions.
2212     unsigned getOpcode() const {
2213       return MainOp ? MainOp->getOpcode() : 0;
2214     }
2215 
2216     unsigned getAltOpcode() const {
2217       return AltOp ? AltOp->getOpcode() : 0;
2218     }
2219 
2220     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2221     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2222     int findLaneForValue(Value *V) const {
2223       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2224       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2225       if (!ReorderIndices.empty())
2226         FoundLane = ReorderIndices[FoundLane];
2227       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2228       if (!ReuseShuffleIndices.empty()) {
2229         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2230                                   find(ReuseShuffleIndices, FoundLane));
2231       }
2232       return FoundLane;
2233     }
2234 
2235 #ifndef NDEBUG
2236     /// Debug printer.
2237     LLVM_DUMP_METHOD void dump() const {
2238       dbgs() << Idx << ".\n";
2239       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2240         dbgs() << "Operand " << OpI << ":\n";
2241         for (const Value *V : Operands[OpI])
2242           dbgs().indent(2) << *V << "\n";
2243       }
2244       dbgs() << "Scalars: \n";
2245       for (Value *V : Scalars)
2246         dbgs().indent(2) << *V << "\n";
2247       dbgs() << "State: ";
2248       switch (State) {
2249       case Vectorize:
2250         dbgs() << "Vectorize\n";
2251         break;
2252       case ScatterVectorize:
2253         dbgs() << "ScatterVectorize\n";
2254         break;
2255       case NeedToGather:
2256         dbgs() << "NeedToGather\n";
2257         break;
2258       }
2259       dbgs() << "MainOp: ";
2260       if (MainOp)
2261         dbgs() << *MainOp << "\n";
2262       else
2263         dbgs() << "NULL\n";
2264       dbgs() << "AltOp: ";
2265       if (AltOp)
2266         dbgs() << *AltOp << "\n";
2267       else
2268         dbgs() << "NULL\n";
2269       dbgs() << "VectorizedValue: ";
2270       if (VectorizedValue)
2271         dbgs() << *VectorizedValue << "\n";
2272       else
2273         dbgs() << "NULL\n";
2274       dbgs() << "ReuseShuffleIndices: ";
2275       if (ReuseShuffleIndices.empty())
2276         dbgs() << "Empty";
2277       else
2278         for (int ReuseIdx : ReuseShuffleIndices)
2279           dbgs() << ReuseIdx << ", ";
2280       dbgs() << "\n";
2281       dbgs() << "ReorderIndices: ";
2282       for (unsigned ReorderIdx : ReorderIndices)
2283         dbgs() << ReorderIdx << ", ";
2284       dbgs() << "\n";
2285       dbgs() << "UserTreeIndices: ";
2286       for (const auto &EInfo : UserTreeIndices)
2287         dbgs() << EInfo << ", ";
2288       dbgs() << "\n";
2289     }
2290 #endif
2291   };
2292 
2293 #ifndef NDEBUG
2294   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2295                      InstructionCost VecCost,
2296                      InstructionCost ScalarCost) const {
2297     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2298     dbgs() << "SLP: Costs:\n";
2299     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2300     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2301     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2302     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2303                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2304   }
2305 #endif
2306 
2307   /// Create a new VectorizableTree entry.
2308   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2309                           const InstructionsState &S,
2310                           const EdgeInfo &UserTreeIdx,
2311                           ArrayRef<int> ReuseShuffleIndices = None,
2312                           ArrayRef<unsigned> ReorderIndices = None) {
2313     TreeEntry::EntryState EntryState =
2314         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2315     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2316                         ReuseShuffleIndices, ReorderIndices);
2317   }
2318 
2319   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2320                           TreeEntry::EntryState EntryState,
2321                           Optional<ScheduleData *> Bundle,
2322                           const InstructionsState &S,
2323                           const EdgeInfo &UserTreeIdx,
2324                           ArrayRef<int> ReuseShuffleIndices = None,
2325                           ArrayRef<unsigned> ReorderIndices = None) {
2326     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2327             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2328            "Need to vectorize gather entry?");
2329     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2330     TreeEntry *Last = VectorizableTree.back().get();
2331     Last->Idx = VectorizableTree.size() - 1;
2332     Last->State = EntryState;
2333     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2334                                      ReuseShuffleIndices.end());
2335     if (ReorderIndices.empty()) {
2336       Last->Scalars.assign(VL.begin(), VL.end());
2337       Last->setOperations(S);
2338     } else {
2339       // Reorder scalars and build final mask.
2340       Last->Scalars.assign(VL.size(), nullptr);
2341       transform(ReorderIndices, Last->Scalars.begin(),
2342                 [VL](unsigned Idx) -> Value * {
2343                   if (Idx >= VL.size())
2344                     return UndefValue::get(VL.front()->getType());
2345                   return VL[Idx];
2346                 });
2347       InstructionsState S = getSameOpcode(Last->Scalars);
2348       Last->setOperations(S);
2349       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2350     }
2351     if (Last->State != TreeEntry::NeedToGather) {
2352       for (Value *V : VL) {
2353         assert(!getTreeEntry(V) && "Scalar already in tree!");
2354         ScalarToTreeEntry[V] = Last;
2355       }
2356       // Update the scheduler bundle to point to this TreeEntry.
2357       unsigned Lane = 0;
2358       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
2359            BundleMember = BundleMember->NextInBundle) {
2360         BundleMember->TE = Last;
2361         BundleMember->Lane = Lane;
2362         ++Lane;
2363       }
2364       assert((!Bundle.getValue() || Lane == VL.size()) &&
2365              "Bundle and VL out of sync");
2366     } else {
2367       MustGather.insert(VL.begin(), VL.end());
2368     }
2369 
2370     if (UserTreeIdx.UserTE)
2371       Last->UserTreeIndices.push_back(UserTreeIdx);
2372 
2373     return Last;
2374   }
2375 
2376   /// -- Vectorization State --
2377   /// Holds all of the tree entries.
2378   TreeEntry::VecTreeTy VectorizableTree;
2379 
2380 #ifndef NDEBUG
2381   /// Debug printer.
2382   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2383     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2384       VectorizableTree[Id]->dump();
2385       dbgs() << "\n";
2386     }
2387   }
2388 #endif
2389 
2390   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2391 
2392   const TreeEntry *getTreeEntry(Value *V) const {
2393     return ScalarToTreeEntry.lookup(V);
2394   }
2395 
2396   /// Maps a specific scalar to its tree entry.
2397   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2398 
2399   /// Maps a value to the proposed vectorizable size.
2400   SmallDenseMap<Value *, unsigned> InstrElementSize;
2401 
2402   /// A list of scalars that we found that we need to keep as scalars.
2403   ValueSet MustGather;
2404 
2405   /// This POD struct describes one external user in the vectorized tree.
2406   struct ExternalUser {
2407     ExternalUser(Value *S, llvm::User *U, int L)
2408         : Scalar(S), User(U), Lane(L) {}
2409 
2410     // Which scalar in our function.
2411     Value *Scalar;
2412 
2413     // Which user that uses the scalar.
2414     llvm::User *User;
2415 
2416     // Which lane does the scalar belong to.
2417     int Lane;
2418   };
2419   using UserList = SmallVector<ExternalUser, 16>;
2420 
2421   /// Checks if two instructions may access the same memory.
2422   ///
2423   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2424   /// is invariant in the calling loop.
2425   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2426                  Instruction *Inst2) {
2427     // First check if the result is already in the cache.
2428     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2429     Optional<bool> &result = AliasCache[key];
2430     if (result.hasValue()) {
2431       return result.getValue();
2432     }
2433     bool aliased = true;
2434     if (Loc1.Ptr && isSimple(Inst1))
2435       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2436     // Store the result in the cache.
2437     result = aliased;
2438     return aliased;
2439   }
2440 
2441   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2442 
2443   /// Cache for alias results.
2444   /// TODO: consider moving this to the AliasAnalysis itself.
2445   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2446 
2447   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2448   // globally through SLP because we don't perform any action which
2449   // invalidates capture results.
2450   BatchAAResults BatchAA;
2451 
2452   /// Removes an instruction from its block and eventually deletes it.
2453   /// It's like Instruction::eraseFromParent() except that the actual deletion
2454   /// is delayed until BoUpSLP is destructed.
2455   /// This is required to ensure that there are no incorrect collisions in the
2456   /// AliasCache, which can happen if a new instruction is allocated at the
2457   /// same address as a previously deleted instruction.
2458   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2459     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2460     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2461   }
2462 
2463   /// Temporary store for deleted instructions. Instructions will be deleted
2464   /// eventually when the BoUpSLP is destructed.
2465   DenseMap<Instruction *, bool> DeletedInstructions;
2466 
2467   /// A list of values that need to extracted out of the tree.
2468   /// This list holds pairs of (Internal Scalar : External User). External User
2469   /// can be nullptr, it means that this Internal Scalar will be used later,
2470   /// after vectorization.
2471   UserList ExternalUses;
2472 
2473   /// Values used only by @llvm.assume calls.
2474   SmallPtrSet<const Value *, 32> EphValues;
2475 
2476   /// Holds all of the instructions that we gathered.
2477   SetVector<Instruction *> GatherShuffleSeq;
2478 
2479   /// A list of blocks that we are going to CSE.
2480   SetVector<BasicBlock *> CSEBlocks;
2481 
2482   /// Contains all scheduling relevant data for an instruction.
2483   /// A ScheduleData either represents a single instruction or a member of an
2484   /// instruction bundle (= a group of instructions which is combined into a
2485   /// vector instruction).
2486   struct ScheduleData {
2487     // The initial value for the dependency counters. It means that the
2488     // dependencies are not calculated yet.
2489     enum { InvalidDeps = -1 };
2490 
2491     ScheduleData() = default;
2492 
2493     void init(int BlockSchedulingRegionID, Value *OpVal) {
2494       FirstInBundle = this;
2495       NextInBundle = nullptr;
2496       NextLoadStore = nullptr;
2497       IsScheduled = false;
2498       SchedulingRegionID = BlockSchedulingRegionID;
2499       clearDependencies();
2500       OpValue = OpVal;
2501       TE = nullptr;
2502       Lane = -1;
2503     }
2504 
2505     /// Verify basic self consistency properties
2506     void verify() {
2507       if (hasValidDependencies()) {
2508         assert(UnscheduledDeps <= Dependencies && "invariant");
2509       } else {
2510         assert(UnscheduledDeps == Dependencies && "invariant");
2511       }
2512 
2513       if (IsScheduled) {
2514         assert(isSchedulingEntity() &&
2515                 "unexpected scheduled state");
2516         for (const ScheduleData *BundleMember = this; BundleMember;
2517              BundleMember = BundleMember->NextInBundle) {
2518           assert(BundleMember->hasValidDependencies() &&
2519                  BundleMember->UnscheduledDeps == 0 &&
2520                  "unexpected scheduled state");
2521           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2522                  "only bundle is marked scheduled");
2523         }
2524       }
2525 
2526       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2527              "all bundle members must be in same basic block");
2528     }
2529 
2530     /// Returns true if the dependency information has been calculated.
2531     /// Note that depenendency validity can vary between instructions within
2532     /// a single bundle.
2533     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2534 
2535     /// Returns true for single instructions and for bundle representatives
2536     /// (= the head of a bundle).
2537     bool isSchedulingEntity() const { return FirstInBundle == this; }
2538 
2539     /// Returns true if it represents an instruction bundle and not only a
2540     /// single instruction.
2541     bool isPartOfBundle() const {
2542       return NextInBundle != nullptr || FirstInBundle != this;
2543     }
2544 
2545     /// Returns true if it is ready for scheduling, i.e. it has no more
2546     /// unscheduled depending instructions/bundles.
2547     bool isReady() const {
2548       assert(isSchedulingEntity() &&
2549              "can't consider non-scheduling entity for ready list");
2550       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2551     }
2552 
2553     /// Modifies the number of unscheduled dependencies for this instruction,
2554     /// and returns the number of remaining dependencies for the containing
2555     /// bundle.
2556     int incrementUnscheduledDeps(int Incr) {
2557       assert(hasValidDependencies() &&
2558              "increment of unscheduled deps would be meaningless");
2559       UnscheduledDeps += Incr;
2560       return FirstInBundle->unscheduledDepsInBundle();
2561     }
2562 
2563     /// Sets the number of unscheduled dependencies to the number of
2564     /// dependencies.
2565     void resetUnscheduledDeps() {
2566       UnscheduledDeps = Dependencies;
2567     }
2568 
2569     /// Clears all dependency information.
2570     void clearDependencies() {
2571       Dependencies = InvalidDeps;
2572       resetUnscheduledDeps();
2573       MemoryDependencies.clear();
2574     }
2575 
2576     int unscheduledDepsInBundle() const {
2577       assert(isSchedulingEntity() && "only meaningful on the bundle");
2578       int Sum = 0;
2579       for (const ScheduleData *BundleMember = this; BundleMember;
2580            BundleMember = BundleMember->NextInBundle) {
2581         if (BundleMember->UnscheduledDeps == InvalidDeps)
2582           return InvalidDeps;
2583         Sum += BundleMember->UnscheduledDeps;
2584       }
2585       return Sum;
2586     }
2587 
2588     void dump(raw_ostream &os) const {
2589       if (!isSchedulingEntity()) {
2590         os << "/ " << *Inst;
2591       } else if (NextInBundle) {
2592         os << '[' << *Inst;
2593         ScheduleData *SD = NextInBundle;
2594         while (SD) {
2595           os << ';' << *SD->Inst;
2596           SD = SD->NextInBundle;
2597         }
2598         os << ']';
2599       } else {
2600         os << *Inst;
2601       }
2602     }
2603 
2604     Instruction *Inst = nullptr;
2605 
2606     /// Opcode of the current instruction in the schedule data.
2607     Value *OpValue = nullptr;
2608 
2609     /// The TreeEntry that this instruction corresponds to.
2610     TreeEntry *TE = nullptr;
2611 
2612     /// Points to the head in an instruction bundle (and always to this for
2613     /// single instructions).
2614     ScheduleData *FirstInBundle = nullptr;
2615 
2616     /// Single linked list of all instructions in a bundle. Null if it is a
2617     /// single instruction.
2618     ScheduleData *NextInBundle = nullptr;
2619 
2620     /// Single linked list of all memory instructions (e.g. load, store, call)
2621     /// in the block - until the end of the scheduling region.
2622     ScheduleData *NextLoadStore = nullptr;
2623 
2624     /// The dependent memory instructions.
2625     /// This list is derived on demand in calculateDependencies().
2626     SmallVector<ScheduleData *, 4> MemoryDependencies;
2627 
2628     /// This ScheduleData is in the current scheduling region if this matches
2629     /// the current SchedulingRegionID of BlockScheduling.
2630     int SchedulingRegionID = 0;
2631 
2632     /// Used for getting a "good" final ordering of instructions.
2633     int SchedulingPriority = 0;
2634 
2635     /// The number of dependencies. Constitutes of the number of users of the
2636     /// instruction plus the number of dependent memory instructions (if any).
2637     /// This value is calculated on demand.
2638     /// If InvalidDeps, the number of dependencies is not calculated yet.
2639     int Dependencies = InvalidDeps;
2640 
2641     /// The number of dependencies minus the number of dependencies of scheduled
2642     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2643     /// for scheduling.
2644     /// Note that this is negative as long as Dependencies is not calculated.
2645     int UnscheduledDeps = InvalidDeps;
2646 
2647     /// The lane of this node in the TreeEntry.
2648     int Lane = -1;
2649 
2650     /// True if this instruction is scheduled (or considered as scheduled in the
2651     /// dry-run).
2652     bool IsScheduled = false;
2653   };
2654 
2655 #ifndef NDEBUG
2656   friend inline raw_ostream &operator<<(raw_ostream &os,
2657                                         const BoUpSLP::ScheduleData &SD) {
2658     SD.dump(os);
2659     return os;
2660   }
2661 #endif
2662 
2663   friend struct GraphTraits<BoUpSLP *>;
2664   friend struct DOTGraphTraits<BoUpSLP *>;
2665 
2666   /// Contains all scheduling data for a basic block.
2667   struct BlockScheduling {
2668     BlockScheduling(BasicBlock *BB)
2669         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2670 
2671     void clear() {
2672       ReadyInsts.clear();
2673       ScheduleStart = nullptr;
2674       ScheduleEnd = nullptr;
2675       FirstLoadStoreInRegion = nullptr;
2676       LastLoadStoreInRegion = nullptr;
2677 
2678       // Reduce the maximum schedule region size by the size of the
2679       // previous scheduling run.
2680       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2681       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2682         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2683       ScheduleRegionSize = 0;
2684 
2685       // Make a new scheduling region, i.e. all existing ScheduleData is not
2686       // in the new region yet.
2687       ++SchedulingRegionID;
2688     }
2689 
2690     ScheduleData *getScheduleData(Instruction *I) {
2691       if (BB != I->getParent())
2692         // Avoid lookup if can't possibly be in map.
2693         return nullptr;
2694       ScheduleData *SD = ScheduleDataMap[I];
2695       if (SD && isInSchedulingRegion(SD))
2696         return SD;
2697       return nullptr;
2698     }
2699 
2700     ScheduleData *getScheduleData(Value *V) {
2701       if (auto *I = dyn_cast<Instruction>(V))
2702         return getScheduleData(I);
2703       return nullptr;
2704     }
2705 
2706     ScheduleData *getScheduleData(Value *V, Value *Key) {
2707       if (V == Key)
2708         return getScheduleData(V);
2709       auto I = ExtraScheduleDataMap.find(V);
2710       if (I != ExtraScheduleDataMap.end()) {
2711         ScheduleData *SD = I->second[Key];
2712         if (SD && isInSchedulingRegion(SD))
2713           return SD;
2714       }
2715       return nullptr;
2716     }
2717 
2718     bool isInSchedulingRegion(ScheduleData *SD) const {
2719       return SD->SchedulingRegionID == SchedulingRegionID;
2720     }
2721 
2722     /// Marks an instruction as scheduled and puts all dependent ready
2723     /// instructions into the ready-list.
2724     template <typename ReadyListType>
2725     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2726       SD->IsScheduled = true;
2727       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2728 
2729       for (ScheduleData *BundleMember = SD; BundleMember;
2730            BundleMember = BundleMember->NextInBundle) {
2731         if (BundleMember->Inst != BundleMember->OpValue)
2732           continue;
2733 
2734         // Handle the def-use chain dependencies.
2735 
2736         // Decrement the unscheduled counter and insert to ready list if ready.
2737         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2738           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2739             if (OpDef && OpDef->hasValidDependencies() &&
2740                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2741               // There are no more unscheduled dependencies after
2742               // decrementing, so we can put the dependent instruction
2743               // into the ready list.
2744               ScheduleData *DepBundle = OpDef->FirstInBundle;
2745               assert(!DepBundle->IsScheduled &&
2746                      "already scheduled bundle gets ready");
2747               ReadyList.insert(DepBundle);
2748               LLVM_DEBUG(dbgs()
2749                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2750             }
2751           });
2752         };
2753 
2754         // If BundleMember is a vector bundle, its operands may have been
2755         // reordered during buildTree(). We therefore need to get its operands
2756         // through the TreeEntry.
2757         if (TreeEntry *TE = BundleMember->TE) {
2758           int Lane = BundleMember->Lane;
2759           assert(Lane >= 0 && "Lane not set");
2760 
2761           // Since vectorization tree is being built recursively this assertion
2762           // ensures that the tree entry has all operands set before reaching
2763           // this code. Couple of exceptions known at the moment are extracts
2764           // where their second (immediate) operand is not added. Since
2765           // immediates do not affect scheduler behavior this is considered
2766           // okay.
2767           auto *In = TE->getMainOp();
2768           assert(In &&
2769                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2770                   In->getNumOperands() == TE->getNumOperands()) &&
2771                  "Missed TreeEntry operands?");
2772           (void)In; // fake use to avoid build failure when assertions disabled
2773 
2774           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2775                OpIdx != NumOperands; ++OpIdx)
2776             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2777               DecrUnsched(I);
2778         } else {
2779           // If BundleMember is a stand-alone instruction, no operand reordering
2780           // has taken place, so we directly access its operands.
2781           for (Use &U : BundleMember->Inst->operands())
2782             if (auto *I = dyn_cast<Instruction>(U.get()))
2783               DecrUnsched(I);
2784         }
2785         // Handle the memory dependencies.
2786         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2787           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2788             // There are no more unscheduled dependencies after decrementing,
2789             // so we can put the dependent instruction into the ready list.
2790             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2791             assert(!DepBundle->IsScheduled &&
2792                    "already scheduled bundle gets ready");
2793             ReadyList.insert(DepBundle);
2794             LLVM_DEBUG(dbgs()
2795                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2796           }
2797         }
2798       }
2799     }
2800 
2801     /// Verify basic self consistency properties of the data structure.
2802     void verify() {
2803       if (!ScheduleStart)
2804         return;
2805 
2806       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2807              ScheduleStart->comesBefore(ScheduleEnd) &&
2808              "Not a valid scheduling region?");
2809 
2810       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2811         auto *SD = getScheduleData(I);
2812         assert(SD && "primary scheduledata must exist in window");
2813         assert(isInSchedulingRegion(SD) &&
2814                "primary schedule data not in window?");
2815         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2816                "entire bundle in window!");
2817         (void)SD;
2818         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2819       }
2820 
2821       for (auto *SD : ReadyInsts) {
2822         assert(SD->isSchedulingEntity() && SD->isReady() &&
2823                "item in ready list not ready?");
2824         (void)SD;
2825       }
2826     }
2827 
2828     void doForAllOpcodes(Value *V,
2829                          function_ref<void(ScheduleData *SD)> Action) {
2830       if (ScheduleData *SD = getScheduleData(V))
2831         Action(SD);
2832       auto I = ExtraScheduleDataMap.find(V);
2833       if (I != ExtraScheduleDataMap.end())
2834         for (auto &P : I->second)
2835           if (isInSchedulingRegion(P.second))
2836             Action(P.second);
2837     }
2838 
2839     /// Put all instructions into the ReadyList which are ready for scheduling.
2840     template <typename ReadyListType>
2841     void initialFillReadyList(ReadyListType &ReadyList) {
2842       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2843         doForAllOpcodes(I, [&](ScheduleData *SD) {
2844           if (SD->isSchedulingEntity() && SD->isReady()) {
2845             ReadyList.insert(SD);
2846             LLVM_DEBUG(dbgs()
2847                        << "SLP:    initially in ready list: " << *SD << "\n");
2848           }
2849         });
2850       }
2851     }
2852 
2853     /// Build a bundle from the ScheduleData nodes corresponding to the
2854     /// scalar instruction for each lane.
2855     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2856 
2857     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2858     /// cyclic dependencies. This is only a dry-run, no instructions are
2859     /// actually moved at this stage.
2860     /// \returns the scheduling bundle. The returned Optional value is non-None
2861     /// if \p VL is allowed to be scheduled.
2862     Optional<ScheduleData *>
2863     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2864                       const InstructionsState &S);
2865 
2866     /// Un-bundles a group of instructions.
2867     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2868 
2869     /// Allocates schedule data chunk.
2870     ScheduleData *allocateScheduleDataChunks();
2871 
2872     /// Extends the scheduling region so that V is inside the region.
2873     /// \returns true if the region size is within the limit.
2874     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2875 
2876     /// Initialize the ScheduleData structures for new instructions in the
2877     /// scheduling region.
2878     void initScheduleData(Instruction *FromI, Instruction *ToI,
2879                           ScheduleData *PrevLoadStore,
2880                           ScheduleData *NextLoadStore);
2881 
2882     /// Updates the dependency information of a bundle and of all instructions/
2883     /// bundles which depend on the original bundle.
2884     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2885                                BoUpSLP *SLP);
2886 
2887     /// Sets all instruction in the scheduling region to un-scheduled.
2888     void resetSchedule();
2889 
2890     BasicBlock *BB;
2891 
2892     /// Simple memory allocation for ScheduleData.
2893     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2894 
2895     /// The size of a ScheduleData array in ScheduleDataChunks.
2896     int ChunkSize;
2897 
2898     /// The allocator position in the current chunk, which is the last entry
2899     /// of ScheduleDataChunks.
2900     int ChunkPos;
2901 
2902     /// Attaches ScheduleData to Instruction.
2903     /// Note that the mapping survives during all vectorization iterations, i.e.
2904     /// ScheduleData structures are recycled.
2905     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
2906 
2907     /// Attaches ScheduleData to Instruction with the leading key.
2908     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2909         ExtraScheduleDataMap;
2910 
2911     /// The ready-list for scheduling (only used for the dry-run).
2912     SetVector<ScheduleData *> ReadyInsts;
2913 
2914     /// The first instruction of the scheduling region.
2915     Instruction *ScheduleStart = nullptr;
2916 
2917     /// The first instruction _after_ the scheduling region.
2918     Instruction *ScheduleEnd = nullptr;
2919 
2920     /// The first memory accessing instruction in the scheduling region
2921     /// (can be null).
2922     ScheduleData *FirstLoadStoreInRegion = nullptr;
2923 
2924     /// The last memory accessing instruction in the scheduling region
2925     /// (can be null).
2926     ScheduleData *LastLoadStoreInRegion = nullptr;
2927 
2928     /// The current size of the scheduling region.
2929     int ScheduleRegionSize = 0;
2930 
2931     /// The maximum size allowed for the scheduling region.
2932     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2933 
2934     /// The ID of the scheduling region. For a new vectorization iteration this
2935     /// is incremented which "removes" all ScheduleData from the region.
2936     /// Make sure that the initial SchedulingRegionID is greater than the
2937     /// initial SchedulingRegionID in ScheduleData (which is 0).
2938     int SchedulingRegionID = 1;
2939   };
2940 
2941   /// Attaches the BlockScheduling structures to basic blocks.
2942   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2943 
2944   /// Performs the "real" scheduling. Done before vectorization is actually
2945   /// performed in a basic block.
2946   void scheduleBlock(BlockScheduling *BS);
2947 
2948   /// List of users to ignore during scheduling and that don't need extracting.
2949   ArrayRef<Value *> UserIgnoreList;
2950 
2951   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2952   /// sorted SmallVectors of unsigned.
2953   struct OrdersTypeDenseMapInfo {
2954     static OrdersType getEmptyKey() {
2955       OrdersType V;
2956       V.push_back(~1U);
2957       return V;
2958     }
2959 
2960     static OrdersType getTombstoneKey() {
2961       OrdersType V;
2962       V.push_back(~2U);
2963       return V;
2964     }
2965 
2966     static unsigned getHashValue(const OrdersType &V) {
2967       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2968     }
2969 
2970     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2971       return LHS == RHS;
2972     }
2973   };
2974 
2975   // Analysis and block reference.
2976   Function *F;
2977   ScalarEvolution *SE;
2978   TargetTransformInfo *TTI;
2979   TargetLibraryInfo *TLI;
2980   LoopInfo *LI;
2981   DominatorTree *DT;
2982   AssumptionCache *AC;
2983   DemandedBits *DB;
2984   const DataLayout *DL;
2985   OptimizationRemarkEmitter *ORE;
2986 
2987   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2988   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2989 
2990   /// Instruction builder to construct the vectorized tree.
2991   IRBuilder<> Builder;
2992 
2993   /// A map of scalar integer values to the smallest bit width with which they
2994   /// can legally be represented. The values map to (width, signed) pairs,
2995   /// where "width" indicates the minimum bit width and "signed" is True if the
2996   /// value must be signed-extended, rather than zero-extended, back to its
2997   /// original width.
2998   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2999 };
3000 
3001 } // end namespace slpvectorizer
3002 
3003 template <> struct GraphTraits<BoUpSLP *> {
3004   using TreeEntry = BoUpSLP::TreeEntry;
3005 
3006   /// NodeRef has to be a pointer per the GraphWriter.
3007   using NodeRef = TreeEntry *;
3008 
3009   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3010 
3011   /// Add the VectorizableTree to the index iterator to be able to return
3012   /// TreeEntry pointers.
3013   struct ChildIteratorType
3014       : public iterator_adaptor_base<
3015             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3016     ContainerTy &VectorizableTree;
3017 
3018     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3019                       ContainerTy &VT)
3020         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3021 
3022     NodeRef operator*() { return I->UserTE; }
3023   };
3024 
3025   static NodeRef getEntryNode(BoUpSLP &R) {
3026     return R.VectorizableTree[0].get();
3027   }
3028 
3029   static ChildIteratorType child_begin(NodeRef N) {
3030     return {N->UserTreeIndices.begin(), N->Container};
3031   }
3032 
3033   static ChildIteratorType child_end(NodeRef N) {
3034     return {N->UserTreeIndices.end(), N->Container};
3035   }
3036 
3037   /// For the node iterator we just need to turn the TreeEntry iterator into a
3038   /// TreeEntry* iterator so that it dereferences to NodeRef.
3039   class nodes_iterator {
3040     using ItTy = ContainerTy::iterator;
3041     ItTy It;
3042 
3043   public:
3044     nodes_iterator(const ItTy &It2) : It(It2) {}
3045     NodeRef operator*() { return It->get(); }
3046     nodes_iterator operator++() {
3047       ++It;
3048       return *this;
3049     }
3050     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3051   };
3052 
3053   static nodes_iterator nodes_begin(BoUpSLP *R) {
3054     return nodes_iterator(R->VectorizableTree.begin());
3055   }
3056 
3057   static nodes_iterator nodes_end(BoUpSLP *R) {
3058     return nodes_iterator(R->VectorizableTree.end());
3059   }
3060 
3061   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3062 };
3063 
3064 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3065   using TreeEntry = BoUpSLP::TreeEntry;
3066 
3067   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3068 
3069   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3070     std::string Str;
3071     raw_string_ostream OS(Str);
3072     if (isSplat(Entry->Scalars))
3073       OS << "<splat> ";
3074     for (auto V : Entry->Scalars) {
3075       OS << *V;
3076       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3077             return EU.Scalar == V;
3078           }))
3079         OS << " <extract>";
3080       OS << "\n";
3081     }
3082     return Str;
3083   }
3084 
3085   static std::string getNodeAttributes(const TreeEntry *Entry,
3086                                        const BoUpSLP *) {
3087     if (Entry->State == TreeEntry::NeedToGather)
3088       return "color=red";
3089     return "";
3090   }
3091 };
3092 
3093 } // end namespace llvm
3094 
3095 BoUpSLP::~BoUpSLP() {
3096   for (const auto &Pair : DeletedInstructions) {
3097     // Replace operands of ignored instructions with Undefs in case if they were
3098     // marked for deletion.
3099     if (Pair.getSecond()) {
3100       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3101       Pair.getFirst()->replaceAllUsesWith(Undef);
3102     }
3103     Pair.getFirst()->dropAllReferences();
3104   }
3105   for (const auto &Pair : DeletedInstructions) {
3106     assert(Pair.getFirst()->use_empty() &&
3107            "trying to erase instruction with users.");
3108     Pair.getFirst()->eraseFromParent();
3109   }
3110 #ifdef EXPENSIVE_CHECKS
3111   // If we could guarantee that this call is not extremely slow, we could
3112   // remove the ifdef limitation (see PR47712).
3113   assert(!verifyFunction(*F, &dbgs()));
3114 #endif
3115 }
3116 
3117 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3118   for (auto *V : AV) {
3119     if (auto *I = dyn_cast<Instruction>(V))
3120       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3121   };
3122 }
3123 
3124 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3125 /// contains original mask for the scalars reused in the node. Procedure
3126 /// transform this mask in accordance with the given \p Mask.
3127 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3128   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3129          "Expected non-empty mask.");
3130   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3131   Prev.swap(Reuses);
3132   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3133     if (Mask[I] != UndefMaskElem)
3134       Reuses[Mask[I]] = Prev[I];
3135 }
3136 
3137 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3138 /// the original order of the scalars. Procedure transforms the provided order
3139 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3140 /// identity order, \p Order is cleared.
3141 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3142   assert(!Mask.empty() && "Expected non-empty mask.");
3143   SmallVector<int> MaskOrder;
3144   if (Order.empty()) {
3145     MaskOrder.resize(Mask.size());
3146     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3147   } else {
3148     inversePermutation(Order, MaskOrder);
3149   }
3150   reorderReuses(MaskOrder, Mask);
3151   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3152     Order.clear();
3153     return;
3154   }
3155   Order.assign(Mask.size(), Mask.size());
3156   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3157     if (MaskOrder[I] != UndefMaskElem)
3158       Order[MaskOrder[I]] = I;
3159   fixupOrderingIndices(Order);
3160 }
3161 
3162 Optional<BoUpSLP::OrdersType>
3163 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3164   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3165   unsigned NumScalars = TE.Scalars.size();
3166   OrdersType CurrentOrder(NumScalars, NumScalars);
3167   SmallVector<int> Positions;
3168   SmallBitVector UsedPositions(NumScalars);
3169   const TreeEntry *STE = nullptr;
3170   // Try to find all gathered scalars that are gets vectorized in other
3171   // vectorize node. Here we can have only one single tree vector node to
3172   // correctly identify order of the gathered scalars.
3173   for (unsigned I = 0; I < NumScalars; ++I) {
3174     Value *V = TE.Scalars[I];
3175     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3176       continue;
3177     if (const auto *LocalSTE = getTreeEntry(V)) {
3178       if (!STE)
3179         STE = LocalSTE;
3180       else if (STE != LocalSTE)
3181         // Take the order only from the single vector node.
3182         return None;
3183       unsigned Lane =
3184           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3185       if (Lane >= NumScalars)
3186         return None;
3187       if (CurrentOrder[Lane] != NumScalars) {
3188         if (Lane != I)
3189           continue;
3190         UsedPositions.reset(CurrentOrder[Lane]);
3191       }
3192       // The partial identity (where only some elements of the gather node are
3193       // in the identity order) is good.
3194       CurrentOrder[Lane] = I;
3195       UsedPositions.set(I);
3196     }
3197   }
3198   // Need to keep the order if we have a vector entry and at least 2 scalars or
3199   // the vectorized entry has just 2 scalars.
3200   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3201     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3202       for (unsigned I = 0; I < NumScalars; ++I)
3203         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3204           return false;
3205       return true;
3206     };
3207     if (IsIdentityOrder(CurrentOrder)) {
3208       CurrentOrder.clear();
3209       return CurrentOrder;
3210     }
3211     auto *It = CurrentOrder.begin();
3212     for (unsigned I = 0; I < NumScalars;) {
3213       if (UsedPositions.test(I)) {
3214         ++I;
3215         continue;
3216       }
3217       if (*It == NumScalars) {
3218         *It = I;
3219         ++I;
3220       }
3221       ++It;
3222     }
3223     return CurrentOrder;
3224   }
3225   return None;
3226 }
3227 
3228 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3229                                                          bool TopToBottom) {
3230   // No need to reorder if need to shuffle reuses, still need to shuffle the
3231   // node.
3232   if (!TE.ReuseShuffleIndices.empty())
3233     return None;
3234   if (TE.State == TreeEntry::Vectorize &&
3235       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3236        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3237       !TE.isAltShuffle())
3238     return TE.ReorderIndices;
3239   if (TE.State == TreeEntry::NeedToGather) {
3240     // TODO: add analysis of other gather nodes with extractelement
3241     // instructions and other values/instructions, not only undefs.
3242     if (((TE.getOpcode() == Instruction::ExtractElement &&
3243           !TE.isAltShuffle()) ||
3244          (all_of(TE.Scalars,
3245                  [](Value *V) {
3246                    return isa<UndefValue, ExtractElementInst>(V);
3247                  }) &&
3248           any_of(TE.Scalars,
3249                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3250         all_of(TE.Scalars,
3251                [](Value *V) {
3252                  auto *EE = dyn_cast<ExtractElementInst>(V);
3253                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3254                }) &&
3255         allSameType(TE.Scalars)) {
3256       // Check that gather of extractelements can be represented as
3257       // just a shuffle of a single vector.
3258       OrdersType CurrentOrder;
3259       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3260       if (Reuse || !CurrentOrder.empty()) {
3261         if (!CurrentOrder.empty())
3262           fixupOrderingIndices(CurrentOrder);
3263         return CurrentOrder;
3264       }
3265     }
3266     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3267       return CurrentOrder;
3268   }
3269   return None;
3270 }
3271 
3272 void BoUpSLP::reorderTopToBottom() {
3273   // Maps VF to the graph nodes.
3274   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3275   // ExtractElement gather nodes which can be vectorized and need to handle
3276   // their ordering.
3277   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3278   // Find all reorderable nodes with the given VF.
3279   // Currently the are vectorized stores,loads,extracts + some gathering of
3280   // extracts.
3281   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3282                                  const std::unique_ptr<TreeEntry> &TE) {
3283     if (Optional<OrdersType> CurrentOrder =
3284             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3285       // Do not include ordering for nodes used in the alt opcode vectorization,
3286       // better to reorder them during bottom-to-top stage. If follow the order
3287       // here, it causes reordering of the whole graph though actually it is
3288       // profitable just to reorder the subgraph that starts from the alternate
3289       // opcode vectorization node. Such nodes already end-up with the shuffle
3290       // instruction and it is just enough to change this shuffle rather than
3291       // rotate the scalars for the whole graph.
3292       unsigned Cnt = 0;
3293       const TreeEntry *UserTE = TE.get();
3294       while (UserTE && Cnt < RecursionMaxDepth) {
3295         if (UserTE->UserTreeIndices.size() != 1)
3296           break;
3297         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3298               return EI.UserTE->State == TreeEntry::Vectorize &&
3299                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3300             }))
3301           return;
3302         if (UserTE->UserTreeIndices.empty())
3303           UserTE = nullptr;
3304         else
3305           UserTE = UserTE->UserTreeIndices.back().UserTE;
3306         ++Cnt;
3307       }
3308       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3309       if (TE->State != TreeEntry::Vectorize)
3310         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3311     }
3312   });
3313 
3314   // Reorder the graph nodes according to their vectorization factor.
3315   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3316        VF /= 2) {
3317     auto It = VFToOrderedEntries.find(VF);
3318     if (It == VFToOrderedEntries.end())
3319       continue;
3320     // Try to find the most profitable order. We just are looking for the most
3321     // used order and reorder scalar elements in the nodes according to this
3322     // mostly used order.
3323     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3324     // All operands are reordered and used only in this node - propagate the
3325     // most used order to the user node.
3326     MapVector<OrdersType, unsigned,
3327               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3328         OrdersUses;
3329     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3330     for (const TreeEntry *OpTE : OrderedEntries) {
3331       // No need to reorder this nodes, still need to extend and to use shuffle,
3332       // just need to merge reordering shuffle and the reuse shuffle.
3333       if (!OpTE->ReuseShuffleIndices.empty())
3334         continue;
3335       // Count number of orders uses.
3336       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3337         if (OpTE->State == TreeEntry::NeedToGather)
3338           return GathersToOrders.find(OpTE)->second;
3339         return OpTE->ReorderIndices;
3340       }();
3341       // Stores actually store the mask, not the order, need to invert.
3342       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3343           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3344         SmallVector<int> Mask;
3345         inversePermutation(Order, Mask);
3346         unsigned E = Order.size();
3347         OrdersType CurrentOrder(E, E);
3348         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3349           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3350         });
3351         fixupOrderingIndices(CurrentOrder);
3352         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3353       } else {
3354         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3355       }
3356     }
3357     // Set order of the user node.
3358     if (OrdersUses.empty())
3359       continue;
3360     // Choose the most used order.
3361     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3362     unsigned Cnt = OrdersUses.front().second;
3363     for (const auto &Pair : drop_begin(OrdersUses)) {
3364       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3365         BestOrder = Pair.first;
3366         Cnt = Pair.second;
3367       }
3368     }
3369     // Set order of the user node.
3370     if (BestOrder.empty())
3371       continue;
3372     SmallVector<int> Mask;
3373     inversePermutation(BestOrder, Mask);
3374     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3375     unsigned E = BestOrder.size();
3376     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3377       return I < E ? static_cast<int>(I) : UndefMaskElem;
3378     });
3379     // Do an actual reordering, if profitable.
3380     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3381       // Just do the reordering for the nodes with the given VF.
3382       if (TE->Scalars.size() != VF) {
3383         if (TE->ReuseShuffleIndices.size() == VF) {
3384           // Need to reorder the reuses masks of the operands with smaller VF to
3385           // be able to find the match between the graph nodes and scalar
3386           // operands of the given node during vectorization/cost estimation.
3387           assert(all_of(TE->UserTreeIndices,
3388                         [VF, &TE](const EdgeInfo &EI) {
3389                           return EI.UserTE->Scalars.size() == VF ||
3390                                  EI.UserTE->Scalars.size() ==
3391                                      TE->Scalars.size();
3392                         }) &&
3393                  "All users must be of VF size.");
3394           // Update ordering of the operands with the smaller VF than the given
3395           // one.
3396           reorderReuses(TE->ReuseShuffleIndices, Mask);
3397         }
3398         continue;
3399       }
3400       if (TE->State == TreeEntry::Vectorize &&
3401           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3402               InsertElementInst>(TE->getMainOp()) &&
3403           !TE->isAltShuffle()) {
3404         // Build correct orders for extract{element,value}, loads and
3405         // stores.
3406         reorderOrder(TE->ReorderIndices, Mask);
3407         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3408           TE->reorderOperands(Mask);
3409       } else {
3410         // Reorder the node and its operands.
3411         TE->reorderOperands(Mask);
3412         assert(TE->ReorderIndices.empty() &&
3413                "Expected empty reorder sequence.");
3414         reorderScalars(TE->Scalars, Mask);
3415       }
3416       if (!TE->ReuseShuffleIndices.empty()) {
3417         // Apply reversed order to keep the original ordering of the reused
3418         // elements to avoid extra reorder indices shuffling.
3419         OrdersType CurrentOrder;
3420         reorderOrder(CurrentOrder, MaskOrder);
3421         SmallVector<int> NewReuses;
3422         inversePermutation(CurrentOrder, NewReuses);
3423         addMask(NewReuses, TE->ReuseShuffleIndices);
3424         TE->ReuseShuffleIndices.swap(NewReuses);
3425       }
3426     }
3427   }
3428 }
3429 
3430 bool BoUpSLP::canReorderOperands(
3431     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3432     ArrayRef<TreeEntry *> ReorderableGathers,
3433     SmallVectorImpl<TreeEntry *> &GatherOps) {
3434   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3435     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3436           return OpData.first == I &&
3437                  OpData.second->State == TreeEntry::Vectorize;
3438         }))
3439       continue;
3440     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3441       // Do not reorder if operand node is used by many user nodes.
3442       if (any_of(TE->UserTreeIndices,
3443                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3444         return false;
3445       // Add the node to the list of the ordered nodes with the identity
3446       // order.
3447       Edges.emplace_back(I, TE);
3448       continue;
3449     }
3450     ArrayRef<Value *> VL = UserTE->getOperand(I);
3451     TreeEntry *Gather = nullptr;
3452     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3453           assert(TE->State != TreeEntry::Vectorize &&
3454                  "Only non-vectorized nodes are expected.");
3455           if (TE->isSame(VL)) {
3456             Gather = TE;
3457             return true;
3458           }
3459           return false;
3460         }) > 1)
3461       return false;
3462     if (Gather)
3463       GatherOps.push_back(Gather);
3464   }
3465   return true;
3466 }
3467 
3468 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3469   SetVector<TreeEntry *> OrderedEntries;
3470   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3471   // Find all reorderable leaf nodes with the given VF.
3472   // Currently the are vectorized loads,extracts without alternate operands +
3473   // some gathering of extracts.
3474   SmallVector<TreeEntry *> NonVectorized;
3475   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3476                               &NonVectorized](
3477                                  const std::unique_ptr<TreeEntry> &TE) {
3478     if (TE->State != TreeEntry::Vectorize)
3479       NonVectorized.push_back(TE.get());
3480     if (Optional<OrdersType> CurrentOrder =
3481             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3482       OrderedEntries.insert(TE.get());
3483       if (TE->State != TreeEntry::Vectorize)
3484         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3485     }
3486   });
3487 
3488   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3489   // I.e., if the node has operands, that are reordered, try to make at least
3490   // one operand order in the natural order and reorder others + reorder the
3491   // user node itself.
3492   SmallPtrSet<const TreeEntry *, 4> Visited;
3493   while (!OrderedEntries.empty()) {
3494     // 1. Filter out only reordered nodes.
3495     // 2. If the entry has multiple uses - skip it and jump to the next node.
3496     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3497     SmallVector<TreeEntry *> Filtered;
3498     for (TreeEntry *TE : OrderedEntries) {
3499       if (!(TE->State == TreeEntry::Vectorize ||
3500             (TE->State == TreeEntry::NeedToGather &&
3501              GathersToOrders.count(TE))) ||
3502           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3503           !all_of(drop_begin(TE->UserTreeIndices),
3504                   [TE](const EdgeInfo &EI) {
3505                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3506                   }) ||
3507           !Visited.insert(TE).second) {
3508         Filtered.push_back(TE);
3509         continue;
3510       }
3511       // Build a map between user nodes and their operands order to speedup
3512       // search. The graph currently does not provide this dependency directly.
3513       for (EdgeInfo &EI : TE->UserTreeIndices) {
3514         TreeEntry *UserTE = EI.UserTE;
3515         auto It = Users.find(UserTE);
3516         if (It == Users.end())
3517           It = Users.insert({UserTE, {}}).first;
3518         It->second.emplace_back(EI.EdgeIdx, TE);
3519       }
3520     }
3521     // Erase filtered entries.
3522     for_each(Filtered,
3523              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3524     for (auto &Data : Users) {
3525       // Check that operands are used only in the User node.
3526       SmallVector<TreeEntry *> GatherOps;
3527       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3528                               GatherOps)) {
3529         for_each(Data.second,
3530                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3531                    OrderedEntries.remove(Op.second);
3532                  });
3533         continue;
3534       }
3535       // All operands are reordered and used only in this node - propagate the
3536       // most used order to the user node.
3537       MapVector<OrdersType, unsigned,
3538                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3539           OrdersUses;
3540       // Do the analysis for each tree entry only once, otherwise the order of
3541       // the same node my be considered several times, though might be not
3542       // profitable.
3543       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3544       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3545       for (const auto &Op : Data.second) {
3546         TreeEntry *OpTE = Op.second;
3547         if (!VisitedOps.insert(OpTE).second)
3548           continue;
3549         if (!OpTE->ReuseShuffleIndices.empty() ||
3550             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3551           continue;
3552         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3553           if (OpTE->State == TreeEntry::NeedToGather)
3554             return GathersToOrders.find(OpTE)->second;
3555           return OpTE->ReorderIndices;
3556         }();
3557         unsigned NumOps = count_if(
3558             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3559               return P.second == OpTE;
3560             });
3561         // Stores actually store the mask, not the order, need to invert.
3562         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3563             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3564           SmallVector<int> Mask;
3565           inversePermutation(Order, Mask);
3566           unsigned E = Order.size();
3567           OrdersType CurrentOrder(E, E);
3568           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3569             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3570           });
3571           fixupOrderingIndices(CurrentOrder);
3572           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3573               NumOps;
3574         } else {
3575           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3576         }
3577         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3578         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3579                                             const TreeEntry *TE) {
3580           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3581               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3582               (IgnoreReorder && TE->Idx == 0))
3583             return true;
3584           if (TE->State == TreeEntry::NeedToGather) {
3585             auto It = GathersToOrders.find(TE);
3586             if (It != GathersToOrders.end())
3587               return !It->second.empty();
3588             return true;
3589           }
3590           return false;
3591         };
3592         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3593           TreeEntry *UserTE = EI.UserTE;
3594           if (!VisitedUsers.insert(UserTE).second)
3595             continue;
3596           // May reorder user node if it requires reordering, has reused
3597           // scalars, is an alternate op vectorize node or its op nodes require
3598           // reordering.
3599           if (AllowsReordering(UserTE))
3600             continue;
3601           // Check if users allow reordering.
3602           // Currently look up just 1 level of operands to avoid increase of
3603           // the compile time.
3604           // Profitable to reorder if definitely more operands allow
3605           // reordering rather than those with natural order.
3606           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3607           if (static_cast<unsigned>(count_if(
3608                   Ops, [UserTE, &AllowsReordering](
3609                            const std::pair<unsigned, TreeEntry *> &Op) {
3610                     return AllowsReordering(Op.second) &&
3611                            all_of(Op.second->UserTreeIndices,
3612                                   [UserTE](const EdgeInfo &EI) {
3613                                     return EI.UserTE == UserTE;
3614                                   });
3615                   })) <= Ops.size() / 2)
3616             ++Res.first->second;
3617         }
3618       }
3619       // If no orders - skip current nodes and jump to the next one, if any.
3620       if (OrdersUses.empty()) {
3621         for_each(Data.second,
3622                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3623                    OrderedEntries.remove(Op.second);
3624                  });
3625         continue;
3626       }
3627       // Choose the best order.
3628       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3629       unsigned Cnt = OrdersUses.front().second;
3630       for (const auto &Pair : drop_begin(OrdersUses)) {
3631         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3632           BestOrder = Pair.first;
3633           Cnt = Pair.second;
3634         }
3635       }
3636       // Set order of the user node (reordering of operands and user nodes).
3637       if (BestOrder.empty()) {
3638         for_each(Data.second,
3639                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3640                    OrderedEntries.remove(Op.second);
3641                  });
3642         continue;
3643       }
3644       // Erase operands from OrderedEntries list and adjust their orders.
3645       VisitedOps.clear();
3646       SmallVector<int> Mask;
3647       inversePermutation(BestOrder, Mask);
3648       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3649       unsigned E = BestOrder.size();
3650       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3651         return I < E ? static_cast<int>(I) : UndefMaskElem;
3652       });
3653       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3654         TreeEntry *TE = Op.second;
3655         OrderedEntries.remove(TE);
3656         if (!VisitedOps.insert(TE).second)
3657           continue;
3658         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3659           // Just reorder reuses indices.
3660           reorderReuses(TE->ReuseShuffleIndices, Mask);
3661           continue;
3662         }
3663         // Gathers are processed separately.
3664         if (TE->State != TreeEntry::Vectorize)
3665           continue;
3666         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3667                 TE->ReorderIndices.empty()) &&
3668                "Non-matching sizes of user/operand entries.");
3669         reorderOrder(TE->ReorderIndices, Mask);
3670       }
3671       // For gathers just need to reorder its scalars.
3672       for (TreeEntry *Gather : GatherOps) {
3673         assert(Gather->ReorderIndices.empty() &&
3674                "Unexpected reordering of gathers.");
3675         if (!Gather->ReuseShuffleIndices.empty()) {
3676           // Just reorder reuses indices.
3677           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3678           continue;
3679         }
3680         reorderScalars(Gather->Scalars, Mask);
3681         OrderedEntries.remove(Gather);
3682       }
3683       // Reorder operands of the user node and set the ordering for the user
3684       // node itself.
3685       if (Data.first->State != TreeEntry::Vectorize ||
3686           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3687               Data.first->getMainOp()) ||
3688           Data.first->isAltShuffle())
3689         Data.first->reorderOperands(Mask);
3690       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3691           Data.first->isAltShuffle()) {
3692         reorderScalars(Data.first->Scalars, Mask);
3693         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3694         if (Data.first->ReuseShuffleIndices.empty() &&
3695             !Data.first->ReorderIndices.empty() &&
3696             !Data.first->isAltShuffle()) {
3697           // Insert user node to the list to try to sink reordering deeper in
3698           // the graph.
3699           OrderedEntries.insert(Data.first);
3700         }
3701       } else {
3702         reorderOrder(Data.first->ReorderIndices, Mask);
3703       }
3704     }
3705   }
3706   // If the reordering is unnecessary, just remove the reorder.
3707   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3708       VectorizableTree.front()->ReuseShuffleIndices.empty())
3709     VectorizableTree.front()->ReorderIndices.clear();
3710 }
3711 
3712 void BoUpSLP::buildExternalUses(
3713     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3714   // Collect the values that we need to extract from the tree.
3715   for (auto &TEPtr : VectorizableTree) {
3716     TreeEntry *Entry = TEPtr.get();
3717 
3718     // No need to handle users of gathered values.
3719     if (Entry->State == TreeEntry::NeedToGather)
3720       continue;
3721 
3722     // For each lane:
3723     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3724       Value *Scalar = Entry->Scalars[Lane];
3725       int FoundLane = Entry->findLaneForValue(Scalar);
3726 
3727       // Check if the scalar is externally used as an extra arg.
3728       auto ExtI = ExternallyUsedValues.find(Scalar);
3729       if (ExtI != ExternallyUsedValues.end()) {
3730         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3731                           << Lane << " from " << *Scalar << ".\n");
3732         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3733       }
3734       for (User *U : Scalar->users()) {
3735         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3736 
3737         Instruction *UserInst = dyn_cast<Instruction>(U);
3738         if (!UserInst)
3739           continue;
3740 
3741         if (isDeleted(UserInst))
3742           continue;
3743 
3744         // Skip in-tree scalars that become vectors
3745         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3746           Value *UseScalar = UseEntry->Scalars[0];
3747           // Some in-tree scalars will remain as scalar in vectorized
3748           // instructions. If that is the case, the one in Lane 0 will
3749           // be used.
3750           if (UseScalar != U ||
3751               UseEntry->State == TreeEntry::ScatterVectorize ||
3752               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3753             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3754                               << ".\n");
3755             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3756             continue;
3757           }
3758         }
3759 
3760         // Ignore users in the user ignore list.
3761         if (is_contained(UserIgnoreList, UserInst))
3762           continue;
3763 
3764         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3765                           << Lane << " from " << *Scalar << ".\n");
3766         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3767       }
3768     }
3769   }
3770 }
3771 
3772 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3773                         ArrayRef<Value *> UserIgnoreLst) {
3774   deleteTree();
3775   UserIgnoreList = UserIgnoreLst;
3776   if (!allSameType(Roots))
3777     return;
3778   buildTree_rec(Roots, 0, EdgeInfo());
3779 }
3780 
3781 namespace {
3782 /// Tracks the state we can represent the loads in the given sequence.
3783 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3784 } // anonymous namespace
3785 
3786 /// Checks if the given array of loads can be represented as a vectorized,
3787 /// scatter or just simple gather.
3788 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3789                                     const TargetTransformInfo &TTI,
3790                                     const DataLayout &DL, ScalarEvolution &SE,
3791                                     SmallVectorImpl<unsigned> &Order,
3792                                     SmallVectorImpl<Value *> &PointerOps) {
3793   // Check that a vectorized load would load the same memory as a scalar
3794   // load. For example, we don't want to vectorize loads that are smaller
3795   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3796   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3797   // from such a struct, we read/write packed bits disagreeing with the
3798   // unvectorized version.
3799   Type *ScalarTy = VL0->getType();
3800 
3801   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3802     return LoadsState::Gather;
3803 
3804   // Make sure all loads in the bundle are simple - we can't vectorize
3805   // atomic or volatile loads.
3806   PointerOps.clear();
3807   PointerOps.resize(VL.size());
3808   auto *POIter = PointerOps.begin();
3809   for (Value *V : VL) {
3810     auto *L = cast<LoadInst>(V);
3811     if (!L->isSimple())
3812       return LoadsState::Gather;
3813     *POIter = L->getPointerOperand();
3814     ++POIter;
3815   }
3816 
3817   Order.clear();
3818   // Check the order of pointer operands.
3819   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3820     Value *Ptr0;
3821     Value *PtrN;
3822     if (Order.empty()) {
3823       Ptr0 = PointerOps.front();
3824       PtrN = PointerOps.back();
3825     } else {
3826       Ptr0 = PointerOps[Order.front()];
3827       PtrN = PointerOps[Order.back()];
3828     }
3829     Optional<int> Diff =
3830         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3831     // Check that the sorted loads are consecutive.
3832     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3833       return LoadsState::Vectorize;
3834     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3835     for (Value *V : VL)
3836       CommonAlignment =
3837           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3838     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3839                                 CommonAlignment))
3840       return LoadsState::ScatterVectorize;
3841   }
3842 
3843   return LoadsState::Gather;
3844 }
3845 
3846 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3847                             const EdgeInfo &UserTreeIdx) {
3848   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3849 
3850   SmallVector<int> ReuseShuffleIndicies;
3851   SmallVector<Value *> UniqueValues;
3852   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3853                                 &UserTreeIdx,
3854                                 this](const InstructionsState &S) {
3855     // Check that every instruction appears once in this bundle.
3856     DenseMap<Value *, unsigned> UniquePositions;
3857     for (Value *V : VL) {
3858       if (isConstant(V)) {
3859         ReuseShuffleIndicies.emplace_back(
3860             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3861         UniqueValues.emplace_back(V);
3862         continue;
3863       }
3864       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3865       ReuseShuffleIndicies.emplace_back(Res.first->second);
3866       if (Res.second)
3867         UniqueValues.emplace_back(V);
3868     }
3869     size_t NumUniqueScalarValues = UniqueValues.size();
3870     if (NumUniqueScalarValues == VL.size()) {
3871       ReuseShuffleIndicies.clear();
3872     } else {
3873       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3874       if (NumUniqueScalarValues <= 1 ||
3875           (UniquePositions.size() == 1 && all_of(UniqueValues,
3876                                                  [](Value *V) {
3877                                                    return isa<UndefValue>(V) ||
3878                                                           !isConstant(V);
3879                                                  })) ||
3880           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3881         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3882         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3883         return false;
3884       }
3885       VL = UniqueValues;
3886     }
3887     return true;
3888   };
3889 
3890   InstructionsState S = getSameOpcode(VL);
3891   if (Depth == RecursionMaxDepth) {
3892     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3893     if (TryToFindDuplicates(S))
3894       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3895                    ReuseShuffleIndicies);
3896     return;
3897   }
3898 
3899   // Don't handle scalable vectors
3900   if (S.getOpcode() == Instruction::ExtractElement &&
3901       isa<ScalableVectorType>(
3902           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3903     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3904     if (TryToFindDuplicates(S))
3905       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3906                    ReuseShuffleIndicies);
3907     return;
3908   }
3909 
3910   // Don't handle vectors.
3911   if (S.OpValue->getType()->isVectorTy() &&
3912       !isa<InsertElementInst>(S.OpValue)) {
3913     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3914     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3915     return;
3916   }
3917 
3918   // Avoid attempting to schedule allocas; there are unmodeled dependencies
3919   // for "static" alloca status and for reordering with stacksave calls.
3920   for (Value *V : VL) {
3921     if (isa<AllocaInst>(V)) {
3922       LLVM_DEBUG(dbgs() << "SLP: Gathering due to alloca.\n");
3923       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3924       return;
3925     }
3926   }
3927 
3928   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3929     if (SI->getValueOperand()->getType()->isVectorTy()) {
3930       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3931       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3932       return;
3933     }
3934 
3935   // If all of the operands are identical or constant we have a simple solution.
3936   // If we deal with insert/extract instructions, they all must have constant
3937   // indices, otherwise we should gather them, not try to vectorize.
3938   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3939       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3940        !all_of(VL, isVectorLikeInstWithConstOps))) {
3941     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3942     if (TryToFindDuplicates(S))
3943       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3944                    ReuseShuffleIndicies);
3945     return;
3946   }
3947 
3948   // We now know that this is a vector of instructions of the same type from
3949   // the same block.
3950 
3951   // Don't vectorize ephemeral values.
3952   for (Value *V : VL) {
3953     if (EphValues.count(V)) {
3954       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3955                         << ") is ephemeral.\n");
3956       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3957       return;
3958     }
3959   }
3960 
3961   // Check if this is a duplicate of another entry.
3962   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3963     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3964     if (!E->isSame(VL)) {
3965       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3966       if (TryToFindDuplicates(S))
3967         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3968                      ReuseShuffleIndicies);
3969       return;
3970     }
3971     // Record the reuse of the tree node.  FIXME, currently this is only used to
3972     // properly draw the graph rather than for the actual vectorization.
3973     E->UserTreeIndices.push_back(UserTreeIdx);
3974     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3975                       << ".\n");
3976     return;
3977   }
3978 
3979   // Check that none of the instructions in the bundle are already in the tree.
3980   for (Value *V : VL) {
3981     auto *I = dyn_cast<Instruction>(V);
3982     if (!I)
3983       continue;
3984     if (getTreeEntry(I)) {
3985       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3986                         << ") is already in tree.\n");
3987       if (TryToFindDuplicates(S))
3988         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3989                      ReuseShuffleIndicies);
3990       return;
3991     }
3992   }
3993 
3994   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3995   for (Value *V : VL) {
3996     if (is_contained(UserIgnoreList, V)) {
3997       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3998       if (TryToFindDuplicates(S))
3999         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4000                      ReuseShuffleIndicies);
4001       return;
4002     }
4003   }
4004 
4005   // Check that all of the users of the scalars that we want to vectorize are
4006   // schedulable.
4007   auto *VL0 = cast<Instruction>(S.OpValue);
4008   BasicBlock *BB = VL0->getParent();
4009 
4010   if (!DT->isReachableFromEntry(BB)) {
4011     // Don't go into unreachable blocks. They may contain instructions with
4012     // dependency cycles which confuse the final scheduling.
4013     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4014     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4015     return;
4016   }
4017 
4018   // Check that every instruction appears once in this bundle.
4019   if (!TryToFindDuplicates(S))
4020     return;
4021 
4022   auto &BSRef = BlocksSchedules[BB];
4023   if (!BSRef)
4024     BSRef = std::make_unique<BlockScheduling>(BB);
4025 
4026   BlockScheduling &BS = *BSRef.get();
4027 
4028   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4029 #ifdef EXPENSIVE_CHECKS
4030   // Make sure we didn't break any internal invariants
4031   BS.verify();
4032 #endif
4033   if (!Bundle) {
4034     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4035     assert((!BS.getScheduleData(VL0) ||
4036             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4037            "tryScheduleBundle should cancelScheduling on failure");
4038     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4039                  ReuseShuffleIndicies);
4040     return;
4041   }
4042   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4043 
4044   unsigned ShuffleOrOp = S.isAltShuffle() ?
4045                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4046   switch (ShuffleOrOp) {
4047     case Instruction::PHI: {
4048       auto *PH = cast<PHINode>(VL0);
4049 
4050       // Check for terminator values (e.g. invoke).
4051       for (Value *V : VL)
4052         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4053           Instruction *Term = dyn_cast<Instruction>(
4054               cast<PHINode>(V)->getIncomingValueForBlock(
4055                   PH->getIncomingBlock(I)));
4056           if (Term && Term->isTerminator()) {
4057             LLVM_DEBUG(dbgs()
4058                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4059             BS.cancelScheduling(VL, VL0);
4060             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4061                          ReuseShuffleIndicies);
4062             return;
4063           }
4064         }
4065 
4066       TreeEntry *TE =
4067           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4068       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4069 
4070       // Keeps the reordered operands to avoid code duplication.
4071       SmallVector<ValueList, 2> OperandsVec;
4072       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4073         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4074           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4075           TE->setOperand(I, Operands);
4076           OperandsVec.push_back(Operands);
4077           continue;
4078         }
4079         ValueList Operands;
4080         // Prepare the operand vector.
4081         for (Value *V : VL)
4082           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4083               PH->getIncomingBlock(I)));
4084         TE->setOperand(I, Operands);
4085         OperandsVec.push_back(Operands);
4086       }
4087       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4088         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4089       return;
4090     }
4091     case Instruction::ExtractValue:
4092     case Instruction::ExtractElement: {
4093       OrdersType CurrentOrder;
4094       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4095       if (Reuse) {
4096         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4097         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4098                      ReuseShuffleIndicies);
4099         // This is a special case, as it does not gather, but at the same time
4100         // we are not extending buildTree_rec() towards the operands.
4101         ValueList Op0;
4102         Op0.assign(VL.size(), VL0->getOperand(0));
4103         VectorizableTree.back()->setOperand(0, Op0);
4104         return;
4105       }
4106       if (!CurrentOrder.empty()) {
4107         LLVM_DEBUG({
4108           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4109                     "with order";
4110           for (unsigned Idx : CurrentOrder)
4111             dbgs() << " " << Idx;
4112           dbgs() << "\n";
4113         });
4114         fixupOrderingIndices(CurrentOrder);
4115         // Insert new order with initial value 0, if it does not exist,
4116         // otherwise return the iterator to the existing one.
4117         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4118                      ReuseShuffleIndicies, CurrentOrder);
4119         // This is a special case, as it does not gather, but at the same time
4120         // we are not extending buildTree_rec() towards the operands.
4121         ValueList Op0;
4122         Op0.assign(VL.size(), VL0->getOperand(0));
4123         VectorizableTree.back()->setOperand(0, Op0);
4124         return;
4125       }
4126       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4127       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4128                    ReuseShuffleIndicies);
4129       BS.cancelScheduling(VL, VL0);
4130       return;
4131     }
4132     case Instruction::InsertElement: {
4133       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4134 
4135       // Check that we have a buildvector and not a shuffle of 2 or more
4136       // different vectors.
4137       ValueSet SourceVectors;
4138       for (Value *V : VL) {
4139         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4140         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4141       }
4142 
4143       if (count_if(VL, [&SourceVectors](Value *V) {
4144             return !SourceVectors.contains(V);
4145           }) >= 2) {
4146         // Found 2nd source vector - cancel.
4147         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4148                              "different source vectors.\n");
4149         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4150         BS.cancelScheduling(VL, VL0);
4151         return;
4152       }
4153 
4154       auto OrdCompare = [](const std::pair<int, int> &P1,
4155                            const std::pair<int, int> &P2) {
4156         return P1.first > P2.first;
4157       };
4158       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4159                     decltype(OrdCompare)>
4160           Indices(OrdCompare);
4161       for (int I = 0, E = VL.size(); I < E; ++I) {
4162         unsigned Idx = *getInsertIndex(VL[I]);
4163         Indices.emplace(Idx, I);
4164       }
4165       OrdersType CurrentOrder(VL.size(), VL.size());
4166       bool IsIdentity = true;
4167       for (int I = 0, E = VL.size(); I < E; ++I) {
4168         CurrentOrder[Indices.top().second] = I;
4169         IsIdentity &= Indices.top().second == I;
4170         Indices.pop();
4171       }
4172       if (IsIdentity)
4173         CurrentOrder.clear();
4174       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4175                                    None, CurrentOrder);
4176       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4177 
4178       constexpr int NumOps = 2;
4179       ValueList VectorOperands[NumOps];
4180       for (int I = 0; I < NumOps; ++I) {
4181         for (Value *V : VL)
4182           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4183 
4184         TE->setOperand(I, VectorOperands[I]);
4185       }
4186       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4187       return;
4188     }
4189     case Instruction::Load: {
4190       // Check that a vectorized load would load the same memory as a scalar
4191       // load. For example, we don't want to vectorize loads that are smaller
4192       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4193       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4194       // from such a struct, we read/write packed bits disagreeing with the
4195       // unvectorized version.
4196       SmallVector<Value *> PointerOps;
4197       OrdersType CurrentOrder;
4198       TreeEntry *TE = nullptr;
4199       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4200                                 PointerOps)) {
4201       case LoadsState::Vectorize:
4202         if (CurrentOrder.empty()) {
4203           // Original loads are consecutive and does not require reordering.
4204           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4205                             ReuseShuffleIndicies);
4206           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4207         } else {
4208           fixupOrderingIndices(CurrentOrder);
4209           // Need to reorder.
4210           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4211                             ReuseShuffleIndicies, CurrentOrder);
4212           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4213         }
4214         TE->setOperandsInOrder();
4215         break;
4216       case LoadsState::ScatterVectorize:
4217         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4218         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4219                           UserTreeIdx, ReuseShuffleIndicies);
4220         TE->setOperandsInOrder();
4221         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4222         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4223         break;
4224       case LoadsState::Gather:
4225         BS.cancelScheduling(VL, VL0);
4226         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4227                      ReuseShuffleIndicies);
4228 #ifndef NDEBUG
4229         Type *ScalarTy = VL0->getType();
4230         if (DL->getTypeSizeInBits(ScalarTy) !=
4231             DL->getTypeAllocSizeInBits(ScalarTy))
4232           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4233         else if (any_of(VL, [](Value *V) {
4234                    return !cast<LoadInst>(V)->isSimple();
4235                  }))
4236           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4237         else
4238           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4239 #endif // NDEBUG
4240         break;
4241       }
4242       return;
4243     }
4244     case Instruction::ZExt:
4245     case Instruction::SExt:
4246     case Instruction::FPToUI:
4247     case Instruction::FPToSI:
4248     case Instruction::FPExt:
4249     case Instruction::PtrToInt:
4250     case Instruction::IntToPtr:
4251     case Instruction::SIToFP:
4252     case Instruction::UIToFP:
4253     case Instruction::Trunc:
4254     case Instruction::FPTrunc:
4255     case Instruction::BitCast: {
4256       Type *SrcTy = VL0->getOperand(0)->getType();
4257       for (Value *V : VL) {
4258         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4259         if (Ty != SrcTy || !isValidElementType(Ty)) {
4260           BS.cancelScheduling(VL, VL0);
4261           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4262                        ReuseShuffleIndicies);
4263           LLVM_DEBUG(dbgs()
4264                      << "SLP: Gathering casts with different src types.\n");
4265           return;
4266         }
4267       }
4268       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4269                                    ReuseShuffleIndicies);
4270       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4271 
4272       TE->setOperandsInOrder();
4273       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4274         ValueList Operands;
4275         // Prepare the operand vector.
4276         for (Value *V : VL)
4277           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4278 
4279         buildTree_rec(Operands, Depth + 1, {TE, i});
4280       }
4281       return;
4282     }
4283     case Instruction::ICmp:
4284     case Instruction::FCmp: {
4285       // Check that all of the compares have the same predicate.
4286       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4287       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4288       Type *ComparedTy = VL0->getOperand(0)->getType();
4289       for (Value *V : VL) {
4290         CmpInst *Cmp = cast<CmpInst>(V);
4291         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4292             Cmp->getOperand(0)->getType() != ComparedTy) {
4293           BS.cancelScheduling(VL, VL0);
4294           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4295                        ReuseShuffleIndicies);
4296           LLVM_DEBUG(dbgs()
4297                      << "SLP: Gathering cmp with different predicate.\n");
4298           return;
4299         }
4300       }
4301 
4302       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4303                                    ReuseShuffleIndicies);
4304       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4305 
4306       ValueList Left, Right;
4307       if (cast<CmpInst>(VL0)->isCommutative()) {
4308         // Commutative predicate - collect + sort operands of the instructions
4309         // so that each side is more likely to have the same opcode.
4310         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4311         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4312       } else {
4313         // Collect operands - commute if it uses the swapped predicate.
4314         for (Value *V : VL) {
4315           auto *Cmp = cast<CmpInst>(V);
4316           Value *LHS = Cmp->getOperand(0);
4317           Value *RHS = Cmp->getOperand(1);
4318           if (Cmp->getPredicate() != P0)
4319             std::swap(LHS, RHS);
4320           Left.push_back(LHS);
4321           Right.push_back(RHS);
4322         }
4323       }
4324       TE->setOperand(0, Left);
4325       TE->setOperand(1, Right);
4326       buildTree_rec(Left, Depth + 1, {TE, 0});
4327       buildTree_rec(Right, Depth + 1, {TE, 1});
4328       return;
4329     }
4330     case Instruction::Select:
4331     case Instruction::FNeg:
4332     case Instruction::Add:
4333     case Instruction::FAdd:
4334     case Instruction::Sub:
4335     case Instruction::FSub:
4336     case Instruction::Mul:
4337     case Instruction::FMul:
4338     case Instruction::UDiv:
4339     case Instruction::SDiv:
4340     case Instruction::FDiv:
4341     case Instruction::URem:
4342     case Instruction::SRem:
4343     case Instruction::FRem:
4344     case Instruction::Shl:
4345     case Instruction::LShr:
4346     case Instruction::AShr:
4347     case Instruction::And:
4348     case Instruction::Or:
4349     case Instruction::Xor: {
4350       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4351                                    ReuseShuffleIndicies);
4352       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4353 
4354       // Sort operands of the instructions so that each side is more likely to
4355       // have the same opcode.
4356       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4357         ValueList Left, Right;
4358         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4359         TE->setOperand(0, Left);
4360         TE->setOperand(1, Right);
4361         buildTree_rec(Left, Depth + 1, {TE, 0});
4362         buildTree_rec(Right, Depth + 1, {TE, 1});
4363         return;
4364       }
4365 
4366       TE->setOperandsInOrder();
4367       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4368         ValueList Operands;
4369         // Prepare the operand vector.
4370         for (Value *V : VL)
4371           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4372 
4373         buildTree_rec(Operands, Depth + 1, {TE, i});
4374       }
4375       return;
4376     }
4377     case Instruction::GetElementPtr: {
4378       // We don't combine GEPs with complicated (nested) indexing.
4379       for (Value *V : VL) {
4380         if (cast<Instruction>(V)->getNumOperands() != 2) {
4381           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4382           BS.cancelScheduling(VL, VL0);
4383           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4384                        ReuseShuffleIndicies);
4385           return;
4386         }
4387       }
4388 
4389       // We can't combine several GEPs into one vector if they operate on
4390       // different types.
4391       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4392       for (Value *V : VL) {
4393         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4394         if (Ty0 != CurTy) {
4395           LLVM_DEBUG(dbgs()
4396                      << "SLP: not-vectorizable GEP (different types).\n");
4397           BS.cancelScheduling(VL, VL0);
4398           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4399                        ReuseShuffleIndicies);
4400           return;
4401         }
4402       }
4403 
4404       // We don't combine GEPs with non-constant indexes.
4405       Type *Ty1 = VL0->getOperand(1)->getType();
4406       for (Value *V : VL) {
4407         auto Op = cast<Instruction>(V)->getOperand(1);
4408         if (!isa<ConstantInt>(Op) ||
4409             (Op->getType() != Ty1 &&
4410              Op->getType()->getScalarSizeInBits() >
4411                  DL->getIndexSizeInBits(
4412                      V->getType()->getPointerAddressSpace()))) {
4413           LLVM_DEBUG(dbgs()
4414                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4415           BS.cancelScheduling(VL, VL0);
4416           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4417                        ReuseShuffleIndicies);
4418           return;
4419         }
4420       }
4421 
4422       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4423                                    ReuseShuffleIndicies);
4424       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4425       SmallVector<ValueList, 2> Operands(2);
4426       // Prepare the operand vector for pointer operands.
4427       for (Value *V : VL)
4428         Operands.front().push_back(
4429             cast<GetElementPtrInst>(V)->getPointerOperand());
4430       TE->setOperand(0, Operands.front());
4431       // Need to cast all indices to the same type before vectorization to
4432       // avoid crash.
4433       // Required to be able to find correct matches between different gather
4434       // nodes and reuse the vectorized values rather than trying to gather them
4435       // again.
4436       int IndexIdx = 1;
4437       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4438       Type *Ty = all_of(VL,
4439                         [VL0Ty, IndexIdx](Value *V) {
4440                           return VL0Ty == cast<GetElementPtrInst>(V)
4441                                               ->getOperand(IndexIdx)
4442                                               ->getType();
4443                         })
4444                      ? VL0Ty
4445                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4446                                             ->getPointerOperandType()
4447                                             ->getScalarType());
4448       // Prepare the operand vector.
4449       for (Value *V : VL) {
4450         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4451         auto *CI = cast<ConstantInt>(Op);
4452         Operands.back().push_back(ConstantExpr::getIntegerCast(
4453             CI, Ty, CI->getValue().isSignBitSet()));
4454       }
4455       TE->setOperand(IndexIdx, Operands.back());
4456 
4457       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4458         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4459       return;
4460     }
4461     case Instruction::Store: {
4462       // Check if the stores are consecutive or if we need to swizzle them.
4463       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4464       // Avoid types that are padded when being allocated as scalars, while
4465       // being packed together in a vector (such as i1).
4466       if (DL->getTypeSizeInBits(ScalarTy) !=
4467           DL->getTypeAllocSizeInBits(ScalarTy)) {
4468         BS.cancelScheduling(VL, VL0);
4469         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4470                      ReuseShuffleIndicies);
4471         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4472         return;
4473       }
4474       // Make sure all stores in the bundle are simple - we can't vectorize
4475       // atomic or volatile stores.
4476       SmallVector<Value *, 4> PointerOps(VL.size());
4477       ValueList Operands(VL.size());
4478       auto POIter = PointerOps.begin();
4479       auto OIter = Operands.begin();
4480       for (Value *V : VL) {
4481         auto *SI = cast<StoreInst>(V);
4482         if (!SI->isSimple()) {
4483           BS.cancelScheduling(VL, VL0);
4484           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4485                        ReuseShuffleIndicies);
4486           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4487           return;
4488         }
4489         *POIter = SI->getPointerOperand();
4490         *OIter = SI->getValueOperand();
4491         ++POIter;
4492         ++OIter;
4493       }
4494 
4495       OrdersType CurrentOrder;
4496       // Check the order of pointer operands.
4497       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4498         Value *Ptr0;
4499         Value *PtrN;
4500         if (CurrentOrder.empty()) {
4501           Ptr0 = PointerOps.front();
4502           PtrN = PointerOps.back();
4503         } else {
4504           Ptr0 = PointerOps[CurrentOrder.front()];
4505           PtrN = PointerOps[CurrentOrder.back()];
4506         }
4507         Optional<int> Dist =
4508             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4509         // Check that the sorted pointer operands are consecutive.
4510         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4511           if (CurrentOrder.empty()) {
4512             // Original stores are consecutive and does not require reordering.
4513             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4514                                          UserTreeIdx, ReuseShuffleIndicies);
4515             TE->setOperandsInOrder();
4516             buildTree_rec(Operands, Depth + 1, {TE, 0});
4517             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4518           } else {
4519             fixupOrderingIndices(CurrentOrder);
4520             TreeEntry *TE =
4521                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4522                              ReuseShuffleIndicies, CurrentOrder);
4523             TE->setOperandsInOrder();
4524             buildTree_rec(Operands, Depth + 1, {TE, 0});
4525             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4526           }
4527           return;
4528         }
4529       }
4530 
4531       BS.cancelScheduling(VL, VL0);
4532       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4533                    ReuseShuffleIndicies);
4534       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4535       return;
4536     }
4537     case Instruction::Call: {
4538       // Check if the calls are all to the same vectorizable intrinsic or
4539       // library function.
4540       CallInst *CI = cast<CallInst>(VL0);
4541       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4542 
4543       VFShape Shape = VFShape::get(
4544           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4545           false /*HasGlobalPred*/);
4546       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4547 
4548       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4549         BS.cancelScheduling(VL, VL0);
4550         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4551                      ReuseShuffleIndicies);
4552         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4553         return;
4554       }
4555       Function *F = CI->getCalledFunction();
4556       unsigned NumArgs = CI->arg_size();
4557       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4558       for (unsigned j = 0; j != NumArgs; ++j)
4559         if (hasVectorInstrinsicScalarOpd(ID, j))
4560           ScalarArgs[j] = CI->getArgOperand(j);
4561       for (Value *V : VL) {
4562         CallInst *CI2 = dyn_cast<CallInst>(V);
4563         if (!CI2 || CI2->getCalledFunction() != F ||
4564             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4565             (VecFunc &&
4566              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4567             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4568           BS.cancelScheduling(VL, VL0);
4569           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4570                        ReuseShuffleIndicies);
4571           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4572                             << "\n");
4573           return;
4574         }
4575         // Some intrinsics have scalar arguments and should be same in order for
4576         // them to be vectorized.
4577         for (unsigned j = 0; j != NumArgs; ++j) {
4578           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4579             Value *A1J = CI2->getArgOperand(j);
4580             if (ScalarArgs[j] != A1J) {
4581               BS.cancelScheduling(VL, VL0);
4582               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4583                            ReuseShuffleIndicies);
4584               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4585                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4586                                 << "\n");
4587               return;
4588             }
4589           }
4590         }
4591         // Verify that the bundle operands are identical between the two calls.
4592         if (CI->hasOperandBundles() &&
4593             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4594                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4595                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4596           BS.cancelScheduling(VL, VL0);
4597           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4598                        ReuseShuffleIndicies);
4599           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4600                             << *CI << "!=" << *V << '\n');
4601           return;
4602         }
4603       }
4604 
4605       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4606                                    ReuseShuffleIndicies);
4607       TE->setOperandsInOrder();
4608       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4609         // For scalar operands no need to to create an entry since no need to
4610         // vectorize it.
4611         if (hasVectorInstrinsicScalarOpd(ID, i))
4612           continue;
4613         ValueList Operands;
4614         // Prepare the operand vector.
4615         for (Value *V : VL) {
4616           auto *CI2 = cast<CallInst>(V);
4617           Operands.push_back(CI2->getArgOperand(i));
4618         }
4619         buildTree_rec(Operands, Depth + 1, {TE, i});
4620       }
4621       return;
4622     }
4623     case Instruction::ShuffleVector: {
4624       // If this is not an alternate sequence of opcode like add-sub
4625       // then do not vectorize this instruction.
4626       if (!S.isAltShuffle()) {
4627         BS.cancelScheduling(VL, VL0);
4628         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4629                      ReuseShuffleIndicies);
4630         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4631         return;
4632       }
4633       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4634                                    ReuseShuffleIndicies);
4635       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4636 
4637       // Reorder operands if reordering would enable vectorization.
4638       auto *CI = dyn_cast<CmpInst>(VL0);
4639       if (isa<BinaryOperator>(VL0) || CI) {
4640         ValueList Left, Right;
4641         if (!CI || all_of(VL, [](Value *V) {
4642               return cast<CmpInst>(V)->isCommutative();
4643             })) {
4644           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4645         } else {
4646           CmpInst::Predicate P0 = CI->getPredicate();
4647           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4648           assert(P0 != AltP0 &&
4649                  "Expected different main/alternate predicates.");
4650           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4651           Value *BaseOp0 = VL0->getOperand(0);
4652           Value *BaseOp1 = VL0->getOperand(1);
4653           // Collect operands - commute if it uses the swapped predicate or
4654           // alternate operation.
4655           for (Value *V : VL) {
4656             auto *Cmp = cast<CmpInst>(V);
4657             Value *LHS = Cmp->getOperand(0);
4658             Value *RHS = Cmp->getOperand(1);
4659             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4660             if (P0 == AltP0Swapped) {
4661               if (CI != Cmp && S.AltOp != Cmp &&
4662                   ((P0 == CurrentPred &&
4663                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4664                    (AltP0 == CurrentPred &&
4665                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4666                 std::swap(LHS, RHS);
4667             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4668               std::swap(LHS, RHS);
4669             }
4670             Left.push_back(LHS);
4671             Right.push_back(RHS);
4672           }
4673         }
4674         TE->setOperand(0, Left);
4675         TE->setOperand(1, Right);
4676         buildTree_rec(Left, Depth + 1, {TE, 0});
4677         buildTree_rec(Right, Depth + 1, {TE, 1});
4678         return;
4679       }
4680 
4681       TE->setOperandsInOrder();
4682       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4683         ValueList Operands;
4684         // Prepare the operand vector.
4685         for (Value *V : VL)
4686           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4687 
4688         buildTree_rec(Operands, Depth + 1, {TE, i});
4689       }
4690       return;
4691     }
4692     default:
4693       BS.cancelScheduling(VL, VL0);
4694       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4695                    ReuseShuffleIndicies);
4696       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4697       return;
4698   }
4699 }
4700 
4701 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4702   unsigned N = 1;
4703   Type *EltTy = T;
4704 
4705   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4706          isa<VectorType>(EltTy)) {
4707     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4708       // Check that struct is homogeneous.
4709       for (const auto *Ty : ST->elements())
4710         if (Ty != *ST->element_begin())
4711           return 0;
4712       N *= ST->getNumElements();
4713       EltTy = *ST->element_begin();
4714     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4715       N *= AT->getNumElements();
4716       EltTy = AT->getElementType();
4717     } else {
4718       auto *VT = cast<FixedVectorType>(EltTy);
4719       N *= VT->getNumElements();
4720       EltTy = VT->getElementType();
4721     }
4722   }
4723 
4724   if (!isValidElementType(EltTy))
4725     return 0;
4726   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4727   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4728     return 0;
4729   return N;
4730 }
4731 
4732 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4733                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4734   const auto *It = find_if(VL, [](Value *V) {
4735     return isa<ExtractElementInst, ExtractValueInst>(V);
4736   });
4737   assert(It != VL.end() && "Expected at least one extract instruction.");
4738   auto *E0 = cast<Instruction>(*It);
4739   assert(all_of(VL,
4740                 [](Value *V) {
4741                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4742                       V);
4743                 }) &&
4744          "Invalid opcode");
4745   // Check if all of the extracts come from the same vector and from the
4746   // correct offset.
4747   Value *Vec = E0->getOperand(0);
4748 
4749   CurrentOrder.clear();
4750 
4751   // We have to extract from a vector/aggregate with the same number of elements.
4752   unsigned NElts;
4753   if (E0->getOpcode() == Instruction::ExtractValue) {
4754     const DataLayout &DL = E0->getModule()->getDataLayout();
4755     NElts = canMapToVector(Vec->getType(), DL);
4756     if (!NElts)
4757       return false;
4758     // Check if load can be rewritten as load of vector.
4759     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4760     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4761       return false;
4762   } else {
4763     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4764   }
4765 
4766   if (NElts != VL.size())
4767     return false;
4768 
4769   // Check that all of the indices extract from the correct offset.
4770   bool ShouldKeepOrder = true;
4771   unsigned E = VL.size();
4772   // Assign to all items the initial value E + 1 so we can check if the extract
4773   // instruction index was used already.
4774   // Also, later we can check that all the indices are used and we have a
4775   // consecutive access in the extract instructions, by checking that no
4776   // element of CurrentOrder still has value E + 1.
4777   CurrentOrder.assign(E, E);
4778   unsigned I = 0;
4779   for (; I < E; ++I) {
4780     auto *Inst = dyn_cast<Instruction>(VL[I]);
4781     if (!Inst)
4782       continue;
4783     if (Inst->getOperand(0) != Vec)
4784       break;
4785     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4786       if (isa<UndefValue>(EE->getIndexOperand()))
4787         continue;
4788     Optional<unsigned> Idx = getExtractIndex(Inst);
4789     if (!Idx)
4790       break;
4791     const unsigned ExtIdx = *Idx;
4792     if (ExtIdx != I) {
4793       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4794         break;
4795       ShouldKeepOrder = false;
4796       CurrentOrder[ExtIdx] = I;
4797     } else {
4798       if (CurrentOrder[I] != E)
4799         break;
4800       CurrentOrder[I] = I;
4801     }
4802   }
4803   if (I < E) {
4804     CurrentOrder.clear();
4805     return false;
4806   }
4807   if (ShouldKeepOrder)
4808     CurrentOrder.clear();
4809 
4810   return ShouldKeepOrder;
4811 }
4812 
4813 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4814                                     ArrayRef<Value *> VectorizedVals) const {
4815   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4816          all_of(I->users(), [this](User *U) {
4817            return ScalarToTreeEntry.count(U) > 0 ||
4818                   isVectorLikeInstWithConstOps(U) ||
4819                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4820          });
4821 }
4822 
4823 static std::pair<InstructionCost, InstructionCost>
4824 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4825                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4826   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4827 
4828   // Calculate the cost of the scalar and vector calls.
4829   SmallVector<Type *, 4> VecTys;
4830   for (Use &Arg : CI->args())
4831     VecTys.push_back(
4832         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4833   FastMathFlags FMF;
4834   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4835     FMF = FPCI->getFastMathFlags();
4836   SmallVector<const Value *> Arguments(CI->args());
4837   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4838                                     dyn_cast<IntrinsicInst>(CI));
4839   auto IntrinsicCost =
4840     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4841 
4842   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4843                                      VecTy->getNumElements())),
4844                             false /*HasGlobalPred*/);
4845   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4846   auto LibCost = IntrinsicCost;
4847   if (!CI->isNoBuiltin() && VecFunc) {
4848     // Calculate the cost of the vector library call.
4849     // If the corresponding vector call is cheaper, return its cost.
4850     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4851                                     TTI::TCK_RecipThroughput);
4852   }
4853   return {IntrinsicCost, LibCost};
4854 }
4855 
4856 /// Compute the cost of creating a vector of type \p VecTy containing the
4857 /// extracted values from \p VL.
4858 static InstructionCost
4859 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4860                    TargetTransformInfo::ShuffleKind ShuffleKind,
4861                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4862   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4863 
4864   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4865       VecTy->getNumElements() < NumOfParts)
4866     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4867 
4868   bool AllConsecutive = true;
4869   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4870   unsigned Idx = -1;
4871   InstructionCost Cost = 0;
4872 
4873   // Process extracts in blocks of EltsPerVector to check if the source vector
4874   // operand can be re-used directly. If not, add the cost of creating a shuffle
4875   // to extract the values into a vector register.
4876   for (auto *V : VL) {
4877     ++Idx;
4878 
4879     // Need to exclude undefs from analysis.
4880     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4881       continue;
4882 
4883     // Reached the start of a new vector registers.
4884     if (Idx % EltsPerVector == 0) {
4885       AllConsecutive = true;
4886       continue;
4887     }
4888 
4889     // Check all extracts for a vector register on the target directly
4890     // extract values in order.
4891     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4892     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4893       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4894       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4895                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4896     }
4897 
4898     if (AllConsecutive)
4899       continue;
4900 
4901     // Skip all indices, except for the last index per vector block.
4902     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4903       continue;
4904 
4905     // If we have a series of extracts which are not consecutive and hence
4906     // cannot re-use the source vector register directly, compute the shuffle
4907     // cost to extract the a vector with EltsPerVector elements.
4908     Cost += TTI.getShuffleCost(
4909         TargetTransformInfo::SK_PermuteSingleSrc,
4910         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4911   }
4912   return Cost;
4913 }
4914 
4915 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4916 /// operations operands.
4917 static void
4918 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4919                       ArrayRef<int> ReusesIndices,
4920                       const function_ref<bool(Instruction *)> IsAltOp,
4921                       SmallVectorImpl<int> &Mask,
4922                       SmallVectorImpl<Value *> *OpScalars = nullptr,
4923                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
4924   unsigned Sz = VL.size();
4925   Mask.assign(Sz, UndefMaskElem);
4926   SmallVector<int> OrderMask;
4927   if (!ReorderIndices.empty())
4928     inversePermutation(ReorderIndices, OrderMask);
4929   for (unsigned I = 0; I < Sz; ++I) {
4930     unsigned Idx = I;
4931     if (!ReorderIndices.empty())
4932       Idx = OrderMask[I];
4933     auto *OpInst = cast<Instruction>(VL[Idx]);
4934     if (IsAltOp(OpInst)) {
4935       Mask[I] = Sz + Idx;
4936       if (AltScalars)
4937         AltScalars->push_back(OpInst);
4938     } else {
4939       Mask[I] = Idx;
4940       if (OpScalars)
4941         OpScalars->push_back(OpInst);
4942     }
4943   }
4944   if (!ReusesIndices.empty()) {
4945     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4946     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4947       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4948     });
4949     Mask.swap(NewMask);
4950   }
4951 }
4952 
4953 /// Checks if the specified instruction \p I is an alternate operation for the
4954 /// given \p MainOp and \p AltOp instructions.
4955 static bool isAlternateInstruction(const Instruction *I,
4956                                    const Instruction *MainOp,
4957                                    const Instruction *AltOp) {
4958   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
4959     auto *AltCI0 = cast<CmpInst>(AltOp);
4960     auto *CI = cast<CmpInst>(I);
4961     CmpInst::Predicate P0 = CI0->getPredicate();
4962     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
4963     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
4964     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4965     CmpInst::Predicate CurrentPred = CI->getPredicate();
4966     if (P0 == AltP0Swapped)
4967       return I == AltCI0 ||
4968              (I != MainOp &&
4969               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
4970                                    CI->getOperand(0), CI->getOperand(1)));
4971     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
4972   }
4973   return I->getOpcode() == AltOp->getOpcode();
4974 }
4975 
4976 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4977                                       ArrayRef<Value *> VectorizedVals) {
4978   ArrayRef<Value*> VL = E->Scalars;
4979 
4980   Type *ScalarTy = VL[0]->getType();
4981   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4982     ScalarTy = SI->getValueOperand()->getType();
4983   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4984     ScalarTy = CI->getOperand(0)->getType();
4985   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4986     ScalarTy = IE->getOperand(1)->getType();
4987   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4988   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4989 
4990   // If we have computed a smaller type for the expression, update VecTy so
4991   // that the costs will be accurate.
4992   if (MinBWs.count(VL[0]))
4993     VecTy = FixedVectorType::get(
4994         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4995   unsigned EntryVF = E->getVectorFactor();
4996   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
4997 
4998   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4999   // FIXME: it tries to fix a problem with MSVC buildbots.
5000   TargetTransformInfo &TTIRef = *TTI;
5001   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5002                                VectorizedVals, E](InstructionCost &Cost) {
5003     DenseMap<Value *, int> ExtractVectorsTys;
5004     SmallPtrSet<Value *, 4> CheckedExtracts;
5005     for (auto *V : VL) {
5006       if (isa<UndefValue>(V))
5007         continue;
5008       // If all users of instruction are going to be vectorized and this
5009       // instruction itself is not going to be vectorized, consider this
5010       // instruction as dead and remove its cost from the final cost of the
5011       // vectorized tree.
5012       // Also, avoid adjusting the cost for extractelements with multiple uses
5013       // in different graph entries.
5014       const TreeEntry *VE = getTreeEntry(V);
5015       if (!CheckedExtracts.insert(V).second ||
5016           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5017           (VE && VE != E))
5018         continue;
5019       auto *EE = cast<ExtractElementInst>(V);
5020       Optional<unsigned> EEIdx = getExtractIndex(EE);
5021       if (!EEIdx)
5022         continue;
5023       unsigned Idx = *EEIdx;
5024       if (TTIRef.getNumberOfParts(VecTy) !=
5025           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5026         auto It =
5027             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5028         It->getSecond() = std::min<int>(It->second, Idx);
5029       }
5030       // Take credit for instruction that will become dead.
5031       if (EE->hasOneUse()) {
5032         Instruction *Ext = EE->user_back();
5033         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5034             all_of(Ext->users(),
5035                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5036           // Use getExtractWithExtendCost() to calculate the cost of
5037           // extractelement/ext pair.
5038           Cost -=
5039               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5040                                               EE->getVectorOperandType(), Idx);
5041           // Add back the cost of s|zext which is subtracted separately.
5042           Cost += TTIRef.getCastInstrCost(
5043               Ext->getOpcode(), Ext->getType(), EE->getType(),
5044               TTI::getCastContextHint(Ext), CostKind, Ext);
5045           continue;
5046         }
5047       }
5048       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5049                                         EE->getVectorOperandType(), Idx);
5050     }
5051     // Add a cost for subvector extracts/inserts if required.
5052     for (const auto &Data : ExtractVectorsTys) {
5053       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5054       unsigned NumElts = VecTy->getNumElements();
5055       if (Data.second % NumElts == 0)
5056         continue;
5057       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5058         unsigned Idx = (Data.second / NumElts) * NumElts;
5059         unsigned EENumElts = EEVTy->getNumElements();
5060         if (Idx + NumElts <= EENumElts) {
5061           Cost +=
5062               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5063                                     EEVTy, None, Idx, VecTy);
5064         } else {
5065           // Need to round up the subvector type vectorization factor to avoid a
5066           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5067           // <= EENumElts.
5068           auto *SubVT =
5069               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5070           Cost +=
5071               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5072                                     EEVTy, None, Idx, SubVT);
5073         }
5074       } else {
5075         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5076                                       VecTy, None, 0, EEVTy);
5077       }
5078     }
5079   };
5080   if (E->State == TreeEntry::NeedToGather) {
5081     if (allConstant(VL))
5082       return 0;
5083     if (isa<InsertElementInst>(VL[0]))
5084       return InstructionCost::getInvalid();
5085     SmallVector<int> Mask;
5086     SmallVector<const TreeEntry *> Entries;
5087     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5088         isGatherShuffledEntry(E, Mask, Entries);
5089     if (Shuffle.hasValue()) {
5090       InstructionCost GatherCost = 0;
5091       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5092         // Perfect match in the graph, will reuse the previously vectorized
5093         // node. Cost is 0.
5094         LLVM_DEBUG(
5095             dbgs()
5096             << "SLP: perfect diamond match for gather bundle that starts with "
5097             << *VL.front() << ".\n");
5098         if (NeedToShuffleReuses)
5099           GatherCost =
5100               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5101                                   FinalVecTy, E->ReuseShuffleIndices);
5102       } else {
5103         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5104                           << " entries for bundle that starts with "
5105                           << *VL.front() << ".\n");
5106         // Detected that instead of gather we can emit a shuffle of single/two
5107         // previously vectorized nodes. Add the cost of the permutation rather
5108         // than gather.
5109         ::addMask(Mask, E->ReuseShuffleIndices);
5110         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5111       }
5112       return GatherCost;
5113     }
5114     if ((E->getOpcode() == Instruction::ExtractElement ||
5115          all_of(E->Scalars,
5116                 [](Value *V) {
5117                   return isa<ExtractElementInst, UndefValue>(V);
5118                 })) &&
5119         allSameType(VL)) {
5120       // Check that gather of extractelements can be represented as just a
5121       // shuffle of a single/two vectors the scalars are extracted from.
5122       SmallVector<int> Mask;
5123       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5124           isFixedVectorShuffle(VL, Mask);
5125       if (ShuffleKind.hasValue()) {
5126         // Found the bunch of extractelement instructions that must be gathered
5127         // into a vector and can be represented as a permutation elements in a
5128         // single input vector or of 2 input vectors.
5129         InstructionCost Cost =
5130             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5131         AdjustExtractsCost(Cost);
5132         if (NeedToShuffleReuses)
5133           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5134                                       FinalVecTy, E->ReuseShuffleIndices);
5135         return Cost;
5136       }
5137     }
5138     if (isSplat(VL)) {
5139       // Found the broadcasting of the single scalar, calculate the cost as the
5140       // broadcast.
5141       assert(VecTy == FinalVecTy &&
5142              "No reused scalars expected for broadcast.");
5143       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
5144     }
5145     InstructionCost ReuseShuffleCost = 0;
5146     if (NeedToShuffleReuses)
5147       ReuseShuffleCost = TTI->getShuffleCost(
5148           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5149     // Improve gather cost for gather of loads, if we can group some of the
5150     // loads into vector loads.
5151     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5152         !E->isAltShuffle()) {
5153       BoUpSLP::ValueSet VectorizedLoads;
5154       unsigned StartIdx = 0;
5155       unsigned VF = VL.size() / 2;
5156       unsigned VectorizedCnt = 0;
5157       unsigned ScatterVectorizeCnt = 0;
5158       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5159       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5160         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5161              Cnt += VF) {
5162           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5163           if (!VectorizedLoads.count(Slice.front()) &&
5164               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5165             SmallVector<Value *> PointerOps;
5166             OrdersType CurrentOrder;
5167             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5168                                               *SE, CurrentOrder, PointerOps);
5169             switch (LS) {
5170             case LoadsState::Vectorize:
5171             case LoadsState::ScatterVectorize:
5172               // Mark the vectorized loads so that we don't vectorize them
5173               // again.
5174               if (LS == LoadsState::Vectorize)
5175                 ++VectorizedCnt;
5176               else
5177                 ++ScatterVectorizeCnt;
5178               VectorizedLoads.insert(Slice.begin(), Slice.end());
5179               // If we vectorized initial block, no need to try to vectorize it
5180               // again.
5181               if (Cnt == StartIdx)
5182                 StartIdx += VF;
5183               break;
5184             case LoadsState::Gather:
5185               break;
5186             }
5187           }
5188         }
5189         // Check if the whole array was vectorized already - exit.
5190         if (StartIdx >= VL.size())
5191           break;
5192         // Found vectorizable parts - exit.
5193         if (!VectorizedLoads.empty())
5194           break;
5195       }
5196       if (!VectorizedLoads.empty()) {
5197         InstructionCost GatherCost = 0;
5198         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5199         bool NeedInsertSubvectorAnalysis =
5200             !NumParts || (VL.size() / VF) > NumParts;
5201         // Get the cost for gathered loads.
5202         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5203           if (VectorizedLoads.contains(VL[I]))
5204             continue;
5205           GatherCost += getGatherCost(VL.slice(I, VF));
5206         }
5207         // The cost for vectorized loads.
5208         InstructionCost ScalarsCost = 0;
5209         for (Value *V : VectorizedLoads) {
5210           auto *LI = cast<LoadInst>(V);
5211           ScalarsCost += TTI->getMemoryOpCost(
5212               Instruction::Load, LI->getType(), LI->getAlign(),
5213               LI->getPointerAddressSpace(), CostKind, LI);
5214         }
5215         auto *LI = cast<LoadInst>(E->getMainOp());
5216         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5217         Align Alignment = LI->getAlign();
5218         GatherCost +=
5219             VectorizedCnt *
5220             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5221                                  LI->getPointerAddressSpace(), CostKind, LI);
5222         GatherCost += ScatterVectorizeCnt *
5223                       TTI->getGatherScatterOpCost(
5224                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5225                           /*VariableMask=*/false, Alignment, CostKind, LI);
5226         if (NeedInsertSubvectorAnalysis) {
5227           // Add the cost for the subvectors insert.
5228           for (int I = VF, E = VL.size(); I < E; I += VF)
5229             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5230                                               None, I, LoadTy);
5231         }
5232         return ReuseShuffleCost + GatherCost - ScalarsCost;
5233       }
5234     }
5235     return ReuseShuffleCost + getGatherCost(VL);
5236   }
5237   InstructionCost CommonCost = 0;
5238   SmallVector<int> Mask;
5239   if (!E->ReorderIndices.empty()) {
5240     SmallVector<int> NewMask;
5241     if (E->getOpcode() == Instruction::Store) {
5242       // For stores the order is actually a mask.
5243       NewMask.resize(E->ReorderIndices.size());
5244       copy(E->ReorderIndices, NewMask.begin());
5245     } else {
5246       inversePermutation(E->ReorderIndices, NewMask);
5247     }
5248     ::addMask(Mask, NewMask);
5249   }
5250   if (NeedToShuffleReuses)
5251     ::addMask(Mask, E->ReuseShuffleIndices);
5252   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5253     CommonCost =
5254         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5255   assert((E->State == TreeEntry::Vectorize ||
5256           E->State == TreeEntry::ScatterVectorize) &&
5257          "Unhandled state");
5258   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5259   Instruction *VL0 = E->getMainOp();
5260   unsigned ShuffleOrOp =
5261       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5262   switch (ShuffleOrOp) {
5263     case Instruction::PHI:
5264       return 0;
5265 
5266     case Instruction::ExtractValue:
5267     case Instruction::ExtractElement: {
5268       // The common cost of removal ExtractElement/ExtractValue instructions +
5269       // the cost of shuffles, if required to resuffle the original vector.
5270       if (NeedToShuffleReuses) {
5271         unsigned Idx = 0;
5272         for (unsigned I : E->ReuseShuffleIndices) {
5273           if (ShuffleOrOp == Instruction::ExtractElement) {
5274             auto *EE = cast<ExtractElementInst>(VL[I]);
5275             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5276                                                   EE->getVectorOperandType(),
5277                                                   *getExtractIndex(EE));
5278           } else {
5279             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5280                                                   VecTy, Idx);
5281             ++Idx;
5282           }
5283         }
5284         Idx = EntryVF;
5285         for (Value *V : VL) {
5286           if (ShuffleOrOp == Instruction::ExtractElement) {
5287             auto *EE = cast<ExtractElementInst>(V);
5288             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5289                                                   EE->getVectorOperandType(),
5290                                                   *getExtractIndex(EE));
5291           } else {
5292             --Idx;
5293             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5294                                                   VecTy, Idx);
5295           }
5296         }
5297       }
5298       if (ShuffleOrOp == Instruction::ExtractValue) {
5299         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5300           auto *EI = cast<Instruction>(VL[I]);
5301           // Take credit for instruction that will become dead.
5302           if (EI->hasOneUse()) {
5303             Instruction *Ext = EI->user_back();
5304             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5305                 all_of(Ext->users(),
5306                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5307               // Use getExtractWithExtendCost() to calculate the cost of
5308               // extractelement/ext pair.
5309               CommonCost -= TTI->getExtractWithExtendCost(
5310                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5311               // Add back the cost of s|zext which is subtracted separately.
5312               CommonCost += TTI->getCastInstrCost(
5313                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5314                   TTI::getCastContextHint(Ext), CostKind, Ext);
5315               continue;
5316             }
5317           }
5318           CommonCost -=
5319               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5320         }
5321       } else {
5322         AdjustExtractsCost(CommonCost);
5323       }
5324       return CommonCost;
5325     }
5326     case Instruction::InsertElement: {
5327       assert(E->ReuseShuffleIndices.empty() &&
5328              "Unique insertelements only are expected.");
5329       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5330 
5331       unsigned const NumElts = SrcVecTy->getNumElements();
5332       unsigned const NumScalars = VL.size();
5333       APInt DemandedElts = APInt::getZero(NumElts);
5334       // TODO: Add support for Instruction::InsertValue.
5335       SmallVector<int> Mask;
5336       if (!E->ReorderIndices.empty()) {
5337         inversePermutation(E->ReorderIndices, Mask);
5338         Mask.append(NumElts - NumScalars, UndefMaskElem);
5339       } else {
5340         Mask.assign(NumElts, UndefMaskElem);
5341         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5342       }
5343       unsigned Offset = *getInsertIndex(VL0);
5344       bool IsIdentity = true;
5345       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5346       Mask.swap(PrevMask);
5347       for (unsigned I = 0; I < NumScalars; ++I) {
5348         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5349         DemandedElts.setBit(InsertIdx);
5350         IsIdentity &= InsertIdx - Offset == I;
5351         Mask[InsertIdx - Offset] = I;
5352       }
5353       assert(Offset < NumElts && "Failed to find vector index offset");
5354 
5355       InstructionCost Cost = 0;
5356       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5357                                             /*Insert*/ true, /*Extract*/ false);
5358 
5359       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5360         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5361         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5362         Cost += TTI->getShuffleCost(
5363             TargetTransformInfo::SK_PermuteSingleSrc,
5364             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5365       } else if (!IsIdentity) {
5366         auto *FirstInsert =
5367             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5368               return !is_contained(E->Scalars,
5369                                    cast<Instruction>(V)->getOperand(0));
5370             }));
5371         if (isUndefVector(FirstInsert->getOperand(0))) {
5372           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5373         } else {
5374           SmallVector<int> InsertMask(NumElts);
5375           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5376           for (unsigned I = 0; I < NumElts; I++) {
5377             if (Mask[I] != UndefMaskElem)
5378               InsertMask[Offset + I] = NumElts + I;
5379           }
5380           Cost +=
5381               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5382         }
5383       }
5384 
5385       return Cost;
5386     }
5387     case Instruction::ZExt:
5388     case Instruction::SExt:
5389     case Instruction::FPToUI:
5390     case Instruction::FPToSI:
5391     case Instruction::FPExt:
5392     case Instruction::PtrToInt:
5393     case Instruction::IntToPtr:
5394     case Instruction::SIToFP:
5395     case Instruction::UIToFP:
5396     case Instruction::Trunc:
5397     case Instruction::FPTrunc:
5398     case Instruction::BitCast: {
5399       Type *SrcTy = VL0->getOperand(0)->getType();
5400       InstructionCost ScalarEltCost =
5401           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5402                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5403       if (NeedToShuffleReuses) {
5404         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5405       }
5406 
5407       // Calculate the cost of this instruction.
5408       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5409 
5410       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5411       InstructionCost VecCost = 0;
5412       // Check if the values are candidates to demote.
5413       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5414         VecCost = CommonCost + TTI->getCastInstrCost(
5415                                    E->getOpcode(), VecTy, SrcVecTy,
5416                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5417       }
5418       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5419       return VecCost - ScalarCost;
5420     }
5421     case Instruction::FCmp:
5422     case Instruction::ICmp:
5423     case Instruction::Select: {
5424       // Calculate the cost of this instruction.
5425       InstructionCost ScalarEltCost =
5426           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5427                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5428       if (NeedToShuffleReuses) {
5429         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5430       }
5431       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5432       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5433 
5434       // Check if all entries in VL are either compares or selects with compares
5435       // as condition that have the same predicates.
5436       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5437       bool First = true;
5438       for (auto *V : VL) {
5439         CmpInst::Predicate CurrentPred;
5440         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5441         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5442              !match(V, MatchCmp)) ||
5443             (!First && VecPred != CurrentPred)) {
5444           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5445           break;
5446         }
5447         First = false;
5448         VecPred = CurrentPred;
5449       }
5450 
5451       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5452           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5453       // Check if it is possible and profitable to use min/max for selects in
5454       // VL.
5455       //
5456       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5457       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5458         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5459                                           {VecTy, VecTy});
5460         InstructionCost IntrinsicCost =
5461             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5462         // If the selects are the only uses of the compares, they will be dead
5463         // and we can adjust the cost by removing their cost.
5464         if (IntrinsicAndUse.second)
5465           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5466                                                    MaskTy, VecPred, CostKind);
5467         VecCost = std::min(VecCost, IntrinsicCost);
5468       }
5469       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5470       return CommonCost + VecCost - ScalarCost;
5471     }
5472     case Instruction::FNeg:
5473     case Instruction::Add:
5474     case Instruction::FAdd:
5475     case Instruction::Sub:
5476     case Instruction::FSub:
5477     case Instruction::Mul:
5478     case Instruction::FMul:
5479     case Instruction::UDiv:
5480     case Instruction::SDiv:
5481     case Instruction::FDiv:
5482     case Instruction::URem:
5483     case Instruction::SRem:
5484     case Instruction::FRem:
5485     case Instruction::Shl:
5486     case Instruction::LShr:
5487     case Instruction::AShr:
5488     case Instruction::And:
5489     case Instruction::Or:
5490     case Instruction::Xor: {
5491       // Certain instructions can be cheaper to vectorize if they have a
5492       // constant second vector operand.
5493       TargetTransformInfo::OperandValueKind Op1VK =
5494           TargetTransformInfo::OK_AnyValue;
5495       TargetTransformInfo::OperandValueKind Op2VK =
5496           TargetTransformInfo::OK_UniformConstantValue;
5497       TargetTransformInfo::OperandValueProperties Op1VP =
5498           TargetTransformInfo::OP_None;
5499       TargetTransformInfo::OperandValueProperties Op2VP =
5500           TargetTransformInfo::OP_PowerOf2;
5501 
5502       // If all operands are exactly the same ConstantInt then set the
5503       // operand kind to OK_UniformConstantValue.
5504       // If instead not all operands are constants, then set the operand kind
5505       // to OK_AnyValue. If all operands are constants but not the same,
5506       // then set the operand kind to OK_NonUniformConstantValue.
5507       ConstantInt *CInt0 = nullptr;
5508       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5509         const Instruction *I = cast<Instruction>(VL[i]);
5510         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5511         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5512         if (!CInt) {
5513           Op2VK = TargetTransformInfo::OK_AnyValue;
5514           Op2VP = TargetTransformInfo::OP_None;
5515           break;
5516         }
5517         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5518             !CInt->getValue().isPowerOf2())
5519           Op2VP = TargetTransformInfo::OP_None;
5520         if (i == 0) {
5521           CInt0 = CInt;
5522           continue;
5523         }
5524         if (CInt0 != CInt)
5525           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5526       }
5527 
5528       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5529       InstructionCost ScalarEltCost =
5530           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5531                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5532       if (NeedToShuffleReuses) {
5533         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5534       }
5535       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5536       InstructionCost VecCost =
5537           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5538                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5539       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5540       return CommonCost + VecCost - ScalarCost;
5541     }
5542     case Instruction::GetElementPtr: {
5543       TargetTransformInfo::OperandValueKind Op1VK =
5544           TargetTransformInfo::OK_AnyValue;
5545       TargetTransformInfo::OperandValueKind Op2VK =
5546           TargetTransformInfo::OK_UniformConstantValue;
5547 
5548       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5549           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5550       if (NeedToShuffleReuses) {
5551         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5552       }
5553       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5554       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5555           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5556       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5557       return CommonCost + VecCost - ScalarCost;
5558     }
5559     case Instruction::Load: {
5560       // Cost of wide load - cost of scalar loads.
5561       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5562       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5563           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5564       if (NeedToShuffleReuses) {
5565         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5566       }
5567       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5568       InstructionCost VecLdCost;
5569       if (E->State == TreeEntry::Vectorize) {
5570         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5571                                          CostKind, VL0);
5572       } else {
5573         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5574         Align CommonAlignment = Alignment;
5575         for (Value *V : VL)
5576           CommonAlignment =
5577               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5578         VecLdCost = TTI->getGatherScatterOpCost(
5579             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5580             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5581       }
5582       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5583       return CommonCost + VecLdCost - ScalarLdCost;
5584     }
5585     case Instruction::Store: {
5586       // We know that we can merge the stores. Calculate the cost.
5587       bool IsReorder = !E->ReorderIndices.empty();
5588       auto *SI =
5589           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5590       Align Alignment = SI->getAlign();
5591       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5592           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5593       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5594       InstructionCost VecStCost = TTI->getMemoryOpCost(
5595           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5596       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5597       return CommonCost + VecStCost - ScalarStCost;
5598     }
5599     case Instruction::Call: {
5600       CallInst *CI = cast<CallInst>(VL0);
5601       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5602 
5603       // Calculate the cost of the scalar and vector calls.
5604       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5605       InstructionCost ScalarEltCost =
5606           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5607       if (NeedToShuffleReuses) {
5608         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5609       }
5610       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5611 
5612       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5613       InstructionCost VecCallCost =
5614           std::min(VecCallCosts.first, VecCallCosts.second);
5615 
5616       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5617                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5618                         << " for " << *CI << "\n");
5619 
5620       return CommonCost + VecCallCost - ScalarCallCost;
5621     }
5622     case Instruction::ShuffleVector: {
5623       assert(E->isAltShuffle() &&
5624              ((Instruction::isBinaryOp(E->getOpcode()) &&
5625                Instruction::isBinaryOp(E->getAltOpcode())) ||
5626               (Instruction::isCast(E->getOpcode()) &&
5627                Instruction::isCast(E->getAltOpcode())) ||
5628               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5629              "Invalid Shuffle Vector Operand");
5630       InstructionCost ScalarCost = 0;
5631       if (NeedToShuffleReuses) {
5632         for (unsigned Idx : E->ReuseShuffleIndices) {
5633           Instruction *I = cast<Instruction>(VL[Idx]);
5634           CommonCost -= TTI->getInstructionCost(I, CostKind);
5635         }
5636         for (Value *V : VL) {
5637           Instruction *I = cast<Instruction>(V);
5638           CommonCost += TTI->getInstructionCost(I, CostKind);
5639         }
5640       }
5641       for (Value *V : VL) {
5642         Instruction *I = cast<Instruction>(V);
5643         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5644         ScalarCost += TTI->getInstructionCost(I, CostKind);
5645       }
5646       // VecCost is equal to sum of the cost of creating 2 vectors
5647       // and the cost of creating shuffle.
5648       InstructionCost VecCost = 0;
5649       // Try to find the previous shuffle node with the same operands and same
5650       // main/alternate ops.
5651       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5652         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5653           if (TE.get() == E)
5654             break;
5655           if (TE->isAltShuffle() &&
5656               ((TE->getOpcode() == E->getOpcode() &&
5657                 TE->getAltOpcode() == E->getAltOpcode()) ||
5658                (TE->getOpcode() == E->getAltOpcode() &&
5659                 TE->getAltOpcode() == E->getOpcode())) &&
5660               TE->hasEqualOperands(*E))
5661             return true;
5662         }
5663         return false;
5664       };
5665       if (TryFindNodeWithEqualOperands()) {
5666         LLVM_DEBUG({
5667           dbgs() << "SLP: diamond match for alternate node found.\n";
5668           E->dump();
5669         });
5670         // No need to add new vector costs here since we're going to reuse
5671         // same main/alternate vector ops, just do different shuffling.
5672       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5673         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5674         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5675                                                CostKind);
5676       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5677         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5678                                           Builder.getInt1Ty(),
5679                                           CI0->getPredicate(), CostKind, VL0);
5680         VecCost += TTI->getCmpSelInstrCost(
5681             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5682             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5683             E->getAltOp());
5684       } else {
5685         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5686         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5687         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5688         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5689         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5690                                         TTI::CastContextHint::None, CostKind);
5691         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5692                                          TTI::CastContextHint::None, CostKind);
5693       }
5694 
5695       SmallVector<int> Mask;
5696       buildShuffleEntryMask(
5697           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5698           [E](Instruction *I) {
5699             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5700             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5701           },
5702           Mask);
5703       CommonCost =
5704           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5705       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5706       return CommonCost + VecCost - ScalarCost;
5707     }
5708     default:
5709       llvm_unreachable("Unknown instruction");
5710   }
5711 }
5712 
5713 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5714   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5715                     << VectorizableTree.size() << " is fully vectorizable .\n");
5716 
5717   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5718     SmallVector<int> Mask;
5719     return TE->State == TreeEntry::NeedToGather &&
5720            !any_of(TE->Scalars,
5721                    [this](Value *V) { return EphValues.contains(V); }) &&
5722            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5723             TE->Scalars.size() < Limit ||
5724             ((TE->getOpcode() == Instruction::ExtractElement ||
5725               all_of(TE->Scalars,
5726                      [](Value *V) {
5727                        return isa<ExtractElementInst, UndefValue>(V);
5728                      })) &&
5729              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5730             (TE->State == TreeEntry::NeedToGather &&
5731              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5732   };
5733 
5734   // We only handle trees of heights 1 and 2.
5735   if (VectorizableTree.size() == 1 &&
5736       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5737        (ForReduction &&
5738         AreVectorizableGathers(VectorizableTree[0].get(),
5739                                VectorizableTree[0]->Scalars.size()) &&
5740         VectorizableTree[0]->getVectorFactor() > 2)))
5741     return true;
5742 
5743   if (VectorizableTree.size() != 2)
5744     return false;
5745 
5746   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5747   // with the second gather nodes if they have less scalar operands rather than
5748   // the initial tree element (may be profitable to shuffle the second gather)
5749   // or they are extractelements, which form shuffle.
5750   SmallVector<int> Mask;
5751   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5752       AreVectorizableGathers(VectorizableTree[1].get(),
5753                              VectorizableTree[0]->Scalars.size()))
5754     return true;
5755 
5756   // Gathering cost would be too much for tiny trees.
5757   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5758       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5759        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5760     return false;
5761 
5762   return true;
5763 }
5764 
5765 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5766                                        TargetTransformInfo *TTI,
5767                                        bool MustMatchOrInst) {
5768   // Look past the root to find a source value. Arbitrarily follow the
5769   // path through operand 0 of any 'or'. Also, peek through optional
5770   // shift-left-by-multiple-of-8-bits.
5771   Value *ZextLoad = Root;
5772   const APInt *ShAmtC;
5773   bool FoundOr = false;
5774   while (!isa<ConstantExpr>(ZextLoad) &&
5775          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5776           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5777            ShAmtC->urem(8) == 0))) {
5778     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5779     ZextLoad = BinOp->getOperand(0);
5780     if (BinOp->getOpcode() == Instruction::Or)
5781       FoundOr = true;
5782   }
5783   // Check if the input is an extended load of the required or/shift expression.
5784   Value *Load;
5785   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5786       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5787     return false;
5788 
5789   // Require that the total load bit width is a legal integer type.
5790   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5791   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5792   Type *SrcTy = Load->getType();
5793   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5794   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5795     return false;
5796 
5797   // Everything matched - assume that we can fold the whole sequence using
5798   // load combining.
5799   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5800              << *(cast<Instruction>(Root)) << "\n");
5801 
5802   return true;
5803 }
5804 
5805 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5806   if (RdxKind != RecurKind::Or)
5807     return false;
5808 
5809   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5810   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5811   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5812                                     /* MatchOr */ false);
5813 }
5814 
5815 bool BoUpSLP::isLoadCombineCandidate() const {
5816   // Peek through a final sequence of stores and check if all operations are
5817   // likely to be load-combined.
5818   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5819   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5820     Value *X;
5821     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5822         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5823       return false;
5824   }
5825   return true;
5826 }
5827 
5828 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5829   // No need to vectorize inserts of gathered values.
5830   if (VectorizableTree.size() == 2 &&
5831       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5832       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5833     return true;
5834 
5835   // We can vectorize the tree if its size is greater than or equal to the
5836   // minimum size specified by the MinTreeSize command line option.
5837   if (VectorizableTree.size() >= MinTreeSize)
5838     return false;
5839 
5840   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5841   // can vectorize it if we can prove it fully vectorizable.
5842   if (isFullyVectorizableTinyTree(ForReduction))
5843     return false;
5844 
5845   assert(VectorizableTree.empty()
5846              ? ExternalUses.empty()
5847              : true && "We shouldn't have any external users");
5848 
5849   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5850   // vectorizable.
5851   return true;
5852 }
5853 
5854 InstructionCost BoUpSLP::getSpillCost() const {
5855   // Walk from the bottom of the tree to the top, tracking which values are
5856   // live. When we see a call instruction that is not part of our tree,
5857   // query TTI to see if there is a cost to keeping values live over it
5858   // (for example, if spills and fills are required).
5859   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5860   InstructionCost Cost = 0;
5861 
5862   SmallPtrSet<Instruction*, 4> LiveValues;
5863   Instruction *PrevInst = nullptr;
5864 
5865   // The entries in VectorizableTree are not necessarily ordered by their
5866   // position in basic blocks. Collect them and order them by dominance so later
5867   // instructions are guaranteed to be visited first. For instructions in
5868   // different basic blocks, we only scan to the beginning of the block, so
5869   // their order does not matter, as long as all instructions in a basic block
5870   // are grouped together. Using dominance ensures a deterministic order.
5871   SmallVector<Instruction *, 16> OrderedScalars;
5872   for (const auto &TEPtr : VectorizableTree) {
5873     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5874     if (!Inst)
5875       continue;
5876     OrderedScalars.push_back(Inst);
5877   }
5878   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5879     auto *NodeA = DT->getNode(A->getParent());
5880     auto *NodeB = DT->getNode(B->getParent());
5881     assert(NodeA && "Should only process reachable instructions");
5882     assert(NodeB && "Should only process reachable instructions");
5883     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5884            "Different nodes should have different DFS numbers");
5885     if (NodeA != NodeB)
5886       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5887     return B->comesBefore(A);
5888   });
5889 
5890   for (Instruction *Inst : OrderedScalars) {
5891     if (!PrevInst) {
5892       PrevInst = Inst;
5893       continue;
5894     }
5895 
5896     // Update LiveValues.
5897     LiveValues.erase(PrevInst);
5898     for (auto &J : PrevInst->operands()) {
5899       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5900         LiveValues.insert(cast<Instruction>(&*J));
5901     }
5902 
5903     LLVM_DEBUG({
5904       dbgs() << "SLP: #LV: " << LiveValues.size();
5905       for (auto *X : LiveValues)
5906         dbgs() << " " << X->getName();
5907       dbgs() << ", Looking at ";
5908       Inst->dump();
5909     });
5910 
5911     // Now find the sequence of instructions between PrevInst and Inst.
5912     unsigned NumCalls = 0;
5913     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5914                                  PrevInstIt =
5915                                      PrevInst->getIterator().getReverse();
5916     while (InstIt != PrevInstIt) {
5917       if (PrevInstIt == PrevInst->getParent()->rend()) {
5918         PrevInstIt = Inst->getParent()->rbegin();
5919         continue;
5920       }
5921 
5922       // Debug information does not impact spill cost.
5923       if ((isa<CallInst>(&*PrevInstIt) &&
5924            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5925           &*PrevInstIt != PrevInst)
5926         NumCalls++;
5927 
5928       ++PrevInstIt;
5929     }
5930 
5931     if (NumCalls) {
5932       SmallVector<Type*, 4> V;
5933       for (auto *II : LiveValues) {
5934         auto *ScalarTy = II->getType();
5935         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5936           ScalarTy = VectorTy->getElementType();
5937         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5938       }
5939       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5940     }
5941 
5942     PrevInst = Inst;
5943   }
5944 
5945   return Cost;
5946 }
5947 
5948 /// Check if two insertelement instructions are from the same buildvector.
5949 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
5950                                             InsertElementInst *V) {
5951   // Instructions must be from the same basic blocks.
5952   if (VU->getParent() != V->getParent())
5953     return false;
5954   // Checks if 2 insertelements are from the same buildvector.
5955   if (VU->getType() != V->getType())
5956     return false;
5957   // Multiple used inserts are separate nodes.
5958   if (!VU->hasOneUse() && !V->hasOneUse())
5959     return false;
5960   auto *IE1 = VU;
5961   auto *IE2 = V;
5962   // Go through the vector operand of insertelement instructions trying to find
5963   // either VU as the original vector for IE2 or V as the original vector for
5964   // IE1.
5965   do {
5966     if (IE2 == VU || IE1 == V)
5967       return true;
5968     if (IE1) {
5969       if (IE1 != VU && !IE1->hasOneUse())
5970         IE1 = nullptr;
5971       else
5972         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5973     }
5974     if (IE2) {
5975       if (IE2 != V && !IE2->hasOneUse())
5976         IE2 = nullptr;
5977       else
5978         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5979     }
5980   } while (IE1 || IE2);
5981   return false;
5982 }
5983 
5984 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5985   InstructionCost Cost = 0;
5986   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5987                     << VectorizableTree.size() << ".\n");
5988 
5989   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5990 
5991   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5992     TreeEntry &TE = *VectorizableTree[I].get();
5993 
5994     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5995     Cost += C;
5996     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5997                       << " for bundle that starts with " << *TE.Scalars[0]
5998                       << ".\n"
5999                       << "SLP: Current total cost = " << Cost << "\n");
6000   }
6001 
6002   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6003   InstructionCost ExtractCost = 0;
6004   SmallVector<unsigned> VF;
6005   SmallVector<SmallVector<int>> ShuffleMask;
6006   SmallVector<Value *> FirstUsers;
6007   SmallVector<APInt> DemandedElts;
6008   for (ExternalUser &EU : ExternalUses) {
6009     // We only add extract cost once for the same scalar.
6010     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6011         !ExtractCostCalculated.insert(EU.Scalar).second)
6012       continue;
6013 
6014     // Uses by ephemeral values are free (because the ephemeral value will be
6015     // removed prior to code generation, and so the extraction will be
6016     // removed as well).
6017     if (EphValues.count(EU.User))
6018       continue;
6019 
6020     // No extract cost for vector "scalar"
6021     if (isa<FixedVectorType>(EU.Scalar->getType()))
6022       continue;
6023 
6024     // Already counted the cost for external uses when tried to adjust the cost
6025     // for extractelements, no need to add it again.
6026     if (isa<ExtractElementInst>(EU.Scalar))
6027       continue;
6028 
6029     // If found user is an insertelement, do not calculate extract cost but try
6030     // to detect it as a final shuffled/identity match.
6031     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6032       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6033         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6034         if (InsertIdx) {
6035           auto *It = find_if(FirstUsers, [VU](Value *V) {
6036             return areTwoInsertFromSameBuildVector(VU,
6037                                                    cast<InsertElementInst>(V));
6038           });
6039           int VecId = -1;
6040           if (It == FirstUsers.end()) {
6041             VF.push_back(FTy->getNumElements());
6042             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6043             // Find the insertvector, vectorized in tree, if any.
6044             Value *Base = VU;
6045             while (isa<InsertElementInst>(Base)) {
6046               // Build the mask for the vectorized insertelement instructions.
6047               if (const TreeEntry *E = getTreeEntry(Base)) {
6048                 VU = cast<InsertElementInst>(Base);
6049                 do {
6050                   int Idx = E->findLaneForValue(Base);
6051                   ShuffleMask.back()[Idx] = Idx;
6052                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6053                 } while (E == getTreeEntry(Base));
6054                 break;
6055               }
6056               Base = cast<InsertElementInst>(Base)->getOperand(0);
6057             }
6058             FirstUsers.push_back(VU);
6059             DemandedElts.push_back(APInt::getZero(VF.back()));
6060             VecId = FirstUsers.size() - 1;
6061           } else {
6062             VecId = std::distance(FirstUsers.begin(), It);
6063           }
6064           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6065           DemandedElts[VecId].setBit(*InsertIdx);
6066           continue;
6067         }
6068       }
6069     }
6070 
6071     // If we plan to rewrite the tree in a smaller type, we will need to sign
6072     // extend the extracted value back to the original type. Here, we account
6073     // for the extract and the added cost of the sign extend if needed.
6074     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6075     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6076     if (MinBWs.count(ScalarRoot)) {
6077       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6078       auto Extend =
6079           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6080       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6081       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6082                                                    VecTy, EU.Lane);
6083     } else {
6084       ExtractCost +=
6085           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6086     }
6087   }
6088 
6089   InstructionCost SpillCost = getSpillCost();
6090   Cost += SpillCost + ExtractCost;
6091   if (FirstUsers.size() == 1) {
6092     int Limit = ShuffleMask.front().size() * 2;
6093     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6094         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6095       InstructionCost C = TTI->getShuffleCost(
6096           TTI::SK_PermuteSingleSrc,
6097           cast<FixedVectorType>(FirstUsers.front()->getType()),
6098           ShuffleMask.front());
6099       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6100                         << " for final shuffle of insertelement external users "
6101                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6102                         << "SLP: Current total cost = " << Cost << "\n");
6103       Cost += C;
6104     }
6105     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6106         cast<FixedVectorType>(FirstUsers.front()->getType()),
6107         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6108     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6109                       << " for insertelements gather.\n"
6110                       << "SLP: Current total cost = " << Cost << "\n");
6111     Cost -= InsertCost;
6112   } else if (FirstUsers.size() >= 2) {
6113     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6114     // Combined masks of the first 2 vectors.
6115     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6116     copy(ShuffleMask.front(), CombinedMask.begin());
6117     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6118     auto *VecTy = FixedVectorType::get(
6119         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6120         MaxVF);
6121     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6122       if (ShuffleMask[1][I] != UndefMaskElem) {
6123         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6124         CombinedDemandedElts.setBit(I);
6125       }
6126     }
6127     InstructionCost C =
6128         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6129     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6130                       << " for final shuffle of vector node and external "
6131                          "insertelement users "
6132                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6133                       << "SLP: Current total cost = " << Cost << "\n");
6134     Cost += C;
6135     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6136         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6137     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6138                       << " for insertelements gather.\n"
6139                       << "SLP: Current total cost = " << Cost << "\n");
6140     Cost -= InsertCost;
6141     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6142       // Other elements - permutation of 2 vectors (the initial one and the
6143       // next Ith incoming vector).
6144       unsigned VF = ShuffleMask[I].size();
6145       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6146         int Mask = ShuffleMask[I][Idx];
6147         if (Mask != UndefMaskElem)
6148           CombinedMask[Idx] = MaxVF + Mask;
6149         else if (CombinedMask[Idx] != UndefMaskElem)
6150           CombinedMask[Idx] = Idx;
6151       }
6152       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6153         if (CombinedMask[Idx] != UndefMaskElem)
6154           CombinedMask[Idx] = Idx;
6155       InstructionCost C =
6156           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6157       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6158                         << " for final shuffle of vector node and external "
6159                            "insertelement users "
6160                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6161                         << "SLP: Current total cost = " << Cost << "\n");
6162       Cost += C;
6163       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6164           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6165           /*Insert*/ true, /*Extract*/ false);
6166       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6167                         << " for insertelements gather.\n"
6168                         << "SLP: Current total cost = " << Cost << "\n");
6169       Cost -= InsertCost;
6170     }
6171   }
6172 
6173 #ifndef NDEBUG
6174   SmallString<256> Str;
6175   {
6176     raw_svector_ostream OS(Str);
6177     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6178        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6179        << "SLP: Total Cost = " << Cost << ".\n";
6180   }
6181   LLVM_DEBUG(dbgs() << Str);
6182   if (ViewSLPTree)
6183     ViewGraph(this, "SLP" + F->getName(), false, Str);
6184 #endif
6185 
6186   return Cost;
6187 }
6188 
6189 Optional<TargetTransformInfo::ShuffleKind>
6190 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6191                                SmallVectorImpl<const TreeEntry *> &Entries) {
6192   // TODO: currently checking only for Scalars in the tree entry, need to count
6193   // reused elements too for better cost estimation.
6194   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6195   Entries.clear();
6196   // Build a lists of values to tree entries.
6197   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6198   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6199     if (EntryPtr.get() == TE)
6200       break;
6201     if (EntryPtr->State != TreeEntry::NeedToGather)
6202       continue;
6203     for (Value *V : EntryPtr->Scalars)
6204       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6205   }
6206   // Find all tree entries used by the gathered values. If no common entries
6207   // found - not a shuffle.
6208   // Here we build a set of tree nodes for each gathered value and trying to
6209   // find the intersection between these sets. If we have at least one common
6210   // tree node for each gathered value - we have just a permutation of the
6211   // single vector. If we have 2 different sets, we're in situation where we
6212   // have a permutation of 2 input vectors.
6213   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6214   DenseMap<Value *, int> UsedValuesEntry;
6215   for (Value *V : TE->Scalars) {
6216     if (isa<UndefValue>(V))
6217       continue;
6218     // Build a list of tree entries where V is used.
6219     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6220     auto It = ValueToTEs.find(V);
6221     if (It != ValueToTEs.end())
6222       VToTEs = It->second;
6223     if (const TreeEntry *VTE = getTreeEntry(V))
6224       VToTEs.insert(VTE);
6225     if (VToTEs.empty())
6226       return None;
6227     if (UsedTEs.empty()) {
6228       // The first iteration, just insert the list of nodes to vector.
6229       UsedTEs.push_back(VToTEs);
6230     } else {
6231       // Need to check if there are any previously used tree nodes which use V.
6232       // If there are no such nodes, consider that we have another one input
6233       // vector.
6234       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6235       unsigned Idx = 0;
6236       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6237         // Do we have a non-empty intersection of previously listed tree entries
6238         // and tree entries using current V?
6239         set_intersect(VToTEs, Set);
6240         if (!VToTEs.empty()) {
6241           // Yes, write the new subset and continue analysis for the next
6242           // scalar.
6243           Set.swap(VToTEs);
6244           break;
6245         }
6246         VToTEs = SavedVToTEs;
6247         ++Idx;
6248       }
6249       // No non-empty intersection found - need to add a second set of possible
6250       // source vectors.
6251       if (Idx == UsedTEs.size()) {
6252         // If the number of input vectors is greater than 2 - not a permutation,
6253         // fallback to the regular gather.
6254         if (UsedTEs.size() == 2)
6255           return None;
6256         UsedTEs.push_back(SavedVToTEs);
6257         Idx = UsedTEs.size() - 1;
6258       }
6259       UsedValuesEntry.try_emplace(V, Idx);
6260     }
6261   }
6262 
6263   unsigned VF = 0;
6264   if (UsedTEs.size() == 1) {
6265     // Try to find the perfect match in another gather node at first.
6266     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6267       return EntryPtr->isSame(TE->Scalars);
6268     });
6269     if (It != UsedTEs.front().end()) {
6270       Entries.push_back(*It);
6271       std::iota(Mask.begin(), Mask.end(), 0);
6272       return TargetTransformInfo::SK_PermuteSingleSrc;
6273     }
6274     // No perfect match, just shuffle, so choose the first tree node.
6275     Entries.push_back(*UsedTEs.front().begin());
6276   } else {
6277     // Try to find nodes with the same vector factor.
6278     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6279     DenseMap<int, const TreeEntry *> VFToTE;
6280     for (const TreeEntry *TE : UsedTEs.front())
6281       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6282     for (const TreeEntry *TE : UsedTEs.back()) {
6283       auto It = VFToTE.find(TE->getVectorFactor());
6284       if (It != VFToTE.end()) {
6285         VF = It->first;
6286         Entries.push_back(It->second);
6287         Entries.push_back(TE);
6288         break;
6289       }
6290     }
6291     // No 2 source vectors with the same vector factor - give up and do regular
6292     // gather.
6293     if (Entries.empty())
6294       return None;
6295   }
6296 
6297   // Build a shuffle mask for better cost estimation and vector emission.
6298   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6299     Value *V = TE->Scalars[I];
6300     if (isa<UndefValue>(V))
6301       continue;
6302     unsigned Idx = UsedValuesEntry.lookup(V);
6303     const TreeEntry *VTE = Entries[Idx];
6304     int FoundLane = VTE->findLaneForValue(V);
6305     Mask[I] = Idx * VF + FoundLane;
6306     // Extra check required by isSingleSourceMaskImpl function (called by
6307     // ShuffleVectorInst::isSingleSourceMask).
6308     if (Mask[I] >= 2 * E)
6309       return None;
6310   }
6311   switch (Entries.size()) {
6312   case 1:
6313     return TargetTransformInfo::SK_PermuteSingleSrc;
6314   case 2:
6315     return TargetTransformInfo::SK_PermuteTwoSrc;
6316   default:
6317     break;
6318   }
6319   return None;
6320 }
6321 
6322 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6323                                        const APInt &ShuffledIndices,
6324                                        bool NeedToShuffle) const {
6325   InstructionCost Cost =
6326       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6327                                     /*Extract*/ false);
6328   if (NeedToShuffle)
6329     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6330   return Cost;
6331 }
6332 
6333 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6334   // Find the type of the operands in VL.
6335   Type *ScalarTy = VL[0]->getType();
6336   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6337     ScalarTy = SI->getValueOperand()->getType();
6338   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6339   bool DuplicateNonConst = false;
6340   // Find the cost of inserting/extracting values from the vector.
6341   // Check if the same elements are inserted several times and count them as
6342   // shuffle candidates.
6343   APInt ShuffledElements = APInt::getZero(VL.size());
6344   DenseSet<Value *> UniqueElements;
6345   // Iterate in reverse order to consider insert elements with the high cost.
6346   for (unsigned I = VL.size(); I > 0; --I) {
6347     unsigned Idx = I - 1;
6348     // No need to shuffle duplicates for constants.
6349     if (isConstant(VL[Idx])) {
6350       ShuffledElements.setBit(Idx);
6351       continue;
6352     }
6353     if (!UniqueElements.insert(VL[Idx]).second) {
6354       DuplicateNonConst = true;
6355       ShuffledElements.setBit(Idx);
6356     }
6357   }
6358   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6359 }
6360 
6361 // Perform operand reordering on the instructions in VL and return the reordered
6362 // operands in Left and Right.
6363 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6364                                              SmallVectorImpl<Value *> &Left,
6365                                              SmallVectorImpl<Value *> &Right,
6366                                              const DataLayout &DL,
6367                                              ScalarEvolution &SE,
6368                                              const BoUpSLP &R) {
6369   if (VL.empty())
6370     return;
6371   VLOperands Ops(VL, DL, SE, R);
6372   // Reorder the operands in place.
6373   Ops.reorder();
6374   Left = Ops.getVL(0);
6375   Right = Ops.getVL(1);
6376 }
6377 
6378 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6379   // Get the basic block this bundle is in. All instructions in the bundle
6380   // should be in this block.
6381   auto *Front = E->getMainOp();
6382   auto *BB = Front->getParent();
6383   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6384     auto *I = cast<Instruction>(V);
6385     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6386   }));
6387 
6388   // The last instruction in the bundle in program order.
6389   Instruction *LastInst = nullptr;
6390 
6391   // Find the last instruction. The common case should be that BB has been
6392   // scheduled, and the last instruction is VL.back(). So we start with
6393   // VL.back() and iterate over schedule data until we reach the end of the
6394   // bundle. The end of the bundle is marked by null ScheduleData.
6395   if (BlocksSchedules.count(BB)) {
6396     auto *Bundle =
6397         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
6398     if (Bundle && Bundle->isPartOfBundle())
6399       for (; Bundle; Bundle = Bundle->NextInBundle)
6400         if (Bundle->OpValue == Bundle->Inst)
6401           LastInst = Bundle->Inst;
6402   }
6403 
6404   // LastInst can still be null at this point if there's either not an entry
6405   // for BB in BlocksSchedules or there's no ScheduleData available for
6406   // VL.back(). This can be the case if buildTree_rec aborts for various
6407   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6408   // size is reached, etc.). ScheduleData is initialized in the scheduling
6409   // "dry-run".
6410   //
6411   // If this happens, we can still find the last instruction by brute force. We
6412   // iterate forwards from Front (inclusive) until we either see all
6413   // instructions in the bundle or reach the end of the block. If Front is the
6414   // last instruction in program order, LastInst will be set to Front, and we
6415   // will visit all the remaining instructions in the block.
6416   //
6417   // One of the reasons we exit early from buildTree_rec is to place an upper
6418   // bound on compile-time. Thus, taking an additional compile-time hit here is
6419   // not ideal. However, this should be exceedingly rare since it requires that
6420   // we both exit early from buildTree_rec and that the bundle be out-of-order
6421   // (causing us to iterate all the way to the end of the block).
6422   if (!LastInst) {
6423     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6424     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6425       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6426         LastInst = &I;
6427       if (Bundle.empty())
6428         break;
6429     }
6430   }
6431   assert(LastInst && "Failed to find last instruction in bundle");
6432 
6433   // Set the insertion point after the last instruction in the bundle. Set the
6434   // debug location to Front.
6435   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6436   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6437 }
6438 
6439 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6440   // List of instructions/lanes from current block and/or the blocks which are
6441   // part of the current loop. These instructions will be inserted at the end to
6442   // make it possible to optimize loops and hoist invariant instructions out of
6443   // the loops body with better chances for success.
6444   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6445   SmallSet<int, 4> PostponedIndices;
6446   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6447   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6448     SmallPtrSet<BasicBlock *, 4> Visited;
6449     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6450       InsertBB = InsertBB->getSinglePredecessor();
6451     return InsertBB && InsertBB == InstBB;
6452   };
6453   for (int I = 0, E = VL.size(); I < E; ++I) {
6454     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6455       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6456            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6457           PostponedIndices.insert(I).second)
6458         PostponedInsts.emplace_back(Inst, I);
6459   }
6460 
6461   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6462     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6463     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6464     if (!InsElt)
6465       return Vec;
6466     GatherShuffleSeq.insert(InsElt);
6467     CSEBlocks.insert(InsElt->getParent());
6468     // Add to our 'need-to-extract' list.
6469     if (TreeEntry *Entry = getTreeEntry(V)) {
6470       // Find which lane we need to extract.
6471       unsigned FoundLane = Entry->findLaneForValue(V);
6472       ExternalUses.emplace_back(V, InsElt, FoundLane);
6473     }
6474     return Vec;
6475   };
6476   Value *Val0 =
6477       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6478   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6479   Value *Vec = PoisonValue::get(VecTy);
6480   SmallVector<int> NonConsts;
6481   // Insert constant values at first.
6482   for (int I = 0, E = VL.size(); I < E; ++I) {
6483     if (PostponedIndices.contains(I))
6484       continue;
6485     if (!isConstant(VL[I])) {
6486       NonConsts.push_back(I);
6487       continue;
6488     }
6489     Vec = CreateInsertElement(Vec, VL[I], I);
6490   }
6491   // Insert non-constant values.
6492   for (int I : NonConsts)
6493     Vec = CreateInsertElement(Vec, VL[I], I);
6494   // Append instructions, which are/may be part of the loop, in the end to make
6495   // it possible to hoist non-loop-based instructions.
6496   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6497     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6498 
6499   return Vec;
6500 }
6501 
6502 namespace {
6503 /// Merges shuffle masks and emits final shuffle instruction, if required.
6504 class ShuffleInstructionBuilder {
6505   IRBuilderBase &Builder;
6506   const unsigned VF = 0;
6507   bool IsFinalized = false;
6508   SmallVector<int, 4> Mask;
6509   /// Holds all of the instructions that we gathered.
6510   SetVector<Instruction *> &GatherShuffleSeq;
6511   /// A list of blocks that we are going to CSE.
6512   SetVector<BasicBlock *> &CSEBlocks;
6513 
6514 public:
6515   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6516                             SetVector<Instruction *> &GatherShuffleSeq,
6517                             SetVector<BasicBlock *> &CSEBlocks)
6518       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6519         CSEBlocks(CSEBlocks) {}
6520 
6521   /// Adds a mask, inverting it before applying.
6522   void addInversedMask(ArrayRef<unsigned> SubMask) {
6523     if (SubMask.empty())
6524       return;
6525     SmallVector<int, 4> NewMask;
6526     inversePermutation(SubMask, NewMask);
6527     addMask(NewMask);
6528   }
6529 
6530   /// Functions adds masks, merging them into  single one.
6531   void addMask(ArrayRef<unsigned> SubMask) {
6532     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6533     addMask(NewMask);
6534   }
6535 
6536   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6537 
6538   Value *finalize(Value *V) {
6539     IsFinalized = true;
6540     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6541     if (VF == ValueVF && Mask.empty())
6542       return V;
6543     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6544     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6545     addMask(NormalizedMask);
6546 
6547     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6548       return V;
6549     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6550     if (auto *I = dyn_cast<Instruction>(Vec)) {
6551       GatherShuffleSeq.insert(I);
6552       CSEBlocks.insert(I->getParent());
6553     }
6554     return Vec;
6555   }
6556 
6557   ~ShuffleInstructionBuilder() {
6558     assert((IsFinalized || Mask.empty()) &&
6559            "Shuffle construction must be finalized.");
6560   }
6561 };
6562 } // namespace
6563 
6564 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6565   const unsigned VF = VL.size();
6566   InstructionsState S = getSameOpcode(VL);
6567   if (S.getOpcode()) {
6568     if (TreeEntry *E = getTreeEntry(S.OpValue))
6569       if (E->isSame(VL)) {
6570         Value *V = vectorizeTree(E);
6571         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6572           if (!E->ReuseShuffleIndices.empty()) {
6573             // Reshuffle to get only unique values.
6574             // If some of the scalars are duplicated in the vectorization tree
6575             // entry, we do not vectorize them but instead generate a mask for
6576             // the reuses. But if there are several users of the same entry,
6577             // they may have different vectorization factors. This is especially
6578             // important for PHI nodes. In this case, we need to adapt the
6579             // resulting instruction for the user vectorization factor and have
6580             // to reshuffle it again to take only unique elements of the vector.
6581             // Without this code the function incorrectly returns reduced vector
6582             // instruction with the same elements, not with the unique ones.
6583 
6584             // block:
6585             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6586             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6587             // ... (use %2)
6588             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6589             // br %block
6590             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6591             SmallSet<int, 4> UsedIdxs;
6592             int Pos = 0;
6593             int Sz = VL.size();
6594             for (int Idx : E->ReuseShuffleIndices) {
6595               if (Idx != Sz && Idx != UndefMaskElem &&
6596                   UsedIdxs.insert(Idx).second)
6597                 UniqueIdxs[Idx] = Pos;
6598               ++Pos;
6599             }
6600             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6601                                             "less than original vector size.");
6602             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6603             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6604           } else {
6605             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6606                    "Expected vectorization factor less "
6607                    "than original vector size.");
6608             SmallVector<int> UniformMask(VF, 0);
6609             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6610             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6611           }
6612           if (auto *I = dyn_cast<Instruction>(V)) {
6613             GatherShuffleSeq.insert(I);
6614             CSEBlocks.insert(I->getParent());
6615           }
6616         }
6617         return V;
6618       }
6619   }
6620 
6621   // Can't vectorize this, so simply build a new vector with each lane
6622   // corresponding to the requested value.
6623   return createBuildVector(VL);
6624 }
6625 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6626   unsigned VF = VL.size();
6627   // Exploit possible reuse of values across lanes.
6628   SmallVector<int> ReuseShuffleIndicies;
6629   SmallVector<Value *> UniqueValues;
6630   if (VL.size() > 2) {
6631     DenseMap<Value *, unsigned> UniquePositions;
6632     unsigned NumValues =
6633         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6634                                     return !isa<UndefValue>(V);
6635                                   }).base());
6636     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6637     int UniqueVals = 0;
6638     for (Value *V : VL.drop_back(VL.size() - VF)) {
6639       if (isa<UndefValue>(V)) {
6640         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6641         continue;
6642       }
6643       if (isConstant(V)) {
6644         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6645         UniqueValues.emplace_back(V);
6646         continue;
6647       }
6648       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6649       ReuseShuffleIndicies.emplace_back(Res.first->second);
6650       if (Res.second) {
6651         UniqueValues.emplace_back(V);
6652         ++UniqueVals;
6653       }
6654     }
6655     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6656       // Emit pure splat vector.
6657       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6658                                   UndefMaskElem);
6659     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6660       ReuseShuffleIndicies.clear();
6661       UniqueValues.clear();
6662       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6663     }
6664     UniqueValues.append(VF - UniqueValues.size(),
6665                         PoisonValue::get(VL[0]->getType()));
6666     VL = UniqueValues;
6667   }
6668 
6669   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6670                                            CSEBlocks);
6671   Value *Vec = gather(VL);
6672   if (!ReuseShuffleIndicies.empty()) {
6673     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6674     Vec = ShuffleBuilder.finalize(Vec);
6675   }
6676   return Vec;
6677 }
6678 
6679 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6680   IRBuilder<>::InsertPointGuard Guard(Builder);
6681 
6682   if (E->VectorizedValue) {
6683     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6684     return E->VectorizedValue;
6685   }
6686 
6687   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6688   unsigned VF = E->getVectorFactor();
6689   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6690                                            CSEBlocks);
6691   if (E->State == TreeEntry::NeedToGather) {
6692     if (E->getMainOp())
6693       setInsertPointAfterBundle(E);
6694     Value *Vec;
6695     SmallVector<int> Mask;
6696     SmallVector<const TreeEntry *> Entries;
6697     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6698         isGatherShuffledEntry(E, Mask, Entries);
6699     if (Shuffle.hasValue()) {
6700       assert((Entries.size() == 1 || Entries.size() == 2) &&
6701              "Expected shuffle of 1 or 2 entries.");
6702       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6703                                         Entries.back()->VectorizedValue, Mask);
6704       if (auto *I = dyn_cast<Instruction>(Vec)) {
6705         GatherShuffleSeq.insert(I);
6706         CSEBlocks.insert(I->getParent());
6707       }
6708     } else {
6709       Vec = gather(E->Scalars);
6710     }
6711     if (NeedToShuffleReuses) {
6712       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6713       Vec = ShuffleBuilder.finalize(Vec);
6714     }
6715     E->VectorizedValue = Vec;
6716     return Vec;
6717   }
6718 
6719   assert((E->State == TreeEntry::Vectorize ||
6720           E->State == TreeEntry::ScatterVectorize) &&
6721          "Unhandled state");
6722   unsigned ShuffleOrOp =
6723       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6724   Instruction *VL0 = E->getMainOp();
6725   Type *ScalarTy = VL0->getType();
6726   if (auto *Store = dyn_cast<StoreInst>(VL0))
6727     ScalarTy = Store->getValueOperand()->getType();
6728   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6729     ScalarTy = IE->getOperand(1)->getType();
6730   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6731   switch (ShuffleOrOp) {
6732     case Instruction::PHI: {
6733       assert(
6734           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6735           "PHI reordering is free.");
6736       auto *PH = cast<PHINode>(VL0);
6737       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6738       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6739       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6740       Value *V = NewPhi;
6741 
6742       // Adjust insertion point once all PHI's have been generated.
6743       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6744       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6745 
6746       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6747       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6748       V = ShuffleBuilder.finalize(V);
6749 
6750       E->VectorizedValue = V;
6751 
6752       // PHINodes may have multiple entries from the same block. We want to
6753       // visit every block once.
6754       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6755 
6756       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6757         ValueList Operands;
6758         BasicBlock *IBB = PH->getIncomingBlock(i);
6759 
6760         if (!VisitedBBs.insert(IBB).second) {
6761           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6762           continue;
6763         }
6764 
6765         Builder.SetInsertPoint(IBB->getTerminator());
6766         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6767         Value *Vec = vectorizeTree(E->getOperand(i));
6768         NewPhi->addIncoming(Vec, IBB);
6769       }
6770 
6771       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6772              "Invalid number of incoming values");
6773       return V;
6774     }
6775 
6776     case Instruction::ExtractElement: {
6777       Value *V = E->getSingleOperand(0);
6778       Builder.SetInsertPoint(VL0);
6779       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6780       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6781       V = ShuffleBuilder.finalize(V);
6782       E->VectorizedValue = V;
6783       return V;
6784     }
6785     case Instruction::ExtractValue: {
6786       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6787       Builder.SetInsertPoint(LI);
6788       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6789       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6790       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6791       Value *NewV = propagateMetadata(V, E->Scalars);
6792       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6793       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6794       NewV = ShuffleBuilder.finalize(NewV);
6795       E->VectorizedValue = NewV;
6796       return NewV;
6797     }
6798     case Instruction::InsertElement: {
6799       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6800       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6801       Value *V = vectorizeTree(E->getOperand(1));
6802 
6803       // Create InsertVector shuffle if necessary
6804       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6805         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6806       }));
6807       const unsigned NumElts =
6808           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6809       const unsigned NumScalars = E->Scalars.size();
6810 
6811       unsigned Offset = *getInsertIndex(VL0);
6812       assert(Offset < NumElts && "Failed to find vector index offset");
6813 
6814       // Create shuffle to resize vector
6815       SmallVector<int> Mask;
6816       if (!E->ReorderIndices.empty()) {
6817         inversePermutation(E->ReorderIndices, Mask);
6818         Mask.append(NumElts - NumScalars, UndefMaskElem);
6819       } else {
6820         Mask.assign(NumElts, UndefMaskElem);
6821         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6822       }
6823       // Create InsertVector shuffle if necessary
6824       bool IsIdentity = true;
6825       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6826       Mask.swap(PrevMask);
6827       for (unsigned I = 0; I < NumScalars; ++I) {
6828         Value *Scalar = E->Scalars[PrevMask[I]];
6829         unsigned InsertIdx = *getInsertIndex(Scalar);
6830         IsIdentity &= InsertIdx - Offset == I;
6831         Mask[InsertIdx - Offset] = I;
6832       }
6833       if (!IsIdentity || NumElts != NumScalars) {
6834         V = Builder.CreateShuffleVector(V, Mask);
6835         if (auto *I = dyn_cast<Instruction>(V)) {
6836           GatherShuffleSeq.insert(I);
6837           CSEBlocks.insert(I->getParent());
6838         }
6839       }
6840 
6841       if ((!IsIdentity || Offset != 0 ||
6842            !isUndefVector(FirstInsert->getOperand(0))) &&
6843           NumElts != NumScalars) {
6844         SmallVector<int> InsertMask(NumElts);
6845         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6846         for (unsigned I = 0; I < NumElts; I++) {
6847           if (Mask[I] != UndefMaskElem)
6848             InsertMask[Offset + I] = NumElts + I;
6849         }
6850 
6851         V = Builder.CreateShuffleVector(
6852             FirstInsert->getOperand(0), V, InsertMask,
6853             cast<Instruction>(E->Scalars.back())->getName());
6854         if (auto *I = dyn_cast<Instruction>(V)) {
6855           GatherShuffleSeq.insert(I);
6856           CSEBlocks.insert(I->getParent());
6857         }
6858       }
6859 
6860       ++NumVectorInstructions;
6861       E->VectorizedValue = V;
6862       return V;
6863     }
6864     case Instruction::ZExt:
6865     case Instruction::SExt:
6866     case Instruction::FPToUI:
6867     case Instruction::FPToSI:
6868     case Instruction::FPExt:
6869     case Instruction::PtrToInt:
6870     case Instruction::IntToPtr:
6871     case Instruction::SIToFP:
6872     case Instruction::UIToFP:
6873     case Instruction::Trunc:
6874     case Instruction::FPTrunc:
6875     case Instruction::BitCast: {
6876       setInsertPointAfterBundle(E);
6877 
6878       Value *InVec = vectorizeTree(E->getOperand(0));
6879 
6880       if (E->VectorizedValue) {
6881         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6882         return E->VectorizedValue;
6883       }
6884 
6885       auto *CI = cast<CastInst>(VL0);
6886       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6887       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6888       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6889       V = ShuffleBuilder.finalize(V);
6890 
6891       E->VectorizedValue = V;
6892       ++NumVectorInstructions;
6893       return V;
6894     }
6895     case Instruction::FCmp:
6896     case Instruction::ICmp: {
6897       setInsertPointAfterBundle(E);
6898 
6899       Value *L = vectorizeTree(E->getOperand(0));
6900       Value *R = vectorizeTree(E->getOperand(1));
6901 
6902       if (E->VectorizedValue) {
6903         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6904         return E->VectorizedValue;
6905       }
6906 
6907       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6908       Value *V = Builder.CreateCmp(P0, L, R);
6909       propagateIRFlags(V, E->Scalars, VL0);
6910       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6911       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6912       V = ShuffleBuilder.finalize(V);
6913 
6914       E->VectorizedValue = V;
6915       ++NumVectorInstructions;
6916       return V;
6917     }
6918     case Instruction::Select: {
6919       setInsertPointAfterBundle(E);
6920 
6921       Value *Cond = vectorizeTree(E->getOperand(0));
6922       Value *True = vectorizeTree(E->getOperand(1));
6923       Value *False = vectorizeTree(E->getOperand(2));
6924 
6925       if (E->VectorizedValue) {
6926         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6927         return E->VectorizedValue;
6928       }
6929 
6930       Value *V = Builder.CreateSelect(Cond, True, False);
6931       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6932       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6933       V = ShuffleBuilder.finalize(V);
6934 
6935       E->VectorizedValue = V;
6936       ++NumVectorInstructions;
6937       return V;
6938     }
6939     case Instruction::FNeg: {
6940       setInsertPointAfterBundle(E);
6941 
6942       Value *Op = vectorizeTree(E->getOperand(0));
6943 
6944       if (E->VectorizedValue) {
6945         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6946         return E->VectorizedValue;
6947       }
6948 
6949       Value *V = Builder.CreateUnOp(
6950           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6951       propagateIRFlags(V, E->Scalars, VL0);
6952       if (auto *I = dyn_cast<Instruction>(V))
6953         V = propagateMetadata(I, E->Scalars);
6954 
6955       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6956       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6957       V = ShuffleBuilder.finalize(V);
6958 
6959       E->VectorizedValue = V;
6960       ++NumVectorInstructions;
6961 
6962       return V;
6963     }
6964     case Instruction::Add:
6965     case Instruction::FAdd:
6966     case Instruction::Sub:
6967     case Instruction::FSub:
6968     case Instruction::Mul:
6969     case Instruction::FMul:
6970     case Instruction::UDiv:
6971     case Instruction::SDiv:
6972     case Instruction::FDiv:
6973     case Instruction::URem:
6974     case Instruction::SRem:
6975     case Instruction::FRem:
6976     case Instruction::Shl:
6977     case Instruction::LShr:
6978     case Instruction::AShr:
6979     case Instruction::And:
6980     case Instruction::Or:
6981     case Instruction::Xor: {
6982       setInsertPointAfterBundle(E);
6983 
6984       Value *LHS = vectorizeTree(E->getOperand(0));
6985       Value *RHS = vectorizeTree(E->getOperand(1));
6986 
6987       if (E->VectorizedValue) {
6988         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6989         return E->VectorizedValue;
6990       }
6991 
6992       Value *V = Builder.CreateBinOp(
6993           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6994           RHS);
6995       propagateIRFlags(V, E->Scalars, VL0);
6996       if (auto *I = dyn_cast<Instruction>(V))
6997         V = propagateMetadata(I, E->Scalars);
6998 
6999       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7000       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7001       V = ShuffleBuilder.finalize(V);
7002 
7003       E->VectorizedValue = V;
7004       ++NumVectorInstructions;
7005 
7006       return V;
7007     }
7008     case Instruction::Load: {
7009       // Loads are inserted at the head of the tree because we don't want to
7010       // sink them all the way down past store instructions.
7011       setInsertPointAfterBundle(E);
7012 
7013       LoadInst *LI = cast<LoadInst>(VL0);
7014       Instruction *NewLI;
7015       unsigned AS = LI->getPointerAddressSpace();
7016       Value *PO = LI->getPointerOperand();
7017       if (E->State == TreeEntry::Vectorize) {
7018 
7019         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7020 
7021         // The pointer operand uses an in-tree scalar so we add the new BitCast
7022         // to ExternalUses list to make sure that an extract will be generated
7023         // in the future.
7024         if (TreeEntry *Entry = getTreeEntry(PO)) {
7025           // Find which lane we need to extract.
7026           unsigned FoundLane = Entry->findLaneForValue(PO);
7027           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
7028         }
7029 
7030         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7031       } else {
7032         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7033         Value *VecPtr = vectorizeTree(E->getOperand(0));
7034         // Use the minimum alignment of the gathered loads.
7035         Align CommonAlignment = LI->getAlign();
7036         for (Value *V : E->Scalars)
7037           CommonAlignment =
7038               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7039         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7040       }
7041       Value *V = propagateMetadata(NewLI, E->Scalars);
7042 
7043       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7044       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7045       V = ShuffleBuilder.finalize(V);
7046       E->VectorizedValue = V;
7047       ++NumVectorInstructions;
7048       return V;
7049     }
7050     case Instruction::Store: {
7051       auto *SI = cast<StoreInst>(VL0);
7052       unsigned AS = SI->getPointerAddressSpace();
7053 
7054       setInsertPointAfterBundle(E);
7055 
7056       Value *VecValue = vectorizeTree(E->getOperand(0));
7057       ShuffleBuilder.addMask(E->ReorderIndices);
7058       VecValue = ShuffleBuilder.finalize(VecValue);
7059 
7060       Value *ScalarPtr = SI->getPointerOperand();
7061       Value *VecPtr = Builder.CreateBitCast(
7062           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7063       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
7064                                                  SI->getAlign());
7065 
7066       // The pointer operand uses an in-tree scalar, so add the new BitCast to
7067       // ExternalUses to make sure that an extract will be generated in the
7068       // future.
7069       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7070         // Find which lane we need to extract.
7071         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7072         ExternalUses.push_back(
7073             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
7074       }
7075 
7076       Value *V = propagateMetadata(ST, E->Scalars);
7077 
7078       E->VectorizedValue = V;
7079       ++NumVectorInstructions;
7080       return V;
7081     }
7082     case Instruction::GetElementPtr: {
7083       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7084       setInsertPointAfterBundle(E);
7085 
7086       Value *Op0 = vectorizeTree(E->getOperand(0));
7087 
7088       SmallVector<Value *> OpVecs;
7089       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7090         Value *OpVec = vectorizeTree(E->getOperand(J));
7091         OpVecs.push_back(OpVec);
7092       }
7093 
7094       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7095       if (Instruction *I = dyn_cast<Instruction>(V))
7096         V = propagateMetadata(I, E->Scalars);
7097 
7098       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7099       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7100       V = ShuffleBuilder.finalize(V);
7101 
7102       E->VectorizedValue = V;
7103       ++NumVectorInstructions;
7104 
7105       return V;
7106     }
7107     case Instruction::Call: {
7108       CallInst *CI = cast<CallInst>(VL0);
7109       setInsertPointAfterBundle(E);
7110 
7111       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7112       if (Function *FI = CI->getCalledFunction())
7113         IID = FI->getIntrinsicID();
7114 
7115       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7116 
7117       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7118       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7119                           VecCallCosts.first <= VecCallCosts.second;
7120 
7121       Value *ScalarArg = nullptr;
7122       std::vector<Value *> OpVecs;
7123       SmallVector<Type *, 2> TysForDecl =
7124           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7125       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7126         ValueList OpVL;
7127         // Some intrinsics have scalar arguments. This argument should not be
7128         // vectorized.
7129         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7130           CallInst *CEI = cast<CallInst>(VL0);
7131           ScalarArg = CEI->getArgOperand(j);
7132           OpVecs.push_back(CEI->getArgOperand(j));
7133           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7134             TysForDecl.push_back(ScalarArg->getType());
7135           continue;
7136         }
7137 
7138         Value *OpVec = vectorizeTree(E->getOperand(j));
7139         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7140         OpVecs.push_back(OpVec);
7141       }
7142 
7143       Function *CF;
7144       if (!UseIntrinsic) {
7145         VFShape Shape =
7146             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7147                                   VecTy->getNumElements())),
7148                          false /*HasGlobalPred*/);
7149         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7150       } else {
7151         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7152       }
7153 
7154       SmallVector<OperandBundleDef, 1> OpBundles;
7155       CI->getOperandBundlesAsDefs(OpBundles);
7156       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7157 
7158       // The scalar argument uses an in-tree scalar so we add the new vectorized
7159       // call to ExternalUses list to make sure that an extract will be
7160       // generated in the future.
7161       if (ScalarArg) {
7162         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7163           // Find which lane we need to extract.
7164           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7165           ExternalUses.push_back(
7166               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7167         }
7168       }
7169 
7170       propagateIRFlags(V, E->Scalars, VL0);
7171       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7172       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7173       V = ShuffleBuilder.finalize(V);
7174 
7175       E->VectorizedValue = V;
7176       ++NumVectorInstructions;
7177       return V;
7178     }
7179     case Instruction::ShuffleVector: {
7180       assert(E->isAltShuffle() &&
7181              ((Instruction::isBinaryOp(E->getOpcode()) &&
7182                Instruction::isBinaryOp(E->getAltOpcode())) ||
7183               (Instruction::isCast(E->getOpcode()) &&
7184                Instruction::isCast(E->getAltOpcode())) ||
7185               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7186              "Invalid Shuffle Vector Operand");
7187 
7188       Value *LHS = nullptr, *RHS = nullptr;
7189       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7190         setInsertPointAfterBundle(E);
7191         LHS = vectorizeTree(E->getOperand(0));
7192         RHS = vectorizeTree(E->getOperand(1));
7193       } else {
7194         setInsertPointAfterBundle(E);
7195         LHS = vectorizeTree(E->getOperand(0));
7196       }
7197 
7198       if (E->VectorizedValue) {
7199         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7200         return E->VectorizedValue;
7201       }
7202 
7203       Value *V0, *V1;
7204       if (Instruction::isBinaryOp(E->getOpcode())) {
7205         V0 = Builder.CreateBinOp(
7206             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7207         V1 = Builder.CreateBinOp(
7208             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7209       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7210         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7211         auto *AltCI = cast<CmpInst>(E->getAltOp());
7212         CmpInst::Predicate AltPred = AltCI->getPredicate();
7213         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7214       } else {
7215         V0 = Builder.CreateCast(
7216             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7217         V1 = Builder.CreateCast(
7218             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7219       }
7220       // Add V0 and V1 to later analysis to try to find and remove matching
7221       // instruction, if any.
7222       for (Value *V : {V0, V1}) {
7223         if (auto *I = dyn_cast<Instruction>(V)) {
7224           GatherShuffleSeq.insert(I);
7225           CSEBlocks.insert(I->getParent());
7226         }
7227       }
7228 
7229       // Create shuffle to take alternate operations from the vector.
7230       // Also, gather up main and alt scalar ops to propagate IR flags to
7231       // each vector operation.
7232       ValueList OpScalars, AltScalars;
7233       SmallVector<int> Mask;
7234       buildShuffleEntryMask(
7235           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7236           [E](Instruction *I) {
7237             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7238             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7239           },
7240           Mask, &OpScalars, &AltScalars);
7241 
7242       propagateIRFlags(V0, OpScalars);
7243       propagateIRFlags(V1, AltScalars);
7244 
7245       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7246       if (auto *I = dyn_cast<Instruction>(V)) {
7247         V = propagateMetadata(I, E->Scalars);
7248         GatherShuffleSeq.insert(I);
7249         CSEBlocks.insert(I->getParent());
7250       }
7251       V = ShuffleBuilder.finalize(V);
7252 
7253       E->VectorizedValue = V;
7254       ++NumVectorInstructions;
7255 
7256       return V;
7257     }
7258     default:
7259     llvm_unreachable("unknown inst");
7260   }
7261   return nullptr;
7262 }
7263 
7264 Value *BoUpSLP::vectorizeTree() {
7265   ExtraValueToDebugLocsMap ExternallyUsedValues;
7266   return vectorizeTree(ExternallyUsedValues);
7267 }
7268 
7269 Value *
7270 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7271   // All blocks must be scheduled before any instructions are inserted.
7272   for (auto &BSIter : BlocksSchedules) {
7273     scheduleBlock(BSIter.second.get());
7274   }
7275 
7276   Builder.SetInsertPoint(&F->getEntryBlock().front());
7277   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7278 
7279   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7280   // vectorized root. InstCombine will then rewrite the entire expression. We
7281   // sign extend the extracted values below.
7282   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7283   if (MinBWs.count(ScalarRoot)) {
7284     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7285       // If current instr is a phi and not the last phi, insert it after the
7286       // last phi node.
7287       if (isa<PHINode>(I))
7288         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7289       else
7290         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7291     }
7292     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7293     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7294     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7295     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7296     VectorizableTree[0]->VectorizedValue = Trunc;
7297   }
7298 
7299   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7300                     << " values .\n");
7301 
7302   // Extract all of the elements with the external uses.
7303   for (const auto &ExternalUse : ExternalUses) {
7304     Value *Scalar = ExternalUse.Scalar;
7305     llvm::User *User = ExternalUse.User;
7306 
7307     // Skip users that we already RAUW. This happens when one instruction
7308     // has multiple uses of the same value.
7309     if (User && !is_contained(Scalar->users(), User))
7310       continue;
7311     TreeEntry *E = getTreeEntry(Scalar);
7312     assert(E && "Invalid scalar");
7313     assert(E->State != TreeEntry::NeedToGather &&
7314            "Extracting from a gather list");
7315 
7316     Value *Vec = E->VectorizedValue;
7317     assert(Vec && "Can't find vectorizable value");
7318 
7319     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7320     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7321       if (Scalar->getType() != Vec->getType()) {
7322         Value *Ex;
7323         // "Reuse" the existing extract to improve final codegen.
7324         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7325           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7326                                             ES->getOperand(1));
7327         } else {
7328           Ex = Builder.CreateExtractElement(Vec, Lane);
7329         }
7330         // If necessary, sign-extend or zero-extend ScalarRoot
7331         // to the larger type.
7332         if (!MinBWs.count(ScalarRoot))
7333           return Ex;
7334         if (MinBWs[ScalarRoot].second)
7335           return Builder.CreateSExt(Ex, Scalar->getType());
7336         return Builder.CreateZExt(Ex, Scalar->getType());
7337       }
7338       assert(isa<FixedVectorType>(Scalar->getType()) &&
7339              isa<InsertElementInst>(Scalar) &&
7340              "In-tree scalar of vector type is not insertelement?");
7341       return Vec;
7342     };
7343     // If User == nullptr, the Scalar is used as extra arg. Generate
7344     // ExtractElement instruction and update the record for this scalar in
7345     // ExternallyUsedValues.
7346     if (!User) {
7347       assert(ExternallyUsedValues.count(Scalar) &&
7348              "Scalar with nullptr as an external user must be registered in "
7349              "ExternallyUsedValues map");
7350       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7351         Builder.SetInsertPoint(VecI->getParent(),
7352                                std::next(VecI->getIterator()));
7353       } else {
7354         Builder.SetInsertPoint(&F->getEntryBlock().front());
7355       }
7356       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7357       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7358       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7359       auto It = ExternallyUsedValues.find(Scalar);
7360       assert(It != ExternallyUsedValues.end() &&
7361              "Externally used scalar is not found in ExternallyUsedValues");
7362       NewInstLocs.append(It->second);
7363       ExternallyUsedValues.erase(Scalar);
7364       // Required to update internally referenced instructions.
7365       Scalar->replaceAllUsesWith(NewInst);
7366       continue;
7367     }
7368 
7369     // Generate extracts for out-of-tree users.
7370     // Find the insertion point for the extractelement lane.
7371     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7372       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7373         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7374           if (PH->getIncomingValue(i) == Scalar) {
7375             Instruction *IncomingTerminator =
7376                 PH->getIncomingBlock(i)->getTerminator();
7377             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7378               Builder.SetInsertPoint(VecI->getParent(),
7379                                      std::next(VecI->getIterator()));
7380             } else {
7381               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7382             }
7383             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7384             CSEBlocks.insert(PH->getIncomingBlock(i));
7385             PH->setOperand(i, NewInst);
7386           }
7387         }
7388       } else {
7389         Builder.SetInsertPoint(cast<Instruction>(User));
7390         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7391         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7392         User->replaceUsesOfWith(Scalar, NewInst);
7393       }
7394     } else {
7395       Builder.SetInsertPoint(&F->getEntryBlock().front());
7396       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7397       CSEBlocks.insert(&F->getEntryBlock());
7398       User->replaceUsesOfWith(Scalar, NewInst);
7399     }
7400 
7401     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7402   }
7403 
7404   // For each vectorized value:
7405   for (auto &TEPtr : VectorizableTree) {
7406     TreeEntry *Entry = TEPtr.get();
7407 
7408     // No need to handle users of gathered values.
7409     if (Entry->State == TreeEntry::NeedToGather)
7410       continue;
7411 
7412     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7413 
7414     // For each lane:
7415     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7416       Value *Scalar = Entry->Scalars[Lane];
7417 
7418 #ifndef NDEBUG
7419       Type *Ty = Scalar->getType();
7420       if (!Ty->isVoidTy()) {
7421         for (User *U : Scalar->users()) {
7422           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7423 
7424           // It is legal to delete users in the ignorelist.
7425           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7426                   (isa_and_nonnull<Instruction>(U) &&
7427                    isDeleted(cast<Instruction>(U)))) &&
7428                  "Deleting out-of-tree value");
7429         }
7430       }
7431 #endif
7432       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7433       eraseInstruction(cast<Instruction>(Scalar));
7434     }
7435   }
7436 
7437   Builder.ClearInsertionPoint();
7438   InstrElementSize.clear();
7439 
7440   return VectorizableTree[0]->VectorizedValue;
7441 }
7442 
7443 void BoUpSLP::optimizeGatherSequence() {
7444   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7445                     << " gather sequences instructions.\n");
7446   // LICM InsertElementInst sequences.
7447   for (Instruction *I : GatherShuffleSeq) {
7448     if (isDeleted(I))
7449       continue;
7450 
7451     // Check if this block is inside a loop.
7452     Loop *L = LI->getLoopFor(I->getParent());
7453     if (!L)
7454       continue;
7455 
7456     // Check if it has a preheader.
7457     BasicBlock *PreHeader = L->getLoopPreheader();
7458     if (!PreHeader)
7459       continue;
7460 
7461     // If the vector or the element that we insert into it are
7462     // instructions that are defined in this basic block then we can't
7463     // hoist this instruction.
7464     if (any_of(I->operands(), [L](Value *V) {
7465           auto *OpI = dyn_cast<Instruction>(V);
7466           return OpI && L->contains(OpI);
7467         }))
7468       continue;
7469 
7470     // We can hoist this instruction. Move it to the pre-header.
7471     I->moveBefore(PreHeader->getTerminator());
7472   }
7473 
7474   // Make a list of all reachable blocks in our CSE queue.
7475   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7476   CSEWorkList.reserve(CSEBlocks.size());
7477   for (BasicBlock *BB : CSEBlocks)
7478     if (DomTreeNode *N = DT->getNode(BB)) {
7479       assert(DT->isReachableFromEntry(N));
7480       CSEWorkList.push_back(N);
7481     }
7482 
7483   // Sort blocks by domination. This ensures we visit a block after all blocks
7484   // dominating it are visited.
7485   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7486     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7487            "Different nodes should have different DFS numbers");
7488     return A->getDFSNumIn() < B->getDFSNumIn();
7489   });
7490 
7491   // Less defined shuffles can be replaced by the more defined copies.
7492   // Between two shuffles one is less defined if it has the same vector operands
7493   // and its mask indeces are the same as in the first one or undefs. E.g.
7494   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7495   // poison, <0, 0, 0, 0>.
7496   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7497                                            SmallVectorImpl<int> &NewMask) {
7498     if (I1->getType() != I2->getType())
7499       return false;
7500     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7501     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7502     if (!SI1 || !SI2)
7503       return I1->isIdenticalTo(I2);
7504     if (SI1->isIdenticalTo(SI2))
7505       return true;
7506     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7507       if (SI1->getOperand(I) != SI2->getOperand(I))
7508         return false;
7509     // Check if the second instruction is more defined than the first one.
7510     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7511     ArrayRef<int> SM1 = SI1->getShuffleMask();
7512     // Count trailing undefs in the mask to check the final number of used
7513     // registers.
7514     unsigned LastUndefsCnt = 0;
7515     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7516       if (SM1[I] == UndefMaskElem)
7517         ++LastUndefsCnt;
7518       else
7519         LastUndefsCnt = 0;
7520       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7521           NewMask[I] != SM1[I])
7522         return false;
7523       if (NewMask[I] == UndefMaskElem)
7524         NewMask[I] = SM1[I];
7525     }
7526     // Check if the last undefs actually change the final number of used vector
7527     // registers.
7528     return SM1.size() - LastUndefsCnt > 1 &&
7529            TTI->getNumberOfParts(SI1->getType()) ==
7530                TTI->getNumberOfParts(
7531                    FixedVectorType::get(SI1->getType()->getElementType(),
7532                                         SM1.size() - LastUndefsCnt));
7533   };
7534   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7535   // instructions. TODO: We can further optimize this scan if we split the
7536   // instructions into different buckets based on the insert lane.
7537   SmallVector<Instruction *, 16> Visited;
7538   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7539     assert(*I &&
7540            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7541            "Worklist not sorted properly!");
7542     BasicBlock *BB = (*I)->getBlock();
7543     // For all instructions in blocks containing gather sequences:
7544     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7545       if (isDeleted(&In))
7546         continue;
7547       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7548           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7549         continue;
7550 
7551       // Check if we can replace this instruction with any of the
7552       // visited instructions.
7553       bool Replaced = false;
7554       for (Instruction *&V : Visited) {
7555         SmallVector<int> NewMask;
7556         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7557             DT->dominates(V->getParent(), In.getParent())) {
7558           In.replaceAllUsesWith(V);
7559           eraseInstruction(&In);
7560           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7561             if (!NewMask.empty())
7562               SI->setShuffleMask(NewMask);
7563           Replaced = true;
7564           break;
7565         }
7566         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7567             GatherShuffleSeq.contains(V) &&
7568             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7569             DT->dominates(In.getParent(), V->getParent())) {
7570           In.moveAfter(V);
7571           V->replaceAllUsesWith(&In);
7572           eraseInstruction(V);
7573           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7574             if (!NewMask.empty())
7575               SI->setShuffleMask(NewMask);
7576           V = &In;
7577           Replaced = true;
7578           break;
7579         }
7580       }
7581       if (!Replaced) {
7582         assert(!is_contained(Visited, &In));
7583         Visited.push_back(&In);
7584       }
7585     }
7586   }
7587   CSEBlocks.clear();
7588   GatherShuffleSeq.clear();
7589 }
7590 
7591 BoUpSLP::ScheduleData *
7592 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7593   ScheduleData *Bundle = nullptr;
7594   ScheduleData *PrevInBundle = nullptr;
7595   for (Value *V : VL) {
7596     ScheduleData *BundleMember = getScheduleData(V);
7597     assert(BundleMember &&
7598            "no ScheduleData for bundle member "
7599            "(maybe not in same basic block)");
7600     assert(BundleMember->isSchedulingEntity() &&
7601            "bundle member already part of other bundle");
7602     if (PrevInBundle) {
7603       PrevInBundle->NextInBundle = BundleMember;
7604     } else {
7605       Bundle = BundleMember;
7606     }
7607 
7608     // Group the instructions to a bundle.
7609     BundleMember->FirstInBundle = Bundle;
7610     PrevInBundle = BundleMember;
7611   }
7612   assert(Bundle && "Failed to find schedule bundle");
7613   return Bundle;
7614 }
7615 
7616 // Groups the instructions to a bundle (which is then a single scheduling entity)
7617 // and schedules instructions until the bundle gets ready.
7618 Optional<BoUpSLP::ScheduleData *>
7619 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7620                                             const InstructionsState &S) {
7621   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7622   // instructions.
7623   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
7624     return nullptr;
7625 
7626   // Initialize the instruction bundle.
7627   Instruction *OldScheduleEnd = ScheduleEnd;
7628   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7629 
7630   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7631                                                          ScheduleData *Bundle) {
7632     // The scheduling region got new instructions at the lower end (or it is a
7633     // new region for the first bundle). This makes it necessary to
7634     // recalculate all dependencies.
7635     // It is seldom that this needs to be done a second time after adding the
7636     // initial bundle to the region.
7637     if (ScheduleEnd != OldScheduleEnd) {
7638       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7639         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7640       ReSchedule = true;
7641     }
7642     if (Bundle) {
7643       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7644                         << " in block " << BB->getName() << "\n");
7645       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7646     }
7647 
7648     if (ReSchedule) {
7649       resetSchedule();
7650       initialFillReadyList(ReadyInsts);
7651     }
7652 
7653     // Now try to schedule the new bundle or (if no bundle) just calculate
7654     // dependencies. As soon as the bundle is "ready" it means that there are no
7655     // cyclic dependencies and we can schedule it. Note that's important that we
7656     // don't "schedule" the bundle yet (see cancelScheduling).
7657     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7658            !ReadyInsts.empty()) {
7659       ScheduleData *Picked = ReadyInsts.pop_back_val();
7660       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7661              "must be ready to schedule");
7662       schedule(Picked, ReadyInsts);
7663     }
7664   };
7665 
7666   // Make sure that the scheduling region contains all
7667   // instructions of the bundle.
7668   for (Value *V : VL) {
7669     if (!extendSchedulingRegion(V, S)) {
7670       // If the scheduling region got new instructions at the lower end (or it
7671       // is a new region for the first bundle). This makes it necessary to
7672       // recalculate all dependencies.
7673       // Otherwise the compiler may crash trying to incorrectly calculate
7674       // dependencies and emit instruction in the wrong order at the actual
7675       // scheduling.
7676       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7677       return None;
7678     }
7679   }
7680 
7681   bool ReSchedule = false;
7682   for (Value *V : VL) {
7683     ScheduleData *BundleMember = getScheduleData(V);
7684     assert(BundleMember &&
7685            "no ScheduleData for bundle member (maybe not in same basic block)");
7686 
7687     // Make sure we don't leave the pieces of the bundle in the ready list when
7688     // whole bundle might not be ready.
7689     ReadyInsts.remove(BundleMember);
7690 
7691     if (!BundleMember->IsScheduled)
7692       continue;
7693     // A bundle member was scheduled as single instruction before and now
7694     // needs to be scheduled as part of the bundle. We just get rid of the
7695     // existing schedule.
7696     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7697                       << " was already scheduled\n");
7698     ReSchedule = true;
7699   }
7700 
7701   auto *Bundle = buildBundle(VL);
7702   TryScheduleBundleImpl(ReSchedule, Bundle);
7703   if (!Bundle->isReady()) {
7704     cancelScheduling(VL, S.OpValue);
7705     return None;
7706   }
7707   return Bundle;
7708 }
7709 
7710 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7711                                                 Value *OpValue) {
7712   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
7713     return;
7714 
7715   ScheduleData *Bundle = getScheduleData(OpValue);
7716   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7717   assert(!Bundle->IsScheduled &&
7718          "Can't cancel bundle which is already scheduled");
7719   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
7720          "tried to unbundle something which is not a bundle");
7721 
7722   // Remove the bundle from the ready list.
7723   if (Bundle->isReady())
7724     ReadyInsts.remove(Bundle);
7725 
7726   // Un-bundle: make single instructions out of the bundle.
7727   ScheduleData *BundleMember = Bundle;
7728   while (BundleMember) {
7729     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7730     BundleMember->FirstInBundle = BundleMember;
7731     ScheduleData *Next = BundleMember->NextInBundle;
7732     BundleMember->NextInBundle = nullptr;
7733     if (BundleMember->unscheduledDepsInBundle() == 0) {
7734       ReadyInsts.insert(BundleMember);
7735     }
7736     BundleMember = Next;
7737   }
7738 }
7739 
7740 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7741   // Allocate a new ScheduleData for the instruction.
7742   if (ChunkPos >= ChunkSize) {
7743     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7744     ChunkPos = 0;
7745   }
7746   return &(ScheduleDataChunks.back()[ChunkPos++]);
7747 }
7748 
7749 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7750                                                       const InstructionsState &S) {
7751   if (getScheduleData(V, isOneOf(S, V)))
7752     return true;
7753   Instruction *I = dyn_cast<Instruction>(V);
7754   assert(I && "bundle member must be an instruction");
7755   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7756          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7757          "be scheduled");
7758   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7759     ScheduleData *ISD = getScheduleData(I);
7760     if (!ISD)
7761       return false;
7762     assert(isInSchedulingRegion(ISD) &&
7763            "ScheduleData not in scheduling region");
7764     ScheduleData *SD = allocateScheduleDataChunks();
7765     SD->Inst = I;
7766     SD->init(SchedulingRegionID, S.OpValue);
7767     ExtraScheduleDataMap[I][S.OpValue] = SD;
7768     return true;
7769   };
7770   if (CheckScheduleForI(I))
7771     return true;
7772   if (!ScheduleStart) {
7773     // It's the first instruction in the new region.
7774     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7775     ScheduleStart = I;
7776     ScheduleEnd = I->getNextNode();
7777     if (isOneOf(S, I) != I)
7778       CheckScheduleForI(I);
7779     assert(ScheduleEnd && "tried to vectorize a terminator?");
7780     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7781     return true;
7782   }
7783   // Search up and down at the same time, because we don't know if the new
7784   // instruction is above or below the existing scheduling region.
7785   BasicBlock::reverse_iterator UpIter =
7786       ++ScheduleStart->getIterator().getReverse();
7787   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7788   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7789   BasicBlock::iterator LowerEnd = BB->end();
7790   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7791          &*DownIter != I) {
7792     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7793       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7794       return false;
7795     }
7796 
7797     ++UpIter;
7798     ++DownIter;
7799   }
7800   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7801     assert(I->getParent() == ScheduleStart->getParent() &&
7802            "Instruction is in wrong basic block.");
7803     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7804     ScheduleStart = I;
7805     if (isOneOf(S, I) != I)
7806       CheckScheduleForI(I);
7807     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7808                       << "\n");
7809     return true;
7810   }
7811   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7812          "Expected to reach top of the basic block or instruction down the "
7813          "lower end.");
7814   assert(I->getParent() == ScheduleEnd->getParent() &&
7815          "Instruction is in wrong basic block.");
7816   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7817                    nullptr);
7818   ScheduleEnd = I->getNextNode();
7819   if (isOneOf(S, I) != I)
7820     CheckScheduleForI(I);
7821   assert(ScheduleEnd && "tried to vectorize a terminator?");
7822   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7823   return true;
7824 }
7825 
7826 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7827                                                 Instruction *ToI,
7828                                                 ScheduleData *PrevLoadStore,
7829                                                 ScheduleData *NextLoadStore) {
7830   ScheduleData *CurrentLoadStore = PrevLoadStore;
7831   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7832     ScheduleData *SD = ScheduleDataMap[I];
7833     if (!SD) {
7834       SD = allocateScheduleDataChunks();
7835       ScheduleDataMap[I] = SD;
7836       SD->Inst = I;
7837     }
7838     assert(!isInSchedulingRegion(SD) &&
7839            "new ScheduleData already in scheduling region");
7840     SD->init(SchedulingRegionID, I);
7841 
7842     if (I->mayReadOrWriteMemory() &&
7843         (!isa<IntrinsicInst>(I) ||
7844          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7845           cast<IntrinsicInst>(I)->getIntrinsicID() !=
7846               Intrinsic::pseudoprobe))) {
7847       // Update the linked list of memory accessing instructions.
7848       if (CurrentLoadStore) {
7849         CurrentLoadStore->NextLoadStore = SD;
7850       } else {
7851         FirstLoadStoreInRegion = SD;
7852       }
7853       CurrentLoadStore = SD;
7854     }
7855   }
7856   if (NextLoadStore) {
7857     if (CurrentLoadStore)
7858       CurrentLoadStore->NextLoadStore = NextLoadStore;
7859   } else {
7860     LastLoadStoreInRegion = CurrentLoadStore;
7861   }
7862 }
7863 
7864 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
7865                                                      bool InsertInReadyList,
7866                                                      BoUpSLP *SLP) {
7867   assert(SD->isSchedulingEntity());
7868 
7869   SmallVector<ScheduleData *, 10> WorkList;
7870   WorkList.push_back(SD);
7871 
7872   while (!WorkList.empty()) {
7873     ScheduleData *SD = WorkList.pop_back_val();
7874     for (ScheduleData *BundleMember = SD; BundleMember;
7875          BundleMember = BundleMember->NextInBundle) {
7876       assert(isInSchedulingRegion(BundleMember));
7877       if (BundleMember->hasValidDependencies())
7878         continue;
7879 
7880       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
7881                  << "\n");
7882       BundleMember->Dependencies = 0;
7883       BundleMember->resetUnscheduledDeps();
7884 
7885       // Handle def-use chain dependencies.
7886       if (BundleMember->OpValue != BundleMember->Inst) {
7887         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
7888           BundleMember->Dependencies++;
7889           ScheduleData *DestBundle = UseSD->FirstInBundle;
7890           if (!DestBundle->IsScheduled)
7891             BundleMember->incrementUnscheduledDeps(1);
7892           if (!DestBundle->hasValidDependencies())
7893             WorkList.push_back(DestBundle);
7894         }
7895       } else {
7896         for (User *U : BundleMember->Inst->users()) {
7897           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
7898             BundleMember->Dependencies++;
7899             ScheduleData *DestBundle = UseSD->FirstInBundle;
7900             if (!DestBundle->IsScheduled)
7901               BundleMember->incrementUnscheduledDeps(1);
7902             if (!DestBundle->hasValidDependencies())
7903               WorkList.push_back(DestBundle);
7904           }
7905         }
7906       }
7907 
7908       // Handle the memory dependencies (if any).
7909       ScheduleData *DepDest = BundleMember->NextLoadStore;
7910       if (!DepDest)
7911         continue;
7912       Instruction *SrcInst = BundleMember->Inst;
7913       assert(SrcInst->mayReadOrWriteMemory() &&
7914              "NextLoadStore list for non memory effecting bundle?");
7915       MemoryLocation SrcLoc = getLocation(SrcInst);
7916       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7917       unsigned numAliased = 0;
7918       unsigned DistToSrc = 1;
7919 
7920       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
7921         assert(isInSchedulingRegion(DepDest));
7922 
7923         // We have two limits to reduce the complexity:
7924         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7925         //    SLP->isAliased (which is the expensive part in this loop).
7926         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7927         //    the whole loop (even if the loop is fast, it's quadratic).
7928         //    It's important for the loop break condition (see below) to
7929         //    check this limit even between two read-only instructions.
7930         if (DistToSrc >= MaxMemDepDistance ||
7931             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7932              (numAliased >= AliasedCheckLimit ||
7933               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7934 
7935           // We increment the counter only if the locations are aliased
7936           // (instead of counting all alias checks). This gives a better
7937           // balance between reduced runtime and accurate dependencies.
7938           numAliased++;
7939 
7940           DepDest->MemoryDependencies.push_back(BundleMember);
7941           BundleMember->Dependencies++;
7942           ScheduleData *DestBundle = DepDest->FirstInBundle;
7943           if (!DestBundle->IsScheduled) {
7944             BundleMember->incrementUnscheduledDeps(1);
7945           }
7946           if (!DestBundle->hasValidDependencies()) {
7947             WorkList.push_back(DestBundle);
7948           }
7949         }
7950 
7951         // Example, explaining the loop break condition: Let's assume our
7952         // starting instruction is i0 and MaxMemDepDistance = 3.
7953         //
7954         //                      +--------v--v--v
7955         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7956         //             +--------^--^--^
7957         //
7958         // MaxMemDepDistance let us stop alias-checking at i3 and we add
7959         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7960         // Previously we already added dependencies from i3 to i6,i7,i8
7961         // (because of MaxMemDepDistance). As we added a dependency from
7962         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7963         // and we can abort this loop at i6.
7964         if (DistToSrc >= 2 * MaxMemDepDistance)
7965           break;
7966         DistToSrc++;
7967       }
7968     }
7969     if (InsertInReadyList && SD->isReady()) {
7970       ReadyInsts.insert(SD);
7971       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7972                         << "\n");
7973     }
7974   }
7975 }
7976 
7977 void BoUpSLP::BlockScheduling::resetSchedule() {
7978   assert(ScheduleStart &&
7979          "tried to reset schedule on block which has not been scheduled");
7980   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7981     doForAllOpcodes(I, [&](ScheduleData *SD) {
7982       assert(isInSchedulingRegion(SD) &&
7983              "ScheduleData not in scheduling region");
7984       SD->IsScheduled = false;
7985       SD->resetUnscheduledDeps();
7986     });
7987   }
7988   ReadyInsts.clear();
7989 }
7990 
7991 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7992   if (!BS->ScheduleStart)
7993     return;
7994 
7995   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7996 
7997   BS->resetSchedule();
7998 
7999   // For the real scheduling we use a more sophisticated ready-list: it is
8000   // sorted by the original instruction location. This lets the final schedule
8001   // be as  close as possible to the original instruction order.
8002   struct ScheduleDataCompare {
8003     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8004       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8005     }
8006   };
8007   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8008 
8009   // Ensure that all dependency data is updated and fill the ready-list with
8010   // initial instructions.
8011   int Idx = 0;
8012   int NumToSchedule = 0;
8013   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8014        I = I->getNextNode()) {
8015     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
8016       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8017               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
8018              "scheduler and vectorizer bundle mismatch");
8019       SD->FirstInBundle->SchedulingPriority = Idx++;
8020       if (SD->isSchedulingEntity()) {
8021         BS->calculateDependencies(SD, false, this);
8022         NumToSchedule++;
8023       }
8024     });
8025   }
8026   BS->initialFillReadyList(ReadyInsts);
8027 
8028   Instruction *LastScheduledInst = BS->ScheduleEnd;
8029 
8030   // Do the "real" scheduling.
8031   while (!ReadyInsts.empty()) {
8032     ScheduleData *picked = *ReadyInsts.begin();
8033     ReadyInsts.erase(ReadyInsts.begin());
8034 
8035     // Move the scheduled instruction(s) to their dedicated places, if not
8036     // there yet.
8037     for (ScheduleData *BundleMember = picked; BundleMember;
8038          BundleMember = BundleMember->NextInBundle) {
8039       Instruction *pickedInst = BundleMember->Inst;
8040       if (pickedInst->getNextNode() != LastScheduledInst)
8041         pickedInst->moveBefore(LastScheduledInst);
8042       LastScheduledInst = pickedInst;
8043     }
8044 
8045     BS->schedule(picked, ReadyInsts);
8046     NumToSchedule--;
8047   }
8048   assert(NumToSchedule == 0 && "could not schedule all instructions");
8049 
8050   // Check that we didn't break any of our invariants.
8051 #ifdef EXPENSIVE_CHECKS
8052   BS->verify();
8053 #endif
8054 
8055 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8056   // Check that all schedulable entities got scheduled
8057   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8058     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8059       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8060         assert(SD->IsScheduled && "must be scheduled at this point");
8061       }
8062     });
8063   }
8064 #endif
8065 
8066   // Avoid duplicate scheduling of the block.
8067   BS->ScheduleStart = nullptr;
8068 }
8069 
8070 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8071   // If V is a store, just return the width of the stored value (or value
8072   // truncated just before storing) without traversing the expression tree.
8073   // This is the common case.
8074   if (auto *Store = dyn_cast<StoreInst>(V)) {
8075     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8076       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8077     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8078   }
8079 
8080   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8081     return getVectorElementSize(IEI->getOperand(1));
8082 
8083   auto E = InstrElementSize.find(V);
8084   if (E != InstrElementSize.end())
8085     return E->second;
8086 
8087   // If V is not a store, we can traverse the expression tree to find loads
8088   // that feed it. The type of the loaded value may indicate a more suitable
8089   // width than V's type. We want to base the vector element size on the width
8090   // of memory operations where possible.
8091   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8092   SmallPtrSet<Instruction *, 16> Visited;
8093   if (auto *I = dyn_cast<Instruction>(V)) {
8094     Worklist.emplace_back(I, I->getParent());
8095     Visited.insert(I);
8096   }
8097 
8098   // Traverse the expression tree in bottom-up order looking for loads. If we
8099   // encounter an instruction we don't yet handle, we give up.
8100   auto Width = 0u;
8101   while (!Worklist.empty()) {
8102     Instruction *I;
8103     BasicBlock *Parent;
8104     std::tie(I, Parent) = Worklist.pop_back_val();
8105 
8106     // We should only be looking at scalar instructions here. If the current
8107     // instruction has a vector type, skip.
8108     auto *Ty = I->getType();
8109     if (isa<VectorType>(Ty))
8110       continue;
8111 
8112     // If the current instruction is a load, update MaxWidth to reflect the
8113     // width of the loaded value.
8114     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8115         isa<ExtractValueInst>(I))
8116       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8117 
8118     // Otherwise, we need to visit the operands of the instruction. We only
8119     // handle the interesting cases from buildTree here. If an operand is an
8120     // instruction we haven't yet visited and from the same basic block as the
8121     // user or the use is a PHI node, we add it to the worklist.
8122     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8123              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8124              isa<UnaryOperator>(I)) {
8125       for (Use &U : I->operands())
8126         if (auto *J = dyn_cast<Instruction>(U.get()))
8127           if (Visited.insert(J).second &&
8128               (isa<PHINode>(I) || J->getParent() == Parent))
8129             Worklist.emplace_back(J, J->getParent());
8130     } else {
8131       break;
8132     }
8133   }
8134 
8135   // If we didn't encounter a memory access in the expression tree, or if we
8136   // gave up for some reason, just return the width of V. Otherwise, return the
8137   // maximum width we found.
8138   if (!Width) {
8139     if (auto *CI = dyn_cast<CmpInst>(V))
8140       V = CI->getOperand(0);
8141     Width = DL->getTypeSizeInBits(V->getType());
8142   }
8143 
8144   for (Instruction *I : Visited)
8145     InstrElementSize[I] = Width;
8146 
8147   return Width;
8148 }
8149 
8150 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8151 // smaller type with a truncation. We collect the values that will be demoted
8152 // in ToDemote and additional roots that require investigating in Roots.
8153 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8154                                   SmallVectorImpl<Value *> &ToDemote,
8155                                   SmallVectorImpl<Value *> &Roots) {
8156   // We can always demote constants.
8157   if (isa<Constant>(V)) {
8158     ToDemote.push_back(V);
8159     return true;
8160   }
8161 
8162   // If the value is not an instruction in the expression with only one use, it
8163   // cannot be demoted.
8164   auto *I = dyn_cast<Instruction>(V);
8165   if (!I || !I->hasOneUse() || !Expr.count(I))
8166     return false;
8167 
8168   switch (I->getOpcode()) {
8169 
8170   // We can always demote truncations and extensions. Since truncations can
8171   // seed additional demotion, we save the truncated value.
8172   case Instruction::Trunc:
8173     Roots.push_back(I->getOperand(0));
8174     break;
8175   case Instruction::ZExt:
8176   case Instruction::SExt:
8177     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8178         isa<InsertElementInst>(I->getOperand(0)))
8179       return false;
8180     break;
8181 
8182   // We can demote certain binary operations if we can demote both of their
8183   // operands.
8184   case Instruction::Add:
8185   case Instruction::Sub:
8186   case Instruction::Mul:
8187   case Instruction::And:
8188   case Instruction::Or:
8189   case Instruction::Xor:
8190     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8191         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8192       return false;
8193     break;
8194 
8195   // We can demote selects if we can demote their true and false values.
8196   case Instruction::Select: {
8197     SelectInst *SI = cast<SelectInst>(I);
8198     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8199         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8200       return false;
8201     break;
8202   }
8203 
8204   // We can demote phis if we can demote all their incoming operands. Note that
8205   // we don't need to worry about cycles since we ensure single use above.
8206   case Instruction::PHI: {
8207     PHINode *PN = cast<PHINode>(I);
8208     for (Value *IncValue : PN->incoming_values())
8209       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8210         return false;
8211     break;
8212   }
8213 
8214   // Otherwise, conservatively give up.
8215   default:
8216     return false;
8217   }
8218 
8219   // Record the value that we can demote.
8220   ToDemote.push_back(V);
8221   return true;
8222 }
8223 
8224 void BoUpSLP::computeMinimumValueSizes() {
8225   // If there are no external uses, the expression tree must be rooted by a
8226   // store. We can't demote in-memory values, so there is nothing to do here.
8227   if (ExternalUses.empty())
8228     return;
8229 
8230   // We only attempt to truncate integer expressions.
8231   auto &TreeRoot = VectorizableTree[0]->Scalars;
8232   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8233   if (!TreeRootIT)
8234     return;
8235 
8236   // If the expression is not rooted by a store, these roots should have
8237   // external uses. We will rely on InstCombine to rewrite the expression in
8238   // the narrower type. However, InstCombine only rewrites single-use values.
8239   // This means that if a tree entry other than a root is used externally, it
8240   // must have multiple uses and InstCombine will not rewrite it. The code
8241   // below ensures that only the roots are used externally.
8242   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8243   for (auto &EU : ExternalUses)
8244     if (!Expr.erase(EU.Scalar))
8245       return;
8246   if (!Expr.empty())
8247     return;
8248 
8249   // Collect the scalar values of the vectorizable expression. We will use this
8250   // context to determine which values can be demoted. If we see a truncation,
8251   // we mark it as seeding another demotion.
8252   for (auto &EntryPtr : VectorizableTree)
8253     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8254 
8255   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8256   // have a single external user that is not in the vectorizable tree.
8257   for (auto *Root : TreeRoot)
8258     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8259       return;
8260 
8261   // Conservatively determine if we can actually truncate the roots of the
8262   // expression. Collect the values that can be demoted in ToDemote and
8263   // additional roots that require investigating in Roots.
8264   SmallVector<Value *, 32> ToDemote;
8265   SmallVector<Value *, 4> Roots;
8266   for (auto *Root : TreeRoot)
8267     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8268       return;
8269 
8270   // The maximum bit width required to represent all the values that can be
8271   // demoted without loss of precision. It would be safe to truncate the roots
8272   // of the expression to this width.
8273   auto MaxBitWidth = 8u;
8274 
8275   // We first check if all the bits of the roots are demanded. If they're not,
8276   // we can truncate the roots to this narrower type.
8277   for (auto *Root : TreeRoot) {
8278     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8279     MaxBitWidth = std::max<unsigned>(
8280         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8281   }
8282 
8283   // True if the roots can be zero-extended back to their original type, rather
8284   // than sign-extended. We know that if the leading bits are not demanded, we
8285   // can safely zero-extend. So we initialize IsKnownPositive to True.
8286   bool IsKnownPositive = true;
8287 
8288   // If all the bits of the roots are demanded, we can try a little harder to
8289   // compute a narrower type. This can happen, for example, if the roots are
8290   // getelementptr indices. InstCombine promotes these indices to the pointer
8291   // width. Thus, all their bits are technically demanded even though the
8292   // address computation might be vectorized in a smaller type.
8293   //
8294   // We start by looking at each entry that can be demoted. We compute the
8295   // maximum bit width required to store the scalar by using ValueTracking to
8296   // compute the number of high-order bits we can truncate.
8297   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8298       llvm::all_of(TreeRoot, [](Value *R) {
8299         assert(R->hasOneUse() && "Root should have only one use!");
8300         return isa<GetElementPtrInst>(R->user_back());
8301       })) {
8302     MaxBitWidth = 8u;
8303 
8304     // Determine if the sign bit of all the roots is known to be zero. If not,
8305     // IsKnownPositive is set to False.
8306     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8307       KnownBits Known = computeKnownBits(R, *DL);
8308       return Known.isNonNegative();
8309     });
8310 
8311     // Determine the maximum number of bits required to store the scalar
8312     // values.
8313     for (auto *Scalar : ToDemote) {
8314       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8315       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8316       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8317     }
8318 
8319     // If we can't prove that the sign bit is zero, we must add one to the
8320     // maximum bit width to account for the unknown sign bit. This preserves
8321     // the existing sign bit so we can safely sign-extend the root back to the
8322     // original type. Otherwise, if we know the sign bit is zero, we will
8323     // zero-extend the root instead.
8324     //
8325     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8326     //        one to the maximum bit width will yield a larger-than-necessary
8327     //        type. In general, we need to add an extra bit only if we can't
8328     //        prove that the upper bit of the original type is equal to the
8329     //        upper bit of the proposed smaller type. If these two bits are the
8330     //        same (either zero or one) we know that sign-extending from the
8331     //        smaller type will result in the same value. Here, since we can't
8332     //        yet prove this, we are just making the proposed smaller type
8333     //        larger to ensure correctness.
8334     if (!IsKnownPositive)
8335       ++MaxBitWidth;
8336   }
8337 
8338   // Round MaxBitWidth up to the next power-of-two.
8339   if (!isPowerOf2_64(MaxBitWidth))
8340     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8341 
8342   // If the maximum bit width we compute is less than the with of the roots'
8343   // type, we can proceed with the narrowing. Otherwise, do nothing.
8344   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8345     return;
8346 
8347   // If we can truncate the root, we must collect additional values that might
8348   // be demoted as a result. That is, those seeded by truncations we will
8349   // modify.
8350   while (!Roots.empty())
8351     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8352 
8353   // Finally, map the values we can demote to the maximum bit with we computed.
8354   for (auto *Scalar : ToDemote)
8355     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8356 }
8357 
8358 namespace {
8359 
8360 /// The SLPVectorizer Pass.
8361 struct SLPVectorizer : public FunctionPass {
8362   SLPVectorizerPass Impl;
8363 
8364   /// Pass identification, replacement for typeid
8365   static char ID;
8366 
8367   explicit SLPVectorizer() : FunctionPass(ID) {
8368     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8369   }
8370 
8371   bool doInitialization(Module &M) override { return false; }
8372 
8373   bool runOnFunction(Function &F) override {
8374     if (skipFunction(F))
8375       return false;
8376 
8377     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8378     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8379     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8380     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8381     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8382     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8383     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8384     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8385     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8386     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8387 
8388     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8389   }
8390 
8391   void getAnalysisUsage(AnalysisUsage &AU) const override {
8392     FunctionPass::getAnalysisUsage(AU);
8393     AU.addRequired<AssumptionCacheTracker>();
8394     AU.addRequired<ScalarEvolutionWrapperPass>();
8395     AU.addRequired<AAResultsWrapperPass>();
8396     AU.addRequired<TargetTransformInfoWrapperPass>();
8397     AU.addRequired<LoopInfoWrapperPass>();
8398     AU.addRequired<DominatorTreeWrapperPass>();
8399     AU.addRequired<DemandedBitsWrapperPass>();
8400     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8401     AU.addRequired<InjectTLIMappingsLegacy>();
8402     AU.addPreserved<LoopInfoWrapperPass>();
8403     AU.addPreserved<DominatorTreeWrapperPass>();
8404     AU.addPreserved<AAResultsWrapperPass>();
8405     AU.addPreserved<GlobalsAAWrapperPass>();
8406     AU.setPreservesCFG();
8407   }
8408 };
8409 
8410 } // end anonymous namespace
8411 
8412 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8413   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8414   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8415   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8416   auto *AA = &AM.getResult<AAManager>(F);
8417   auto *LI = &AM.getResult<LoopAnalysis>(F);
8418   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8419   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8420   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8421   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8422 
8423   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8424   if (!Changed)
8425     return PreservedAnalyses::all();
8426 
8427   PreservedAnalyses PA;
8428   PA.preserveSet<CFGAnalyses>();
8429   return PA;
8430 }
8431 
8432 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8433                                 TargetTransformInfo *TTI_,
8434                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8435                                 LoopInfo *LI_, DominatorTree *DT_,
8436                                 AssumptionCache *AC_, DemandedBits *DB_,
8437                                 OptimizationRemarkEmitter *ORE_) {
8438   if (!RunSLPVectorization)
8439     return false;
8440   SE = SE_;
8441   TTI = TTI_;
8442   TLI = TLI_;
8443   AA = AA_;
8444   LI = LI_;
8445   DT = DT_;
8446   AC = AC_;
8447   DB = DB_;
8448   DL = &F.getParent()->getDataLayout();
8449 
8450   Stores.clear();
8451   GEPs.clear();
8452   bool Changed = false;
8453 
8454   // If the target claims to have no vector registers don't attempt
8455   // vectorization.
8456   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8457     LLVM_DEBUG(
8458         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8459     return false;
8460   }
8461 
8462   // Don't vectorize when the attribute NoImplicitFloat is used.
8463   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8464     return false;
8465 
8466   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8467 
8468   // Use the bottom up slp vectorizer to construct chains that start with
8469   // store instructions.
8470   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8471 
8472   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8473   // delete instructions.
8474 
8475   // Update DFS numbers now so that we can use them for ordering.
8476   DT->updateDFSNumbers();
8477 
8478   // Scan the blocks in the function in post order.
8479   for (auto BB : post_order(&F.getEntryBlock())) {
8480     collectSeedInstructions(BB);
8481 
8482     // Vectorize trees that end at stores.
8483     if (!Stores.empty()) {
8484       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8485                         << " underlying objects.\n");
8486       Changed |= vectorizeStoreChains(R);
8487     }
8488 
8489     // Vectorize trees that end at reductions.
8490     Changed |= vectorizeChainsInBlock(BB, R);
8491 
8492     // Vectorize the index computations of getelementptr instructions. This
8493     // is primarily intended to catch gather-like idioms ending at
8494     // non-consecutive loads.
8495     if (!GEPs.empty()) {
8496       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8497                         << " underlying objects.\n");
8498       Changed |= vectorizeGEPIndices(BB, R);
8499     }
8500   }
8501 
8502   if (Changed) {
8503     R.optimizeGatherSequence();
8504     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8505   }
8506   return Changed;
8507 }
8508 
8509 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8510                                             unsigned Idx) {
8511   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8512                     << "\n");
8513   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8514   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8515   unsigned VF = Chain.size();
8516 
8517   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8518     return false;
8519 
8520   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8521                     << "\n");
8522 
8523   R.buildTree(Chain);
8524   if (R.isTreeTinyAndNotFullyVectorizable())
8525     return false;
8526   if (R.isLoadCombineCandidate())
8527     return false;
8528   R.reorderTopToBottom();
8529   R.reorderBottomToTop();
8530   R.buildExternalUses();
8531 
8532   R.computeMinimumValueSizes();
8533 
8534   InstructionCost Cost = R.getTreeCost();
8535 
8536   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8537   if (Cost < -SLPCostThreshold) {
8538     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8539 
8540     using namespace ore;
8541 
8542     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8543                                         cast<StoreInst>(Chain[0]))
8544                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8545                      << " and with tree size "
8546                      << NV("TreeSize", R.getTreeSize()));
8547 
8548     R.vectorizeTree();
8549     return true;
8550   }
8551 
8552   return false;
8553 }
8554 
8555 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8556                                         BoUpSLP &R) {
8557   // We may run into multiple chains that merge into a single chain. We mark the
8558   // stores that we vectorized so that we don't visit the same store twice.
8559   BoUpSLP::ValueSet VectorizedStores;
8560   bool Changed = false;
8561 
8562   int E = Stores.size();
8563   SmallBitVector Tails(E, false);
8564   int MaxIter = MaxStoreLookup.getValue();
8565   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8566       E, std::make_pair(E, INT_MAX));
8567   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8568   int IterCnt;
8569   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8570                                   &CheckedPairs,
8571                                   &ConsecutiveChain](int K, int Idx) {
8572     if (IterCnt >= MaxIter)
8573       return true;
8574     if (CheckedPairs[Idx].test(K))
8575       return ConsecutiveChain[K].second == 1 &&
8576              ConsecutiveChain[K].first == Idx;
8577     ++IterCnt;
8578     CheckedPairs[Idx].set(K);
8579     CheckedPairs[K].set(Idx);
8580     Optional<int> Diff = getPointersDiff(
8581         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8582         Stores[Idx]->getValueOperand()->getType(),
8583         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8584     if (!Diff || *Diff == 0)
8585       return false;
8586     int Val = *Diff;
8587     if (Val < 0) {
8588       if (ConsecutiveChain[Idx].second > -Val) {
8589         Tails.set(K);
8590         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8591       }
8592       return false;
8593     }
8594     if (ConsecutiveChain[K].second <= Val)
8595       return false;
8596 
8597     Tails.set(Idx);
8598     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8599     return Val == 1;
8600   };
8601   // Do a quadratic search on all of the given stores in reverse order and find
8602   // all of the pairs of stores that follow each other.
8603   for (int Idx = E - 1; Idx >= 0; --Idx) {
8604     // If a store has multiple consecutive store candidates, search according
8605     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8606     // This is because usually pairing with immediate succeeding or preceding
8607     // candidate create the best chance to find slp vectorization opportunity.
8608     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8609     IterCnt = 0;
8610     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8611       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8612           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8613         break;
8614   }
8615 
8616   // Tracks if we tried to vectorize stores starting from the given tail
8617   // already.
8618   SmallBitVector TriedTails(E, false);
8619   // For stores that start but don't end a link in the chain:
8620   for (int Cnt = E; Cnt > 0; --Cnt) {
8621     int I = Cnt - 1;
8622     if (ConsecutiveChain[I].first == E || Tails.test(I))
8623       continue;
8624     // We found a store instr that starts a chain. Now follow the chain and try
8625     // to vectorize it.
8626     BoUpSLP::ValueList Operands;
8627     // Collect the chain into a list.
8628     while (I != E && !VectorizedStores.count(Stores[I])) {
8629       Operands.push_back(Stores[I]);
8630       Tails.set(I);
8631       if (ConsecutiveChain[I].second != 1) {
8632         // Mark the new end in the chain and go back, if required. It might be
8633         // required if the original stores come in reversed order, for example.
8634         if (ConsecutiveChain[I].first != E &&
8635             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8636             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8637           TriedTails.set(I);
8638           Tails.reset(ConsecutiveChain[I].first);
8639           if (Cnt < ConsecutiveChain[I].first + 2)
8640             Cnt = ConsecutiveChain[I].first + 2;
8641         }
8642         break;
8643       }
8644       // Move to the next value in the chain.
8645       I = ConsecutiveChain[I].first;
8646     }
8647     assert(!Operands.empty() && "Expected non-empty list of stores.");
8648 
8649     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8650     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8651     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8652 
8653     unsigned MinVF = R.getMinVF(EltSize);
8654     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8655                               MaxElts);
8656 
8657     // FIXME: Is division-by-2 the correct step? Should we assert that the
8658     // register size is a power-of-2?
8659     unsigned StartIdx = 0;
8660     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8661       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8662         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8663         if (!VectorizedStores.count(Slice.front()) &&
8664             !VectorizedStores.count(Slice.back()) &&
8665             vectorizeStoreChain(Slice, R, Cnt)) {
8666           // Mark the vectorized stores so that we don't vectorize them again.
8667           VectorizedStores.insert(Slice.begin(), Slice.end());
8668           Changed = true;
8669           // If we vectorized initial block, no need to try to vectorize it
8670           // again.
8671           if (Cnt == StartIdx)
8672             StartIdx += Size;
8673           Cnt += Size;
8674           continue;
8675         }
8676         ++Cnt;
8677       }
8678       // Check if the whole array was vectorized already - exit.
8679       if (StartIdx >= Operands.size())
8680         break;
8681     }
8682   }
8683 
8684   return Changed;
8685 }
8686 
8687 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8688   // Initialize the collections. We will make a single pass over the block.
8689   Stores.clear();
8690   GEPs.clear();
8691 
8692   // Visit the store and getelementptr instructions in BB and organize them in
8693   // Stores and GEPs according to the underlying objects of their pointer
8694   // operands.
8695   for (Instruction &I : *BB) {
8696     // Ignore store instructions that are volatile or have a pointer operand
8697     // that doesn't point to a scalar type.
8698     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8699       if (!SI->isSimple())
8700         continue;
8701       if (!isValidElementType(SI->getValueOperand()->getType()))
8702         continue;
8703       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8704     }
8705 
8706     // Ignore getelementptr instructions that have more than one index, a
8707     // constant index, or a pointer operand that doesn't point to a scalar
8708     // type.
8709     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8710       auto Idx = GEP->idx_begin()->get();
8711       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8712         continue;
8713       if (!isValidElementType(Idx->getType()))
8714         continue;
8715       if (GEP->getType()->isVectorTy())
8716         continue;
8717       GEPs[GEP->getPointerOperand()].push_back(GEP);
8718     }
8719   }
8720 }
8721 
8722 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8723   if (!A || !B)
8724     return false;
8725   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8726     return false;
8727   Value *VL[] = {A, B};
8728   return tryToVectorizeList(VL, R);
8729 }
8730 
8731 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8732                                            bool LimitForRegisterSize) {
8733   if (VL.size() < 2)
8734     return false;
8735 
8736   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8737                     << VL.size() << ".\n");
8738 
8739   // Check that all of the parts are instructions of the same type,
8740   // we permit an alternate opcode via InstructionsState.
8741   InstructionsState S = getSameOpcode(VL);
8742   if (!S.getOpcode())
8743     return false;
8744 
8745   Instruction *I0 = cast<Instruction>(S.OpValue);
8746   // Make sure invalid types (including vector type) are rejected before
8747   // determining vectorization factor for scalar instructions.
8748   for (Value *V : VL) {
8749     Type *Ty = V->getType();
8750     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8751       // NOTE: the following will give user internal llvm type name, which may
8752       // not be useful.
8753       R.getORE()->emit([&]() {
8754         std::string type_str;
8755         llvm::raw_string_ostream rso(type_str);
8756         Ty->print(rso);
8757         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8758                << "Cannot SLP vectorize list: type "
8759                << rso.str() + " is unsupported by vectorizer";
8760       });
8761       return false;
8762     }
8763   }
8764 
8765   unsigned Sz = R.getVectorElementSize(I0);
8766   unsigned MinVF = R.getMinVF(Sz);
8767   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8768   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8769   if (MaxVF < 2) {
8770     R.getORE()->emit([&]() {
8771       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8772              << "Cannot SLP vectorize list: vectorization factor "
8773              << "less than 2 is not supported";
8774     });
8775     return false;
8776   }
8777 
8778   bool Changed = false;
8779   bool CandidateFound = false;
8780   InstructionCost MinCost = SLPCostThreshold.getValue();
8781   Type *ScalarTy = VL[0]->getType();
8782   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8783     ScalarTy = IE->getOperand(1)->getType();
8784 
8785   unsigned NextInst = 0, MaxInst = VL.size();
8786   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8787     // No actual vectorization should happen, if number of parts is the same as
8788     // provided vectorization factor (i.e. the scalar type is used for vector
8789     // code during codegen).
8790     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8791     if (TTI->getNumberOfParts(VecTy) == VF)
8792       continue;
8793     for (unsigned I = NextInst; I < MaxInst; ++I) {
8794       unsigned OpsWidth = 0;
8795 
8796       if (I + VF > MaxInst)
8797         OpsWidth = MaxInst - I;
8798       else
8799         OpsWidth = VF;
8800 
8801       if (!isPowerOf2_32(OpsWidth))
8802         continue;
8803 
8804       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
8805           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
8806         break;
8807 
8808       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
8809       // Check that a previous iteration of this loop did not delete the Value.
8810       if (llvm::any_of(Ops, [&R](Value *V) {
8811             auto *I = dyn_cast<Instruction>(V);
8812             return I && R.isDeleted(I);
8813           }))
8814         continue;
8815 
8816       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
8817                         << "\n");
8818 
8819       R.buildTree(Ops);
8820       if (R.isTreeTinyAndNotFullyVectorizable())
8821         continue;
8822       R.reorderTopToBottom();
8823       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
8824       R.buildExternalUses();
8825 
8826       R.computeMinimumValueSizes();
8827       InstructionCost Cost = R.getTreeCost();
8828       CandidateFound = true;
8829       MinCost = std::min(MinCost, Cost);
8830 
8831       if (Cost < -SLPCostThreshold) {
8832         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
8833         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
8834                                                     cast<Instruction>(Ops[0]))
8835                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
8836                                  << " and with tree size "
8837                                  << ore::NV("TreeSize", R.getTreeSize()));
8838 
8839         R.vectorizeTree();
8840         // Move to the next bundle.
8841         I += VF - 1;
8842         NextInst = I + 1;
8843         Changed = true;
8844       }
8845     }
8846   }
8847 
8848   if (!Changed && CandidateFound) {
8849     R.getORE()->emit([&]() {
8850       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
8851              << "List vectorization was possible but not beneficial with cost "
8852              << ore::NV("Cost", MinCost) << " >= "
8853              << ore::NV("Treshold", -SLPCostThreshold);
8854     });
8855   } else if (!Changed) {
8856     R.getORE()->emit([&]() {
8857       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
8858              << "Cannot SLP vectorize list: vectorization was impossible"
8859              << " with available vectorization factors";
8860     });
8861   }
8862   return Changed;
8863 }
8864 
8865 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
8866   if (!I)
8867     return false;
8868 
8869   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
8870     return false;
8871 
8872   Value *P = I->getParent();
8873 
8874   // Vectorize in current basic block only.
8875   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
8876   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
8877   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
8878     return false;
8879 
8880   // Try to vectorize V.
8881   if (tryToVectorizePair(Op0, Op1, R))
8882     return true;
8883 
8884   auto *A = dyn_cast<BinaryOperator>(Op0);
8885   auto *B = dyn_cast<BinaryOperator>(Op1);
8886   // Try to skip B.
8887   if (B && B->hasOneUse()) {
8888     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
8889     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
8890     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
8891       return true;
8892     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
8893       return true;
8894   }
8895 
8896   // Try to skip A.
8897   if (A && A->hasOneUse()) {
8898     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
8899     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
8900     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
8901       return true;
8902     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8903       return true;
8904   }
8905   return false;
8906 }
8907 
8908 namespace {
8909 
8910 /// Model horizontal reductions.
8911 ///
8912 /// A horizontal reduction is a tree of reduction instructions that has values
8913 /// that can be put into a vector as its leaves. For example:
8914 ///
8915 /// mul mul mul mul
8916 ///  \  /    \  /
8917 ///   +       +
8918 ///    \     /
8919 ///       +
8920 /// This tree has "mul" as its leaf values and "+" as its reduction
8921 /// instructions. A reduction can feed into a store or a binary operation
8922 /// feeding a phi.
8923 ///    ...
8924 ///    \  /
8925 ///     +
8926 ///     |
8927 ///  phi +=
8928 ///
8929 ///  Or:
8930 ///    ...
8931 ///    \  /
8932 ///     +
8933 ///     |
8934 ///   *p =
8935 ///
8936 class HorizontalReduction {
8937   using ReductionOpsType = SmallVector<Value *, 16>;
8938   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8939   ReductionOpsListType ReductionOps;
8940   SmallVector<Value *, 32> ReducedVals;
8941   // Use map vector to make stable output.
8942   MapVector<Instruction *, Value *> ExtraArgs;
8943   WeakTrackingVH ReductionRoot;
8944   /// The type of reduction operation.
8945   RecurKind RdxKind;
8946 
8947   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8948 
8949   static bool isCmpSelMinMax(Instruction *I) {
8950     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8951            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8952   }
8953 
8954   // And/or are potentially poison-safe logical patterns like:
8955   // select x, y, false
8956   // select x, true, y
8957   static bool isBoolLogicOp(Instruction *I) {
8958     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8959            match(I, m_LogicalOr(m_Value(), m_Value()));
8960   }
8961 
8962   /// Checks if instruction is associative and can be vectorized.
8963   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8964     if (Kind == RecurKind::None)
8965       return false;
8966 
8967     // Integer ops that map to select instructions or intrinsics are fine.
8968     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8969         isBoolLogicOp(I))
8970       return true;
8971 
8972     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8973       // FP min/max are associative except for NaN and -0.0. We do not
8974       // have to rule out -0.0 here because the intrinsic semantics do not
8975       // specify a fixed result for it.
8976       return I->getFastMathFlags().noNaNs();
8977     }
8978 
8979     return I->isAssociative();
8980   }
8981 
8982   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8983     // Poison-safe 'or' takes the form: select X, true, Y
8984     // To make that work with the normal operand processing, we skip the
8985     // true value operand.
8986     // TODO: Change the code and data structures to handle this without a hack.
8987     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8988       return I->getOperand(2);
8989     return I->getOperand(Index);
8990   }
8991 
8992   /// Checks if the ParentStackElem.first should be marked as a reduction
8993   /// operation with an extra argument or as extra argument itself.
8994   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8995                     Value *ExtraArg) {
8996     if (ExtraArgs.count(ParentStackElem.first)) {
8997       ExtraArgs[ParentStackElem.first] = nullptr;
8998       // We ran into something like:
8999       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9000       // The whole ParentStackElem.first should be considered as an extra value
9001       // in this case.
9002       // Do not perform analysis of remaining operands of ParentStackElem.first
9003       // instruction, this whole instruction is an extra argument.
9004       ParentStackElem.second = INVALID_OPERAND_INDEX;
9005     } else {
9006       // We ran into something like:
9007       // ParentStackElem.first += ... + ExtraArg + ...
9008       ExtraArgs[ParentStackElem.first] = ExtraArg;
9009     }
9010   }
9011 
9012   /// Creates reduction operation with the current opcode.
9013   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9014                          Value *RHS, const Twine &Name, bool UseSelect) {
9015     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9016     switch (Kind) {
9017     case RecurKind::Or:
9018       if (UseSelect &&
9019           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9020         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9021       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9022                                  Name);
9023     case RecurKind::And:
9024       if (UseSelect &&
9025           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9026         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9027       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9028                                  Name);
9029     case RecurKind::Add:
9030     case RecurKind::Mul:
9031     case RecurKind::Xor:
9032     case RecurKind::FAdd:
9033     case RecurKind::FMul:
9034       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9035                                  Name);
9036     case RecurKind::FMax:
9037       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9038     case RecurKind::FMin:
9039       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9040     case RecurKind::SMax:
9041       if (UseSelect) {
9042         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9043         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9044       }
9045       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9046     case RecurKind::SMin:
9047       if (UseSelect) {
9048         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9049         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9050       }
9051       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9052     case RecurKind::UMax:
9053       if (UseSelect) {
9054         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9055         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9056       }
9057       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9058     case RecurKind::UMin:
9059       if (UseSelect) {
9060         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9061         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9062       }
9063       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9064     default:
9065       llvm_unreachable("Unknown reduction operation.");
9066     }
9067   }
9068 
9069   /// Creates reduction operation with the current opcode with the IR flags
9070   /// from \p ReductionOps.
9071   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9072                          Value *RHS, const Twine &Name,
9073                          const ReductionOpsListType &ReductionOps) {
9074     bool UseSelect = ReductionOps.size() == 2 ||
9075                      // Logical or/and.
9076                      (ReductionOps.size() == 1 &&
9077                       isa<SelectInst>(ReductionOps.front().front()));
9078     assert((!UseSelect || ReductionOps.size() != 2 ||
9079             isa<SelectInst>(ReductionOps[1][0])) &&
9080            "Expected cmp + select pairs for reduction");
9081     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9082     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9083       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9084         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9085         propagateIRFlags(Op, ReductionOps[1]);
9086         return Op;
9087       }
9088     }
9089     propagateIRFlags(Op, ReductionOps[0]);
9090     return Op;
9091   }
9092 
9093   /// Creates reduction operation with the current opcode with the IR flags
9094   /// from \p I.
9095   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9096                          Value *RHS, const Twine &Name, Instruction *I) {
9097     auto *SelI = dyn_cast<SelectInst>(I);
9098     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9099     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9100       if (auto *Sel = dyn_cast<SelectInst>(Op))
9101         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9102     }
9103     propagateIRFlags(Op, I);
9104     return Op;
9105   }
9106 
9107   static RecurKind getRdxKind(Instruction *I) {
9108     assert(I && "Expected instruction for reduction matching");
9109     if (match(I, m_Add(m_Value(), m_Value())))
9110       return RecurKind::Add;
9111     if (match(I, m_Mul(m_Value(), m_Value())))
9112       return RecurKind::Mul;
9113     if (match(I, m_And(m_Value(), m_Value())) ||
9114         match(I, m_LogicalAnd(m_Value(), m_Value())))
9115       return RecurKind::And;
9116     if (match(I, m_Or(m_Value(), m_Value())) ||
9117         match(I, m_LogicalOr(m_Value(), m_Value())))
9118       return RecurKind::Or;
9119     if (match(I, m_Xor(m_Value(), m_Value())))
9120       return RecurKind::Xor;
9121     if (match(I, m_FAdd(m_Value(), m_Value())))
9122       return RecurKind::FAdd;
9123     if (match(I, m_FMul(m_Value(), m_Value())))
9124       return RecurKind::FMul;
9125 
9126     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9127       return RecurKind::FMax;
9128     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9129       return RecurKind::FMin;
9130 
9131     // This matches either cmp+select or intrinsics. SLP is expected to handle
9132     // either form.
9133     // TODO: If we are canonicalizing to intrinsics, we can remove several
9134     //       special-case paths that deal with selects.
9135     if (match(I, m_SMax(m_Value(), m_Value())))
9136       return RecurKind::SMax;
9137     if (match(I, m_SMin(m_Value(), m_Value())))
9138       return RecurKind::SMin;
9139     if (match(I, m_UMax(m_Value(), m_Value())))
9140       return RecurKind::UMax;
9141     if (match(I, m_UMin(m_Value(), m_Value())))
9142       return RecurKind::UMin;
9143 
9144     if (auto *Select = dyn_cast<SelectInst>(I)) {
9145       // Try harder: look for min/max pattern based on instructions producing
9146       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9147       // During the intermediate stages of SLP, it's very common to have
9148       // pattern like this (since optimizeGatherSequence is run only once
9149       // at the end):
9150       // %1 = extractelement <2 x i32> %a, i32 0
9151       // %2 = extractelement <2 x i32> %a, i32 1
9152       // %cond = icmp sgt i32 %1, %2
9153       // %3 = extractelement <2 x i32> %a, i32 0
9154       // %4 = extractelement <2 x i32> %a, i32 1
9155       // %select = select i1 %cond, i32 %3, i32 %4
9156       CmpInst::Predicate Pred;
9157       Instruction *L1;
9158       Instruction *L2;
9159 
9160       Value *LHS = Select->getTrueValue();
9161       Value *RHS = Select->getFalseValue();
9162       Value *Cond = Select->getCondition();
9163 
9164       // TODO: Support inverse predicates.
9165       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9166         if (!isa<ExtractElementInst>(RHS) ||
9167             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9168           return RecurKind::None;
9169       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9170         if (!isa<ExtractElementInst>(LHS) ||
9171             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9172           return RecurKind::None;
9173       } else {
9174         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9175           return RecurKind::None;
9176         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9177             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9178             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9179           return RecurKind::None;
9180       }
9181 
9182       switch (Pred) {
9183       default:
9184         return RecurKind::None;
9185       case CmpInst::ICMP_SGT:
9186       case CmpInst::ICMP_SGE:
9187         return RecurKind::SMax;
9188       case CmpInst::ICMP_SLT:
9189       case CmpInst::ICMP_SLE:
9190         return RecurKind::SMin;
9191       case CmpInst::ICMP_UGT:
9192       case CmpInst::ICMP_UGE:
9193         return RecurKind::UMax;
9194       case CmpInst::ICMP_ULT:
9195       case CmpInst::ICMP_ULE:
9196         return RecurKind::UMin;
9197       }
9198     }
9199     return RecurKind::None;
9200   }
9201 
9202   /// Get the index of the first operand.
9203   static unsigned getFirstOperandIndex(Instruction *I) {
9204     return isCmpSelMinMax(I) ? 1 : 0;
9205   }
9206 
9207   /// Total number of operands in the reduction operation.
9208   static unsigned getNumberOfOperands(Instruction *I) {
9209     return isCmpSelMinMax(I) ? 3 : 2;
9210   }
9211 
9212   /// Checks if the instruction is in basic block \p BB.
9213   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9214   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9215     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9216       auto *Sel = cast<SelectInst>(I);
9217       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9218       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9219     }
9220     return I->getParent() == BB;
9221   }
9222 
9223   /// Expected number of uses for reduction operations/reduced values.
9224   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9225     if (IsCmpSelMinMax) {
9226       // SelectInst must be used twice while the condition op must have single
9227       // use only.
9228       if (auto *Sel = dyn_cast<SelectInst>(I))
9229         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9230       return I->hasNUses(2);
9231     }
9232 
9233     // Arithmetic reduction operation must be used once only.
9234     return I->hasOneUse();
9235   }
9236 
9237   /// Initializes the list of reduction operations.
9238   void initReductionOps(Instruction *I) {
9239     if (isCmpSelMinMax(I))
9240       ReductionOps.assign(2, ReductionOpsType());
9241     else
9242       ReductionOps.assign(1, ReductionOpsType());
9243   }
9244 
9245   /// Add all reduction operations for the reduction instruction \p I.
9246   void addReductionOps(Instruction *I) {
9247     if (isCmpSelMinMax(I)) {
9248       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9249       ReductionOps[1].emplace_back(I);
9250     } else {
9251       ReductionOps[0].emplace_back(I);
9252     }
9253   }
9254 
9255   static Value *getLHS(RecurKind Kind, Instruction *I) {
9256     if (Kind == RecurKind::None)
9257       return nullptr;
9258     return I->getOperand(getFirstOperandIndex(I));
9259   }
9260   static Value *getRHS(RecurKind Kind, Instruction *I) {
9261     if (Kind == RecurKind::None)
9262       return nullptr;
9263     return I->getOperand(getFirstOperandIndex(I) + 1);
9264   }
9265 
9266 public:
9267   HorizontalReduction() = default;
9268 
9269   /// Try to find a reduction tree.
9270   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9271     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9272            "Phi needs to use the binary operator");
9273     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9274             isa<IntrinsicInst>(Inst)) &&
9275            "Expected binop, select, or intrinsic for reduction matching");
9276     RdxKind = getRdxKind(Inst);
9277 
9278     // We could have a initial reductions that is not an add.
9279     //  r *= v1 + v2 + v3 + v4
9280     // In such a case start looking for a tree rooted in the first '+'.
9281     if (Phi) {
9282       if (getLHS(RdxKind, Inst) == Phi) {
9283         Phi = nullptr;
9284         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9285         if (!Inst)
9286           return false;
9287         RdxKind = getRdxKind(Inst);
9288       } else if (getRHS(RdxKind, Inst) == Phi) {
9289         Phi = nullptr;
9290         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9291         if (!Inst)
9292           return false;
9293         RdxKind = getRdxKind(Inst);
9294       }
9295     }
9296 
9297     if (!isVectorizable(RdxKind, Inst))
9298       return false;
9299 
9300     // Analyze "regular" integer/FP types for reductions - no target-specific
9301     // types or pointers.
9302     Type *Ty = Inst->getType();
9303     if (!isValidElementType(Ty) || Ty->isPointerTy())
9304       return false;
9305 
9306     // Though the ultimate reduction may have multiple uses, its condition must
9307     // have only single use.
9308     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9309       if (!Sel->getCondition()->hasOneUse())
9310         return false;
9311 
9312     ReductionRoot = Inst;
9313 
9314     // The opcode for leaf values that we perform a reduction on.
9315     // For example: load(x) + load(y) + load(z) + fptoui(w)
9316     // The leaf opcode for 'w' does not match, so we don't include it as a
9317     // potential candidate for the reduction.
9318     unsigned LeafOpcode = 0;
9319 
9320     // Post-order traverse the reduction tree starting at Inst. We only handle
9321     // true trees containing binary operators or selects.
9322     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9323     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9324     initReductionOps(Inst);
9325     while (!Stack.empty()) {
9326       Instruction *TreeN = Stack.back().first;
9327       unsigned EdgeToVisit = Stack.back().second++;
9328       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9329       bool IsReducedValue = TreeRdxKind != RdxKind;
9330 
9331       // Postorder visit.
9332       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9333         if (IsReducedValue)
9334           ReducedVals.push_back(TreeN);
9335         else {
9336           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9337           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9338             // Check if TreeN is an extra argument of its parent operation.
9339             if (Stack.size() <= 1) {
9340               // TreeN can't be an extra argument as it is a root reduction
9341               // operation.
9342               return false;
9343             }
9344             // Yes, TreeN is an extra argument, do not add it to a list of
9345             // reduction operations.
9346             // Stack[Stack.size() - 2] always points to the parent operation.
9347             markExtraArg(Stack[Stack.size() - 2], TreeN);
9348             ExtraArgs.erase(TreeN);
9349           } else
9350             addReductionOps(TreeN);
9351         }
9352         // Retract.
9353         Stack.pop_back();
9354         continue;
9355       }
9356 
9357       // Visit operands.
9358       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9359       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9360       if (!EdgeInst) {
9361         // Edge value is not a reduction instruction or a leaf instruction.
9362         // (It may be a constant, function argument, or something else.)
9363         markExtraArg(Stack.back(), EdgeVal);
9364         continue;
9365       }
9366       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9367       // Continue analysis if the next operand is a reduction operation or
9368       // (possibly) a leaf value. If the leaf value opcode is not set,
9369       // the first met operation != reduction operation is considered as the
9370       // leaf opcode.
9371       // Only handle trees in the current basic block.
9372       // Each tree node needs to have minimal number of users except for the
9373       // ultimate reduction.
9374       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9375       if (EdgeInst != Phi && EdgeInst != Inst &&
9376           hasSameParent(EdgeInst, Inst->getParent()) &&
9377           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9378           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9379         if (IsRdxInst) {
9380           // We need to be able to reassociate the reduction operations.
9381           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9382             // I is an extra argument for TreeN (its parent operation).
9383             markExtraArg(Stack.back(), EdgeInst);
9384             continue;
9385           }
9386         } else if (!LeafOpcode) {
9387           LeafOpcode = EdgeInst->getOpcode();
9388         }
9389         Stack.push_back(
9390             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9391         continue;
9392       }
9393       // I is an extra argument for TreeN (its parent operation).
9394       markExtraArg(Stack.back(), EdgeInst);
9395     }
9396     return true;
9397   }
9398 
9399   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9400   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9401     // If there are a sufficient number of reduction values, reduce
9402     // to a nearby power-of-2. We can safely generate oversized
9403     // vectors and rely on the backend to split them to legal sizes.
9404     unsigned NumReducedVals = ReducedVals.size();
9405     if (NumReducedVals < 4)
9406       return nullptr;
9407 
9408     // Intersect the fast-math-flags from all reduction operations.
9409     FastMathFlags RdxFMF;
9410     RdxFMF.set();
9411     for (ReductionOpsType &RdxOp : ReductionOps) {
9412       for (Value *RdxVal : RdxOp) {
9413         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9414           RdxFMF &= FPMO->getFastMathFlags();
9415       }
9416     }
9417 
9418     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9419     Builder.setFastMathFlags(RdxFMF);
9420 
9421     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9422     // The same extra argument may be used several times, so log each attempt
9423     // to use it.
9424     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9425       assert(Pair.first && "DebugLoc must be set.");
9426       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9427     }
9428 
9429     // The compare instruction of a min/max is the insertion point for new
9430     // instructions and may be replaced with a new compare instruction.
9431     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9432       assert(isa<SelectInst>(RdxRootInst) &&
9433              "Expected min/max reduction to have select root instruction");
9434       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9435       assert(isa<Instruction>(ScalarCond) &&
9436              "Expected min/max reduction to have compare condition");
9437       return cast<Instruction>(ScalarCond);
9438     };
9439 
9440     // The reduction root is used as the insertion point for new instructions,
9441     // so set it as externally used to prevent it from being deleted.
9442     ExternallyUsedValues[ReductionRoot];
9443     SmallVector<Value *, 16> IgnoreList;
9444     for (ReductionOpsType &RdxOp : ReductionOps)
9445       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9446 
9447     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9448     if (NumReducedVals > ReduxWidth) {
9449       // In the loop below, we are building a tree based on a window of
9450       // 'ReduxWidth' values.
9451       // If the operands of those values have common traits (compare predicate,
9452       // constant operand, etc), then we want to group those together to
9453       // minimize the cost of the reduction.
9454 
9455       // TODO: This should be extended to count common operands for
9456       //       compares and binops.
9457 
9458       // Step 1: Count the number of times each compare predicate occurs.
9459       SmallDenseMap<unsigned, unsigned> PredCountMap;
9460       for (Value *RdxVal : ReducedVals) {
9461         CmpInst::Predicate Pred;
9462         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9463           ++PredCountMap[Pred];
9464       }
9465       // Step 2: Sort the values so the most common predicates come first.
9466       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9467         CmpInst::Predicate PredA, PredB;
9468         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9469             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9470           return PredCountMap[PredA] > PredCountMap[PredB];
9471         }
9472         return false;
9473       });
9474     }
9475 
9476     Value *VectorizedTree = nullptr;
9477     unsigned i = 0;
9478     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9479       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9480       V.buildTree(VL, IgnoreList);
9481       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9482         break;
9483       if (V.isLoadCombineReductionCandidate(RdxKind))
9484         break;
9485       V.reorderTopToBottom();
9486       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9487       V.buildExternalUses(ExternallyUsedValues);
9488 
9489       // For a poison-safe boolean logic reduction, do not replace select
9490       // instructions with logic ops. All reduced values will be frozen (see
9491       // below) to prevent leaking poison.
9492       if (isa<SelectInst>(ReductionRoot) &&
9493           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9494           NumReducedVals != ReduxWidth)
9495         break;
9496 
9497       V.computeMinimumValueSizes();
9498 
9499       // Estimate cost.
9500       InstructionCost TreeCost =
9501           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9502       InstructionCost ReductionCost =
9503           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9504       InstructionCost Cost = TreeCost + ReductionCost;
9505       if (!Cost.isValid()) {
9506         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9507         return nullptr;
9508       }
9509       if (Cost >= -SLPCostThreshold) {
9510         V.getORE()->emit([&]() {
9511           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9512                                           cast<Instruction>(VL[0]))
9513                  << "Vectorizing horizontal reduction is possible"
9514                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9515                  << " and threshold "
9516                  << ore::NV("Threshold", -SLPCostThreshold);
9517         });
9518         break;
9519       }
9520 
9521       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9522                         << Cost << ". (HorRdx)\n");
9523       V.getORE()->emit([&]() {
9524         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9525                                   cast<Instruction>(VL[0]))
9526                << "Vectorized horizontal reduction with cost "
9527                << ore::NV("Cost", Cost) << " and with tree size "
9528                << ore::NV("TreeSize", V.getTreeSize());
9529       });
9530 
9531       // Vectorize a tree.
9532       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9533       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9534 
9535       // Emit a reduction. If the root is a select (min/max idiom), the insert
9536       // point is the compare condition of that select.
9537       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9538       if (isCmpSelMinMax(RdxRootInst))
9539         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9540       else
9541         Builder.SetInsertPoint(RdxRootInst);
9542 
9543       // To prevent poison from leaking across what used to be sequential, safe,
9544       // scalar boolean logic operations, the reduction operand must be frozen.
9545       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9546         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9547 
9548       Value *ReducedSubTree =
9549           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9550 
9551       if (!VectorizedTree) {
9552         // Initialize the final value in the reduction.
9553         VectorizedTree = ReducedSubTree;
9554       } else {
9555         // Update the final value in the reduction.
9556         Builder.SetCurrentDebugLocation(Loc);
9557         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9558                                   ReducedSubTree, "op.rdx", ReductionOps);
9559       }
9560       i += ReduxWidth;
9561       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9562     }
9563 
9564     if (VectorizedTree) {
9565       // Finish the reduction.
9566       for (; i < NumReducedVals; ++i) {
9567         auto *I = cast<Instruction>(ReducedVals[i]);
9568         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9569         VectorizedTree =
9570             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9571       }
9572       for (auto &Pair : ExternallyUsedValues) {
9573         // Add each externally used value to the final reduction.
9574         for (auto *I : Pair.second) {
9575           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9576           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9577                                     Pair.first, "op.extra", I);
9578         }
9579       }
9580 
9581       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9582 
9583       // Mark all scalar reduction ops for deletion, they are replaced by the
9584       // vector reductions.
9585       V.eraseInstructions(IgnoreList);
9586     }
9587     return VectorizedTree;
9588   }
9589 
9590   unsigned numReductionValues() const { return ReducedVals.size(); }
9591 
9592 private:
9593   /// Calculate the cost of a reduction.
9594   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9595                                    Value *FirstReducedVal, unsigned ReduxWidth,
9596                                    FastMathFlags FMF) {
9597     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9598     Type *ScalarTy = FirstReducedVal->getType();
9599     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9600     InstructionCost VectorCost, ScalarCost;
9601     switch (RdxKind) {
9602     case RecurKind::Add:
9603     case RecurKind::Mul:
9604     case RecurKind::Or:
9605     case RecurKind::And:
9606     case RecurKind::Xor:
9607     case RecurKind::FAdd:
9608     case RecurKind::FMul: {
9609       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9610       VectorCost =
9611           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9612       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9613       break;
9614     }
9615     case RecurKind::FMax:
9616     case RecurKind::FMin: {
9617       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9618       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9619       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9620                                                /*IsUnsigned=*/false, CostKind);
9621       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9622       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9623                                            SclCondTy, RdxPred, CostKind) +
9624                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9625                                            SclCondTy, RdxPred, CostKind);
9626       break;
9627     }
9628     case RecurKind::SMax:
9629     case RecurKind::SMin:
9630     case RecurKind::UMax:
9631     case RecurKind::UMin: {
9632       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9633       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9634       bool IsUnsigned =
9635           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9636       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9637                                                CostKind);
9638       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9639       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9640                                            SclCondTy, RdxPred, CostKind) +
9641                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9642                                            SclCondTy, RdxPred, CostKind);
9643       break;
9644     }
9645     default:
9646       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9647     }
9648 
9649     // Scalar cost is repeated for N-1 elements.
9650     ScalarCost *= (ReduxWidth - 1);
9651     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9652                       << " for reduction that starts with " << *FirstReducedVal
9653                       << " (It is a splitting reduction)\n");
9654     return VectorCost - ScalarCost;
9655   }
9656 
9657   /// Emit a horizontal reduction of the vectorized value.
9658   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9659                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9660     assert(VectorizedValue && "Need to have a vectorized tree node");
9661     assert(isPowerOf2_32(ReduxWidth) &&
9662            "We only handle power-of-two reductions for now");
9663     assert(RdxKind != RecurKind::FMulAdd &&
9664            "A call to the llvm.fmuladd intrinsic is not handled yet");
9665 
9666     ++NumVectorInstructions;
9667     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9668   }
9669 };
9670 
9671 } // end anonymous namespace
9672 
9673 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9674   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9675     return cast<FixedVectorType>(IE->getType())->getNumElements();
9676 
9677   unsigned AggregateSize = 1;
9678   auto *IV = cast<InsertValueInst>(InsertInst);
9679   Type *CurrentType = IV->getType();
9680   do {
9681     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9682       for (auto *Elt : ST->elements())
9683         if (Elt != ST->getElementType(0)) // check homogeneity
9684           return None;
9685       AggregateSize *= ST->getNumElements();
9686       CurrentType = ST->getElementType(0);
9687     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9688       AggregateSize *= AT->getNumElements();
9689       CurrentType = AT->getElementType();
9690     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9691       AggregateSize *= VT->getNumElements();
9692       return AggregateSize;
9693     } else if (CurrentType->isSingleValueType()) {
9694       return AggregateSize;
9695     } else {
9696       return None;
9697     }
9698   } while (true);
9699 }
9700 
9701 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9702                                    TargetTransformInfo *TTI,
9703                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9704                                    SmallVectorImpl<Value *> &InsertElts,
9705                                    unsigned OperandOffset) {
9706   do {
9707     Value *InsertedOperand = LastInsertInst->getOperand(1);
9708     Optional<unsigned> OperandIndex =
9709         getInsertIndex(LastInsertInst, OperandOffset);
9710     if (!OperandIndex)
9711       return;
9712     if (isa<InsertElementInst>(InsertedOperand) ||
9713         isa<InsertValueInst>(InsertedOperand)) {
9714       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9715                              BuildVectorOpds, InsertElts, *OperandIndex);
9716 
9717     } else {
9718       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9719       InsertElts[*OperandIndex] = LastInsertInst;
9720     }
9721     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9722   } while (LastInsertInst != nullptr &&
9723            (isa<InsertValueInst>(LastInsertInst) ||
9724             isa<InsertElementInst>(LastInsertInst)) &&
9725            LastInsertInst->hasOneUse());
9726 }
9727 
9728 /// Recognize construction of vectors like
9729 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9730 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9731 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9732 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9733 ///  starting from the last insertelement or insertvalue instruction.
9734 ///
9735 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9736 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9737 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9738 ///
9739 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9740 ///
9741 /// \return true if it matches.
9742 static bool findBuildAggregate(Instruction *LastInsertInst,
9743                                TargetTransformInfo *TTI,
9744                                SmallVectorImpl<Value *> &BuildVectorOpds,
9745                                SmallVectorImpl<Value *> &InsertElts) {
9746 
9747   assert((isa<InsertElementInst>(LastInsertInst) ||
9748           isa<InsertValueInst>(LastInsertInst)) &&
9749          "Expected insertelement or insertvalue instruction!");
9750 
9751   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9752          "Expected empty result vectors!");
9753 
9754   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9755   if (!AggregateSize)
9756     return false;
9757   BuildVectorOpds.resize(*AggregateSize);
9758   InsertElts.resize(*AggregateSize);
9759 
9760   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
9761   llvm::erase_value(BuildVectorOpds, nullptr);
9762   llvm::erase_value(InsertElts, nullptr);
9763   if (BuildVectorOpds.size() >= 2)
9764     return true;
9765 
9766   return false;
9767 }
9768 
9769 /// Try and get a reduction value from a phi node.
9770 ///
9771 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9772 /// if they come from either \p ParentBB or a containing loop latch.
9773 ///
9774 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9775 /// if not possible.
9776 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9777                                 BasicBlock *ParentBB, LoopInfo *LI) {
9778   // There are situations where the reduction value is not dominated by the
9779   // reduction phi. Vectorizing such cases has been reported to cause
9780   // miscompiles. See PR25787.
9781   auto DominatedReduxValue = [&](Value *R) {
9782     return isa<Instruction>(R) &&
9783            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9784   };
9785 
9786   Value *Rdx = nullptr;
9787 
9788   // Return the incoming value if it comes from the same BB as the phi node.
9789   if (P->getIncomingBlock(0) == ParentBB) {
9790     Rdx = P->getIncomingValue(0);
9791   } else if (P->getIncomingBlock(1) == ParentBB) {
9792     Rdx = P->getIncomingValue(1);
9793   }
9794 
9795   if (Rdx && DominatedReduxValue(Rdx))
9796     return Rdx;
9797 
9798   // Otherwise, check whether we have a loop latch to look at.
9799   Loop *BBL = LI->getLoopFor(ParentBB);
9800   if (!BBL)
9801     return nullptr;
9802   BasicBlock *BBLatch = BBL->getLoopLatch();
9803   if (!BBLatch)
9804     return nullptr;
9805 
9806   // There is a loop latch, return the incoming value if it comes from
9807   // that. This reduction pattern occasionally turns up.
9808   if (P->getIncomingBlock(0) == BBLatch) {
9809     Rdx = P->getIncomingValue(0);
9810   } else if (P->getIncomingBlock(1) == BBLatch) {
9811     Rdx = P->getIncomingValue(1);
9812   }
9813 
9814   if (Rdx && DominatedReduxValue(Rdx))
9815     return Rdx;
9816 
9817   return nullptr;
9818 }
9819 
9820 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
9821   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
9822     return true;
9823   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
9824     return true;
9825   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
9826     return true;
9827   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
9828     return true;
9829   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
9830     return true;
9831   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
9832     return true;
9833   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
9834     return true;
9835   return false;
9836 }
9837 
9838 /// Attempt to reduce a horizontal reduction.
9839 /// If it is legal to match a horizontal reduction feeding the phi node \a P
9840 /// with reduction operators \a Root (or one of its operands) in a basic block
9841 /// \a BB, then check if it can be done. If horizontal reduction is not found
9842 /// and root instruction is a binary operation, vectorization of the operands is
9843 /// attempted.
9844 /// \returns true if a horizontal reduction was matched and reduced or operands
9845 /// of one of the binary instruction were vectorized.
9846 /// \returns false if a horizontal reduction was not matched (or not possible)
9847 /// or no vectorization of any binary operation feeding \a Root instruction was
9848 /// performed.
9849 static bool tryToVectorizeHorReductionOrInstOperands(
9850     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
9851     TargetTransformInfo *TTI,
9852     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
9853   if (!ShouldVectorizeHor)
9854     return false;
9855 
9856   if (!Root)
9857     return false;
9858 
9859   if (Root->getParent() != BB || isa<PHINode>(Root))
9860     return false;
9861   // Start analysis starting from Root instruction. If horizontal reduction is
9862   // found, try to vectorize it. If it is not a horizontal reduction or
9863   // vectorization is not possible or not effective, and currently analyzed
9864   // instruction is a binary operation, try to vectorize the operands, using
9865   // pre-order DFS traversal order. If the operands were not vectorized, repeat
9866   // the same procedure considering each operand as a possible root of the
9867   // horizontal reduction.
9868   // Interrupt the process if the Root instruction itself was vectorized or all
9869   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
9870   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
9871   // CmpInsts so we can skip extra attempts in
9872   // tryToVectorizeHorReductionOrInstOperands and save compile time.
9873   std::queue<std::pair<Instruction *, unsigned>> Stack;
9874   Stack.emplace(Root, 0);
9875   SmallPtrSet<Value *, 8> VisitedInstrs;
9876   SmallVector<WeakTrackingVH> PostponedInsts;
9877   bool Res = false;
9878   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
9879                                      Value *&B1) -> Value * {
9880     bool IsBinop = matchRdxBop(Inst, B0, B1);
9881     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
9882     if (IsBinop || IsSelect) {
9883       HorizontalReduction HorRdx;
9884       if (HorRdx.matchAssociativeReduction(P, Inst))
9885         return HorRdx.tryToReduce(R, TTI);
9886     }
9887     return nullptr;
9888   };
9889   while (!Stack.empty()) {
9890     Instruction *Inst;
9891     unsigned Level;
9892     std::tie(Inst, Level) = Stack.front();
9893     Stack.pop();
9894     // Do not try to analyze instruction that has already been vectorized.
9895     // This may happen when we vectorize instruction operands on a previous
9896     // iteration while stack was populated before that happened.
9897     if (R.isDeleted(Inst))
9898       continue;
9899     Value *B0 = nullptr, *B1 = nullptr;
9900     if (Value *V = TryToReduce(Inst, B0, B1)) {
9901       Res = true;
9902       // Set P to nullptr to avoid re-analysis of phi node in
9903       // matchAssociativeReduction function unless this is the root node.
9904       P = nullptr;
9905       if (auto *I = dyn_cast<Instruction>(V)) {
9906         // Try to find another reduction.
9907         Stack.emplace(I, Level);
9908         continue;
9909       }
9910     } else {
9911       bool IsBinop = B0 && B1;
9912       if (P && IsBinop) {
9913         Inst = dyn_cast<Instruction>(B0);
9914         if (Inst == P)
9915           Inst = dyn_cast<Instruction>(B1);
9916         if (!Inst) {
9917           // Set P to nullptr to avoid re-analysis of phi node in
9918           // matchAssociativeReduction function unless this is the root node.
9919           P = nullptr;
9920           continue;
9921         }
9922       }
9923       // Set P to nullptr to avoid re-analysis of phi node in
9924       // matchAssociativeReduction function unless this is the root node.
9925       P = nullptr;
9926       // Do not try to vectorize CmpInst operands, this is done separately.
9927       // Final attempt for binop args vectorization should happen after the loop
9928       // to try to find reductions.
9929       if (!isa<CmpInst>(Inst))
9930         PostponedInsts.push_back(Inst);
9931     }
9932 
9933     // Try to vectorize operands.
9934     // Continue analysis for the instruction from the same basic block only to
9935     // save compile time.
9936     if (++Level < RecursionMaxDepth)
9937       for (auto *Op : Inst->operand_values())
9938         if (VisitedInstrs.insert(Op).second)
9939           if (auto *I = dyn_cast<Instruction>(Op))
9940             // Do not try to vectorize CmpInst operands,  this is done
9941             // separately.
9942             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9943                 I->getParent() == BB)
9944               Stack.emplace(I, Level);
9945   }
9946   // Try to vectorized binops where reductions were not found.
9947   for (Value *V : PostponedInsts)
9948     if (auto *Inst = dyn_cast<Instruction>(V))
9949       if (!R.isDeleted(Inst))
9950         Res |= Vectorize(Inst, R);
9951   return Res;
9952 }
9953 
9954 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9955                                                  BasicBlock *BB, BoUpSLP &R,
9956                                                  TargetTransformInfo *TTI) {
9957   auto *I = dyn_cast_or_null<Instruction>(V);
9958   if (!I)
9959     return false;
9960 
9961   if (!isa<BinaryOperator>(I))
9962     P = nullptr;
9963   // Try to match and vectorize a horizontal reduction.
9964   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9965     return tryToVectorize(I, R);
9966   };
9967   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9968                                                   ExtraVectorization);
9969 }
9970 
9971 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9972                                                  BasicBlock *BB, BoUpSLP &R) {
9973   const DataLayout &DL = BB->getModule()->getDataLayout();
9974   if (!R.canMapToVector(IVI->getType(), DL))
9975     return false;
9976 
9977   SmallVector<Value *, 16> BuildVectorOpds;
9978   SmallVector<Value *, 16> BuildVectorInsts;
9979   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9980     return false;
9981 
9982   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9983   // Aggregate value is unlikely to be processed in vector register.
9984   return tryToVectorizeList(BuildVectorOpds, R);
9985 }
9986 
9987 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9988                                                    BasicBlock *BB, BoUpSLP &R) {
9989   SmallVector<Value *, 16> BuildVectorInsts;
9990   SmallVector<Value *, 16> BuildVectorOpds;
9991   SmallVector<int> Mask;
9992   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9993       (llvm::all_of(
9994            BuildVectorOpds,
9995            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
9996        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9997     return false;
9998 
9999   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10000   return tryToVectorizeList(BuildVectorInsts, R);
10001 }
10002 
10003 template <typename T>
10004 static bool
10005 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10006                        function_ref<unsigned(T *)> Limit,
10007                        function_ref<bool(T *, T *)> Comparator,
10008                        function_ref<bool(T *, T *)> AreCompatible,
10009                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10010                        bool LimitForRegisterSize) {
10011   bool Changed = false;
10012   // Sort by type, parent, operands.
10013   stable_sort(Incoming, Comparator);
10014 
10015   // Try to vectorize elements base on their type.
10016   SmallVector<T *> Candidates;
10017   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10018     // Look for the next elements with the same type, parent and operand
10019     // kinds.
10020     auto *SameTypeIt = IncIt;
10021     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10022       ++SameTypeIt;
10023 
10024     // Try to vectorize them.
10025     unsigned NumElts = (SameTypeIt - IncIt);
10026     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10027                       << NumElts << ")\n");
10028     // The vectorization is a 3-state attempt:
10029     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10030     // size of maximal register at first.
10031     // 2. Try to vectorize remaining instructions with the same type, if
10032     // possible. This may result in the better vectorization results rather than
10033     // if we try just to vectorize instructions with the same/alternate opcodes.
10034     // 3. Final attempt to try to vectorize all instructions with the
10035     // same/alternate ops only, this may result in some extra final
10036     // vectorization.
10037     if (NumElts > 1 &&
10038         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10039       // Success start over because instructions might have been changed.
10040       Changed = true;
10041     } else if (NumElts < Limit(*IncIt) &&
10042                (Candidates.empty() ||
10043                 Candidates.front()->getType() == (*IncIt)->getType())) {
10044       Candidates.append(IncIt, std::next(IncIt, NumElts));
10045     }
10046     // Final attempt to vectorize instructions with the same types.
10047     if (Candidates.size() > 1 &&
10048         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10049       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10050         // Success start over because instructions might have been changed.
10051         Changed = true;
10052       } else if (LimitForRegisterSize) {
10053         // Try to vectorize using small vectors.
10054         for (auto *It = Candidates.begin(), *End = Candidates.end();
10055              It != End;) {
10056           auto *SameTypeIt = It;
10057           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10058             ++SameTypeIt;
10059           unsigned NumElts = (SameTypeIt - It);
10060           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10061                                             /*LimitForRegisterSize=*/false))
10062             Changed = true;
10063           It = SameTypeIt;
10064         }
10065       }
10066       Candidates.clear();
10067     }
10068 
10069     // Start over at the next instruction of a different type (or the end).
10070     IncIt = SameTypeIt;
10071   }
10072   return Changed;
10073 }
10074 
10075 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10076 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10077 /// operands. If IsCompatibility is false, function implements strict weak
10078 /// ordering relation between two cmp instructions, returning true if the first
10079 /// instruction is "less" than the second, i.e. its predicate is less than the
10080 /// predicate of the second or the operands IDs are less than the operands IDs
10081 /// of the second cmp instruction.
10082 template <bool IsCompatibility>
10083 static bool compareCmp(Value *V, Value *V2,
10084                        function_ref<bool(Instruction *)> IsDeleted) {
10085   auto *CI1 = cast<CmpInst>(V);
10086   auto *CI2 = cast<CmpInst>(V2);
10087   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10088     return false;
10089   if (CI1->getOperand(0)->getType()->getTypeID() <
10090       CI2->getOperand(0)->getType()->getTypeID())
10091     return !IsCompatibility;
10092   if (CI1->getOperand(0)->getType()->getTypeID() >
10093       CI2->getOperand(0)->getType()->getTypeID())
10094     return false;
10095   CmpInst::Predicate Pred1 = CI1->getPredicate();
10096   CmpInst::Predicate Pred2 = CI2->getPredicate();
10097   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10098   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10099   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10100   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10101   if (BasePred1 < BasePred2)
10102     return !IsCompatibility;
10103   if (BasePred1 > BasePred2)
10104     return false;
10105   // Compare operands.
10106   bool LEPreds = Pred1 <= Pred2;
10107   bool GEPreds = Pred1 >= Pred2;
10108   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10109     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10110     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10111     if (Op1->getValueID() < Op2->getValueID())
10112       return !IsCompatibility;
10113     if (Op1->getValueID() > Op2->getValueID())
10114       return false;
10115     if (auto *I1 = dyn_cast<Instruction>(Op1))
10116       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10117         if (I1->getParent() != I2->getParent())
10118           return false;
10119         InstructionsState S = getSameOpcode({I1, I2});
10120         if (S.getOpcode())
10121           continue;
10122         return false;
10123       }
10124   }
10125   return IsCompatibility;
10126 }
10127 
10128 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10129     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10130     bool AtTerminator) {
10131   bool OpsChanged = false;
10132   SmallVector<Instruction *, 4> PostponedCmps;
10133   for (auto *I : reverse(Instructions)) {
10134     if (R.isDeleted(I))
10135       continue;
10136     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10137       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10138     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10139       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10140     else if (isa<CmpInst>(I))
10141       PostponedCmps.push_back(I);
10142   }
10143   if (AtTerminator) {
10144     // Try to find reductions first.
10145     for (Instruction *I : PostponedCmps) {
10146       if (R.isDeleted(I))
10147         continue;
10148       for (Value *Op : I->operands())
10149         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10150     }
10151     // Try to vectorize operands as vector bundles.
10152     for (Instruction *I : PostponedCmps) {
10153       if (R.isDeleted(I))
10154         continue;
10155       OpsChanged |= tryToVectorize(I, R);
10156     }
10157     // Try to vectorize list of compares.
10158     // Sort by type, compare predicate, etc.
10159     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10160       return compareCmp<false>(V, V2,
10161                                [&R](Instruction *I) { return R.isDeleted(I); });
10162     };
10163 
10164     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10165       if (V1 == V2)
10166         return true;
10167       return compareCmp<true>(V1, V2,
10168                               [&R](Instruction *I) { return R.isDeleted(I); });
10169     };
10170     auto Limit = [&R](Value *V) {
10171       unsigned EltSize = R.getVectorElementSize(V);
10172       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10173     };
10174 
10175     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10176     OpsChanged |= tryToVectorizeSequence<Value>(
10177         Vals, Limit, CompareSorter, AreCompatibleCompares,
10178         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10179           // Exclude possible reductions from other blocks.
10180           bool ArePossiblyReducedInOtherBlock =
10181               any_of(Candidates, [](Value *V) {
10182                 return any_of(V->users(), [V](User *U) {
10183                   return isa<SelectInst>(U) &&
10184                          cast<SelectInst>(U)->getParent() !=
10185                              cast<Instruction>(V)->getParent();
10186                 });
10187               });
10188           if (ArePossiblyReducedInOtherBlock)
10189             return false;
10190           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10191         },
10192         /*LimitForRegisterSize=*/true);
10193     Instructions.clear();
10194   } else {
10195     // Insert in reverse order since the PostponedCmps vector was filled in
10196     // reverse order.
10197     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10198   }
10199   return OpsChanged;
10200 }
10201 
10202 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10203   bool Changed = false;
10204   SmallVector<Value *, 4> Incoming;
10205   SmallPtrSet<Value *, 16> VisitedInstrs;
10206   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10207   // node. Allows better to identify the chains that can be vectorized in the
10208   // better way.
10209   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10210   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10211     assert(isValidElementType(V1->getType()) &&
10212            isValidElementType(V2->getType()) &&
10213            "Expected vectorizable types only.");
10214     // It is fine to compare type IDs here, since we expect only vectorizable
10215     // types, like ints, floats and pointers, we don't care about other type.
10216     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10217       return true;
10218     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10219       return false;
10220     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10221     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10222     if (Opcodes1.size() < Opcodes2.size())
10223       return true;
10224     if (Opcodes1.size() > Opcodes2.size())
10225       return false;
10226     Optional<bool> ConstOrder;
10227     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10228       // Undefs are compatible with any other value.
10229       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10230         if (!ConstOrder)
10231           ConstOrder =
10232               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10233         continue;
10234       }
10235       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10236         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10237           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10238           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10239           if (!NodeI1)
10240             return NodeI2 != nullptr;
10241           if (!NodeI2)
10242             return false;
10243           assert((NodeI1 == NodeI2) ==
10244                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10245                  "Different nodes should have different DFS numbers");
10246           if (NodeI1 != NodeI2)
10247             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10248           InstructionsState S = getSameOpcode({I1, I2});
10249           if (S.getOpcode())
10250             continue;
10251           return I1->getOpcode() < I2->getOpcode();
10252         }
10253       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10254         if (!ConstOrder)
10255           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10256         continue;
10257       }
10258       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10259         return true;
10260       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10261         return false;
10262     }
10263     return ConstOrder && *ConstOrder;
10264   };
10265   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10266     if (V1 == V2)
10267       return true;
10268     if (V1->getType() != V2->getType())
10269       return false;
10270     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10271     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10272     if (Opcodes1.size() != Opcodes2.size())
10273       return false;
10274     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10275       // Undefs are compatible with any other value.
10276       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10277         continue;
10278       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10279         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10280           if (I1->getParent() != I2->getParent())
10281             return false;
10282           InstructionsState S = getSameOpcode({I1, I2});
10283           if (S.getOpcode())
10284             continue;
10285           return false;
10286         }
10287       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10288         continue;
10289       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10290         return false;
10291     }
10292     return true;
10293   };
10294   auto Limit = [&R](Value *V) {
10295     unsigned EltSize = R.getVectorElementSize(V);
10296     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10297   };
10298 
10299   bool HaveVectorizedPhiNodes = false;
10300   do {
10301     // Collect the incoming values from the PHIs.
10302     Incoming.clear();
10303     for (Instruction &I : *BB) {
10304       PHINode *P = dyn_cast<PHINode>(&I);
10305       if (!P)
10306         break;
10307 
10308       // No need to analyze deleted, vectorized and non-vectorizable
10309       // instructions.
10310       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10311           isValidElementType(P->getType()))
10312         Incoming.push_back(P);
10313     }
10314 
10315     // Find the corresponding non-phi nodes for better matching when trying to
10316     // build the tree.
10317     for (Value *V : Incoming) {
10318       SmallVectorImpl<Value *> &Opcodes =
10319           PHIToOpcodes.try_emplace(V).first->getSecond();
10320       if (!Opcodes.empty())
10321         continue;
10322       SmallVector<Value *, 4> Nodes(1, V);
10323       SmallPtrSet<Value *, 4> Visited;
10324       while (!Nodes.empty()) {
10325         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10326         if (!Visited.insert(PHI).second)
10327           continue;
10328         for (Value *V : PHI->incoming_values()) {
10329           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10330             Nodes.push_back(PHI1);
10331             continue;
10332           }
10333           Opcodes.emplace_back(V);
10334         }
10335       }
10336     }
10337 
10338     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10339         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10340         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10341           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10342         },
10343         /*LimitForRegisterSize=*/true);
10344     Changed |= HaveVectorizedPhiNodes;
10345     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10346   } while (HaveVectorizedPhiNodes);
10347 
10348   VisitedInstrs.clear();
10349 
10350   SmallVector<Instruction *, 8> PostProcessInstructions;
10351   SmallDenseSet<Instruction *, 4> KeyNodes;
10352   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10353     // Skip instructions with scalable type. The num of elements is unknown at
10354     // compile-time for scalable type.
10355     if (isa<ScalableVectorType>(it->getType()))
10356       continue;
10357 
10358     // Skip instructions marked for the deletion.
10359     if (R.isDeleted(&*it))
10360       continue;
10361     // We may go through BB multiple times so skip the one we have checked.
10362     if (!VisitedInstrs.insert(&*it).second) {
10363       if (it->use_empty() && KeyNodes.contains(&*it) &&
10364           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10365                                       it->isTerminator())) {
10366         // We would like to start over since some instructions are deleted
10367         // and the iterator may become invalid value.
10368         Changed = true;
10369         it = BB->begin();
10370         e = BB->end();
10371       }
10372       continue;
10373     }
10374 
10375     if (isa<DbgInfoIntrinsic>(it))
10376       continue;
10377 
10378     // Try to vectorize reductions that use PHINodes.
10379     if (PHINode *P = dyn_cast<PHINode>(it)) {
10380       // Check that the PHI is a reduction PHI.
10381       if (P->getNumIncomingValues() == 2) {
10382         // Try to match and vectorize a horizontal reduction.
10383         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10384                                      TTI)) {
10385           Changed = true;
10386           it = BB->begin();
10387           e = BB->end();
10388           continue;
10389         }
10390       }
10391       // Try to vectorize the incoming values of the PHI, to catch reductions
10392       // that feed into PHIs.
10393       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10394         // Skip if the incoming block is the current BB for now. Also, bypass
10395         // unreachable IR for efficiency and to avoid crashing.
10396         // TODO: Collect the skipped incoming values and try to vectorize them
10397         // after processing BB.
10398         if (BB == P->getIncomingBlock(I) ||
10399             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10400           continue;
10401 
10402         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10403                                             P->getIncomingBlock(I), R, TTI);
10404       }
10405       continue;
10406     }
10407 
10408     // Ran into an instruction without users, like terminator, or function call
10409     // with ignored return value, store. Ignore unused instructions (basing on
10410     // instruction type, except for CallInst and InvokeInst).
10411     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10412                             isa<InvokeInst>(it))) {
10413       KeyNodes.insert(&*it);
10414       bool OpsChanged = false;
10415       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10416         for (auto *V : it->operand_values()) {
10417           // Try to match and vectorize a horizontal reduction.
10418           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10419         }
10420       }
10421       // Start vectorization of post-process list of instructions from the
10422       // top-tree instructions to try to vectorize as many instructions as
10423       // possible.
10424       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10425                                                 it->isTerminator());
10426       if (OpsChanged) {
10427         // We would like to start over since some instructions are deleted
10428         // and the iterator may become invalid value.
10429         Changed = true;
10430         it = BB->begin();
10431         e = BB->end();
10432         continue;
10433       }
10434     }
10435 
10436     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10437         isa<InsertValueInst>(it))
10438       PostProcessInstructions.push_back(&*it);
10439   }
10440 
10441   return Changed;
10442 }
10443 
10444 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10445   auto Changed = false;
10446   for (auto &Entry : GEPs) {
10447     // If the getelementptr list has fewer than two elements, there's nothing
10448     // to do.
10449     if (Entry.second.size() < 2)
10450       continue;
10451 
10452     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10453                       << Entry.second.size() << ".\n");
10454 
10455     // Process the GEP list in chunks suitable for the target's supported
10456     // vector size. If a vector register can't hold 1 element, we are done. We
10457     // are trying to vectorize the index computations, so the maximum number of
10458     // elements is based on the size of the index expression, rather than the
10459     // size of the GEP itself (the target's pointer size).
10460     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10461     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10462     if (MaxVecRegSize < EltSize)
10463       continue;
10464 
10465     unsigned MaxElts = MaxVecRegSize / EltSize;
10466     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10467       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10468       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10469 
10470       // Initialize a set a candidate getelementptrs. Note that we use a
10471       // SetVector here to preserve program order. If the index computations
10472       // are vectorizable and begin with loads, we want to minimize the chance
10473       // of having to reorder them later.
10474       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10475 
10476       // Some of the candidates may have already been vectorized after we
10477       // initially collected them. If so, they are marked as deleted, so remove
10478       // them from the set of candidates.
10479       Candidates.remove_if(
10480           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10481 
10482       // Remove from the set of candidates all pairs of getelementptrs with
10483       // constant differences. Such getelementptrs are likely not good
10484       // candidates for vectorization in a bottom-up phase since one can be
10485       // computed from the other. We also ensure all candidate getelementptr
10486       // indices are unique.
10487       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10488         auto *GEPI = GEPList[I];
10489         if (!Candidates.count(GEPI))
10490           continue;
10491         auto *SCEVI = SE->getSCEV(GEPList[I]);
10492         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10493           auto *GEPJ = GEPList[J];
10494           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10495           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10496             Candidates.remove(GEPI);
10497             Candidates.remove(GEPJ);
10498           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10499             Candidates.remove(GEPJ);
10500           }
10501         }
10502       }
10503 
10504       // We break out of the above computation as soon as we know there are
10505       // fewer than two candidates remaining.
10506       if (Candidates.size() < 2)
10507         continue;
10508 
10509       // Add the single, non-constant index of each candidate to the bundle. We
10510       // ensured the indices met these constraints when we originally collected
10511       // the getelementptrs.
10512       SmallVector<Value *, 16> Bundle(Candidates.size());
10513       auto BundleIndex = 0u;
10514       for (auto *V : Candidates) {
10515         auto *GEP = cast<GetElementPtrInst>(V);
10516         auto *GEPIdx = GEP->idx_begin()->get();
10517         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10518         Bundle[BundleIndex++] = GEPIdx;
10519       }
10520 
10521       // Try and vectorize the indices. We are currently only interested in
10522       // gather-like cases of the form:
10523       //
10524       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10525       //
10526       // where the loads of "a", the loads of "b", and the subtractions can be
10527       // performed in parallel. It's likely that detecting this pattern in a
10528       // bottom-up phase will be simpler and less costly than building a
10529       // full-blown top-down phase beginning at the consecutive loads.
10530       Changed |= tryToVectorizeList(Bundle, R);
10531     }
10532   }
10533   return Changed;
10534 }
10535 
10536 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10537   bool Changed = false;
10538   // Sort by type, base pointers and values operand. Value operands must be
10539   // compatible (have the same opcode, same parent), otherwise it is
10540   // definitely not profitable to try to vectorize them.
10541   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10542     if (V->getPointerOperandType()->getTypeID() <
10543         V2->getPointerOperandType()->getTypeID())
10544       return true;
10545     if (V->getPointerOperandType()->getTypeID() >
10546         V2->getPointerOperandType()->getTypeID())
10547       return false;
10548     // UndefValues are compatible with all other values.
10549     if (isa<UndefValue>(V->getValueOperand()) ||
10550         isa<UndefValue>(V2->getValueOperand()))
10551       return false;
10552     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10553       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10554         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10555             DT->getNode(I1->getParent());
10556         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10557             DT->getNode(I2->getParent());
10558         assert(NodeI1 && "Should only process reachable instructions");
10559         assert(NodeI1 && "Should only process reachable instructions");
10560         assert((NodeI1 == NodeI2) ==
10561                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10562                "Different nodes should have different DFS numbers");
10563         if (NodeI1 != NodeI2)
10564           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10565         InstructionsState S = getSameOpcode({I1, I2});
10566         if (S.getOpcode())
10567           return false;
10568         return I1->getOpcode() < I2->getOpcode();
10569       }
10570     if (isa<Constant>(V->getValueOperand()) &&
10571         isa<Constant>(V2->getValueOperand()))
10572       return false;
10573     return V->getValueOperand()->getValueID() <
10574            V2->getValueOperand()->getValueID();
10575   };
10576 
10577   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10578     if (V1 == V2)
10579       return true;
10580     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10581       return false;
10582     // Undefs are compatible with any other value.
10583     if (isa<UndefValue>(V1->getValueOperand()) ||
10584         isa<UndefValue>(V2->getValueOperand()))
10585       return true;
10586     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10587       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10588         if (I1->getParent() != I2->getParent())
10589           return false;
10590         InstructionsState S = getSameOpcode({I1, I2});
10591         return S.getOpcode() > 0;
10592       }
10593     if (isa<Constant>(V1->getValueOperand()) &&
10594         isa<Constant>(V2->getValueOperand()))
10595       return true;
10596     return V1->getValueOperand()->getValueID() ==
10597            V2->getValueOperand()->getValueID();
10598   };
10599   auto Limit = [&R, this](StoreInst *SI) {
10600     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10601     return R.getMinVF(EltSize);
10602   };
10603 
10604   // Attempt to sort and vectorize each of the store-groups.
10605   for (auto &Pair : Stores) {
10606     if (Pair.second.size() < 2)
10607       continue;
10608 
10609     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10610                       << Pair.second.size() << ".\n");
10611 
10612     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10613       continue;
10614 
10615     Changed |= tryToVectorizeSequence<StoreInst>(
10616         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10617         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10618           return vectorizeStores(Candidates, R);
10619         },
10620         /*LimitForRegisterSize=*/false);
10621   }
10622   return Changed;
10623 }
10624 
10625 char SLPVectorizer::ID = 0;
10626 
10627 static const char lv_name[] = "SLP Vectorizer";
10628 
10629 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10630 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10631 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10632 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10633 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10634 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10635 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10636 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10637 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10638 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10639 
10640 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10641