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/DerivedTypes.h"
57 #include "llvm/IR/Dominators.h"
58 #include "llvm/IR/Function.h"
59 #include "llvm/IR/IRBuilder.h"
60 #include "llvm/IR/InstrTypes.h"
61 #include "llvm/IR/Instruction.h"
62 #include "llvm/IR/Instructions.h"
63 #include "llvm/IR/IntrinsicInst.h"
64 #include "llvm/IR/Intrinsics.h"
65 #include "llvm/IR/Module.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #ifdef EXPENSIVE_CHECKS
74 #include "llvm/IR/Verifier.h"
75 #endif
76 #include "llvm/Pass.h"
77 #include "llvm/Support/Casting.h"
78 #include "llvm/Support/CommandLine.h"
79 #include "llvm/Support/Compiler.h"
80 #include "llvm/Support/DOTGraphTraits.h"
81 #include "llvm/Support/Debug.h"
82 #include "llvm/Support/ErrorHandling.h"
83 #include "llvm/Support/GraphWriter.h"
84 #include "llvm/Support/InstructionCost.h"
85 #include "llvm/Support/KnownBits.h"
86 #include "llvm/Support/MathExtras.h"
87 #include "llvm/Support/raw_ostream.h"
88 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
89 #include "llvm/Transforms/Utils/Local.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 // Limit the number of alias checks. The limit is chosen so that
172 // it has no negative effect on the llvm benchmarks.
173 static const unsigned AliasedCheckLimit = 10;
174 
175 // Another limit for the alias checks: The maximum distance between load/store
176 // instructions where alias checks are done.
177 // This limit is useful for very large basic blocks.
178 static const unsigned MaxMemDepDistance = 160;
179 
180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
181 /// regions to be handled.
182 static const int MinScheduleRegionSize = 16;
183 
184 /// Predicate for the element types that the SLP vectorizer supports.
185 ///
186 /// The most important thing to filter here are types which are invalid in LLVM
187 /// vectors. We also filter target specific types which have absolutely no
188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
189 /// avoids spending time checking the cost model and realizing that they will
190 /// be inevitably scalarized.
191 static bool isValidElementType(Type *Ty) {
192   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
193          !Ty->isPPC_FP128Ty();
194 }
195 
196 /// \returns True if the value is a constant (but not globals/constant
197 /// expressions).
198 static bool isConstant(Value *V) {
199   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
200 }
201 
202 /// Checks if \p V is one of vector-like instructions, i.e. undef,
203 /// insertelement/extractelement with constant indices for fixed vector type or
204 /// extractvalue instruction.
205 static bool isVectorLikeInstWithConstOps(Value *V) {
206   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
207       !isa<ExtractValueInst, UndefValue>(V))
208     return false;
209   auto *I = dyn_cast<Instruction>(V);
210   if (!I || isa<ExtractValueInst>(I))
211     return true;
212   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
213     return false;
214   if (isa<ExtractElementInst>(I))
215     return isConstant(I->getOperand(1));
216   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
217   return isConstant(I->getOperand(2));
218 }
219 
220 /// \returns true if all of the instructions in \p VL are in the same block or
221 /// false otherwise.
222 static bool allSameBlock(ArrayRef<Value *> VL) {
223   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
224   if (!I0)
225     return false;
226   if (all_of(VL, isVectorLikeInstWithConstOps))
227     return true;
228 
229   BasicBlock *BB = I0->getParent();
230   for (int I = 1, E = VL.size(); I < E; I++) {
231     auto *II = dyn_cast<Instruction>(VL[I]);
232     if (!II)
233       return false;
234 
235     if (BB != II->getParent())
236       return false;
237   }
238   return true;
239 }
240 
241 /// \returns True if all of the values in \p VL are constants (but not
242 /// globals/constant expressions).
243 static bool allConstant(ArrayRef<Value *> VL) {
244   // Constant expressions and globals can't be vectorized like normal integer/FP
245   // constants.
246   return all_of(VL, isConstant);
247 }
248 
249 /// \returns True if all of the values in \p VL are identical or some of them
250 /// are UndefValue.
251 static bool isSplat(ArrayRef<Value *> VL) {
252   Value *FirstNonUndef = nullptr;
253   for (Value *V : VL) {
254     if (isa<UndefValue>(V))
255       continue;
256     if (!FirstNonUndef) {
257       FirstNonUndef = V;
258       continue;
259     }
260     if (V != FirstNonUndef)
261       return false;
262   }
263   return FirstNonUndef != nullptr;
264 }
265 
266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
267 static bool isCommutative(Instruction *I) {
268   if (auto *Cmp = dyn_cast<CmpInst>(I))
269     return Cmp->isCommutative();
270   if (auto *BO = dyn_cast<BinaryOperator>(I))
271     return BO->isCommutative();
272   // TODO: This should check for generic Instruction::isCommutative(), but
273   //       we need to confirm that the caller code correctly handles Intrinsics
274   //       for example (does not have 2 operands).
275   return false;
276 }
277 
278 /// Checks if the given value is actually an undefined constant vector.
279 static bool isUndefVector(const Value *V) {
280   if (isa<UndefValue>(V))
281     return true;
282   auto *C = dyn_cast<Constant>(V);
283   if (!C)
284     return false;
285   if (!C->containsUndefOrPoisonElement())
286     return false;
287   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
288   if (!VecTy)
289     return false;
290   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
291     if (Constant *Elem = C->getAggregateElement(I))
292       if (!isa<UndefValue>(Elem))
293         return false;
294   }
295   return true;
296 }
297 
298 /// Checks if the vector of instructions can be represented as a shuffle, like:
299 /// %x0 = extractelement <4 x i8> %x, i32 0
300 /// %x3 = extractelement <4 x i8> %x, i32 3
301 /// %y1 = extractelement <4 x i8> %y, i32 1
302 /// %y2 = extractelement <4 x i8> %y, i32 2
303 /// %x0x0 = mul i8 %x0, %x0
304 /// %x3x3 = mul i8 %x3, %x3
305 /// %y1y1 = mul i8 %y1, %y1
306 /// %y2y2 = mul i8 %y2, %y2
307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
311 /// ret <4 x i8> %ins4
312 /// can be transformed into:
313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
314 ///                                                         i32 6>
315 /// %2 = mul <4 x i8> %1, %1
316 /// ret <4 x i8> %2
317 /// We convert this initially to something like:
318 /// %x0 = extractelement <4 x i8> %x, i32 0
319 /// %x3 = extractelement <4 x i8> %x, i32 3
320 /// %y1 = extractelement <4 x i8> %y, i32 1
321 /// %y2 = extractelement <4 x i8> %y, i32 2
322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
326 /// %5 = mul <4 x i8> %4, %4
327 /// %6 = extractelement <4 x i8> %5, i32 0
328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
329 /// %7 = extractelement <4 x i8> %5, i32 1
330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
331 /// %8 = extractelement <4 x i8> %5, i32 2
332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
333 /// %9 = extractelement <4 x i8> %5, i32 3
334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
335 /// ret <4 x i8> %ins4
336 /// InstCombiner transforms this into a shuffle and vector mul
337 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
338 /// TODO: Can we split off and reuse the shuffle mask detection from
339 /// TargetTransformInfo::getInstructionThroughput?
340 static Optional<TargetTransformInfo::ShuffleKind>
341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
342   const auto *It =
343       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
344   if (It == VL.end())
345     return None;
346   auto *EI0 = cast<ExtractElementInst>(*It);
347   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
348     return None;
349   unsigned Size =
350       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
351   Value *Vec1 = nullptr;
352   Value *Vec2 = nullptr;
353   enum ShuffleMode { Unknown, Select, Permute };
354   ShuffleMode CommonShuffleMode = Unknown;
355   Mask.assign(VL.size(), UndefMaskElem);
356   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
357     // Undef can be represented as an undef element in a vector.
358     if (isa<UndefValue>(VL[I]))
359       continue;
360     auto *EI = cast<ExtractElementInst>(VL[I]);
361     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
362       return None;
363     auto *Vec = EI->getVectorOperand();
364     // We can extractelement from undef or poison vector.
365     if (isUndefVector(Vec))
366       continue;
367     // All vector operands must have the same number of vector elements.
368     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
369       return None;
370     if (isa<UndefValue>(EI->getIndexOperand()))
371       continue;
372     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
373     if (!Idx)
374       return None;
375     // Undefined behavior if Idx is negative or >= Size.
376     if (Idx->getValue().uge(Size))
377       continue;
378     unsigned IntIdx = Idx->getValue().getZExtValue();
379     Mask[I] = IntIdx;
380     // For correct shuffling we have to have at most 2 different vector operands
381     // in all extractelement instructions.
382     if (!Vec1 || Vec1 == Vec) {
383       Vec1 = Vec;
384     } else if (!Vec2 || Vec2 == Vec) {
385       Vec2 = Vec;
386       Mask[I] += Size;
387     } else {
388       return None;
389     }
390     if (CommonShuffleMode == Permute)
391       continue;
392     // If the extract index is not the same as the operation number, it is a
393     // permutation.
394     if (IntIdx != I) {
395       CommonShuffleMode = Permute;
396       continue;
397     }
398     CommonShuffleMode = Select;
399   }
400   // If we're not crossing lanes in different vectors, consider it as blending.
401   if (CommonShuffleMode == Select && Vec2)
402     return TargetTransformInfo::SK_Select;
403   // If Vec2 was never used, we have a permutation of a single vector, otherwise
404   // we have permutation of 2 vectors.
405   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
406               : TargetTransformInfo::SK_PermuteSingleSrc;
407 }
408 
409 namespace {
410 
411 /// Main data required for vectorization of instructions.
412 struct InstructionsState {
413   /// The very first instruction in the list with the main opcode.
414   Value *OpValue = nullptr;
415 
416   /// The main/alternate instruction.
417   Instruction *MainOp = nullptr;
418   Instruction *AltOp = nullptr;
419 
420   /// The main/alternate opcodes for the list of instructions.
421   unsigned getOpcode() const {
422     return MainOp ? MainOp->getOpcode() : 0;
423   }
424 
425   unsigned getAltOpcode() const {
426     return AltOp ? AltOp->getOpcode() : 0;
427   }
428 
429   /// Some of the instructions in the list have alternate opcodes.
430   bool isAltShuffle() const { return AltOp != MainOp; }
431 
432   bool isOpcodeOrAlt(Instruction *I) const {
433     unsigned CheckedOpcode = I->getOpcode();
434     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
435   }
436 
437   InstructionsState() = delete;
438   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
439       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
440 };
441 
442 } // end anonymous namespace
443 
444 /// Chooses the correct key for scheduling data. If \p Op has the same (or
445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
446 /// OpValue.
447 static Value *isOneOf(const InstructionsState &S, Value *Op) {
448   auto *I = dyn_cast<Instruction>(Op);
449   if (I && S.isOpcodeOrAlt(I))
450     return Op;
451   return S.OpValue;
452 }
453 
454 /// \returns true if \p Opcode is allowed as part of of the main/alternate
455 /// instruction for SLP vectorization.
456 ///
457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
458 /// "shuffled out" lane would result in division by zero.
459 static bool isValidForAlternation(unsigned Opcode) {
460   if (Instruction::isIntDivRem(Opcode))
461     return false;
462 
463   return true;
464 }
465 
466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
467                                        unsigned BaseIndex = 0);
468 
469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
470 /// compatible instructions or constants, or just some other regular values.
471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
472                                 Value *Op1) {
473   return (isConstant(BaseOp0) && isConstant(Op0)) ||
474          (isConstant(BaseOp1) && isConstant(Op1)) ||
475          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
476           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
477          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
478          getSameOpcode({BaseOp1, Op1}).getOpcode();
479 }
480 
481 /// \returns analysis of the Instructions in \p VL described in
482 /// InstructionsState, the Opcode that we suppose the whole list
483 /// could be vectorized even if its structure is diverse.
484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
485                                        unsigned BaseIndex) {
486   // Make sure these are all Instructions.
487   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
488     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
489 
490   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
491   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
492   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
493   CmpInst::Predicate BasePred =
494       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
495               : CmpInst::BAD_ICMP_PREDICATE;
496   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
497   unsigned AltOpcode = Opcode;
498   unsigned AltIndex = BaseIndex;
499 
500   // Check for one alternate opcode from another BinaryOperator.
501   // TODO - generalize to support all operators (types, calls etc.).
502   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
503     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
504     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
505       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
506         continue;
507       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
508           isValidForAlternation(Opcode)) {
509         AltOpcode = InstOpcode;
510         AltIndex = Cnt;
511         continue;
512       }
513     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
514       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
515       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
516       if (Ty0 == Ty1) {
517         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518           continue;
519         if (Opcode == AltOpcode) {
520           assert(isValidForAlternation(Opcode) &&
521                  isValidForAlternation(InstOpcode) &&
522                  "Cast isn't safe for alternation, logic needs to be updated!");
523           AltOpcode = InstOpcode;
524           AltIndex = Cnt;
525           continue;
526         }
527       }
528     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
529       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
530       auto *Inst = cast<Instruction>(VL[Cnt]);
531       Type *Ty0 = BaseInst->getOperand(0)->getType();
532       Type *Ty1 = Inst->getOperand(0)->getType();
533       if (Ty0 == Ty1) {
534         Value *BaseOp0 = BaseInst->getOperand(0);
535         Value *BaseOp1 = BaseInst->getOperand(1);
536         Value *Op0 = Inst->getOperand(0);
537         Value *Op1 = Inst->getOperand(1);
538         CmpInst::Predicate CurrentPred =
539             cast<CmpInst>(VL[Cnt])->getPredicate();
540         CmpInst::Predicate SwappedCurrentPred =
541             CmpInst::getSwappedPredicate(CurrentPred);
542         // Check for compatible operands. If the corresponding operands are not
543         // compatible - need to perform alternate vectorization.
544         if (InstOpcode == Opcode) {
545           if (BasePred == CurrentPred &&
546               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
547             continue;
548           if (BasePred == SwappedCurrentPred &&
549               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
550             continue;
551           if (E == 2 &&
552               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
553             continue;
554           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
555           CmpInst::Predicate AltPred = AltInst->getPredicate();
556           Value *AltOp0 = AltInst->getOperand(0);
557           Value *AltOp1 = AltInst->getOperand(1);
558           // Check if operands are compatible with alternate operands.
559           if (AltPred == CurrentPred &&
560               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
561             continue;
562           if (AltPred == SwappedCurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
564             continue;
565         }
566         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
567           assert(isValidForAlternation(Opcode) &&
568                  isValidForAlternation(InstOpcode) &&
569                  "Cast isn't safe for alternation, logic needs to be updated!");
570           AltIndex = Cnt;
571           continue;
572         }
573         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
574         CmpInst::Predicate AltPred = AltInst->getPredicate();
575         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
576             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
577           continue;
578       }
579     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
580       continue;
581     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
582   }
583 
584   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
585                            cast<Instruction>(VL[AltIndex]));
586 }
587 
588 /// \returns true if all of the values in \p VL have the same type or false
589 /// otherwise.
590 static bool allSameType(ArrayRef<Value *> VL) {
591   Type *Ty = VL[0]->getType();
592   for (int i = 1, e = VL.size(); i < e; i++)
593     if (VL[i]->getType() != Ty)
594       return false;
595 
596   return true;
597 }
598 
599 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
600 static Optional<unsigned> getExtractIndex(Instruction *E) {
601   unsigned Opcode = E->getOpcode();
602   assert((Opcode == Instruction::ExtractElement ||
603           Opcode == Instruction::ExtractValue) &&
604          "Expected extractelement or extractvalue instruction.");
605   if (Opcode == Instruction::ExtractElement) {
606     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
607     if (!CI)
608       return None;
609     return CI->getZExtValue();
610   }
611   ExtractValueInst *EI = cast<ExtractValueInst>(E);
612   if (EI->getNumIndices() != 1)
613     return None;
614   return *EI->idx_begin();
615 }
616 
617 /// \returns True if in-tree use also needs extract. This refers to
618 /// possible scalar operand in vectorized instruction.
619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
620                                     TargetLibraryInfo *TLI) {
621   unsigned Opcode = UserInst->getOpcode();
622   switch (Opcode) {
623   case Instruction::Load: {
624     LoadInst *LI = cast<LoadInst>(UserInst);
625     return (LI->getPointerOperand() == Scalar);
626   }
627   case Instruction::Store: {
628     StoreInst *SI = cast<StoreInst>(UserInst);
629     return (SI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Call: {
632     CallInst *CI = cast<CallInst>(UserInst);
633     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
634     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
635       if (hasVectorInstrinsicScalarOpd(ID, i))
636         return (CI->getArgOperand(i) == Scalar);
637     }
638     LLVM_FALLTHROUGH;
639   }
640   default:
641     return false;
642   }
643 }
644 
645 /// \returns the AA location that is being access by the instruction.
646 static MemoryLocation getLocation(Instruction *I) {
647   if (StoreInst *SI = dyn_cast<StoreInst>(I))
648     return MemoryLocation::get(SI);
649   if (LoadInst *LI = dyn_cast<LoadInst>(I))
650     return MemoryLocation::get(LI);
651   return MemoryLocation();
652 }
653 
654 /// \returns True if the instruction is not a volatile or atomic load/store.
655 static bool isSimple(Instruction *I) {
656   if (LoadInst *LI = dyn_cast<LoadInst>(I))
657     return LI->isSimple();
658   if (StoreInst *SI = dyn_cast<StoreInst>(I))
659     return SI->isSimple();
660   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
661     return !MI->isVolatile();
662   return true;
663 }
664 
665 /// Shuffles \p Mask in accordance with the given \p SubMask.
666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
667   if (SubMask.empty())
668     return;
669   if (Mask.empty()) {
670     Mask.append(SubMask.begin(), SubMask.end());
671     return;
672   }
673   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
674   int TermValue = std::min(Mask.size(), SubMask.size());
675   for (int I = 0, E = SubMask.size(); I < E; ++I) {
676     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
677         Mask[SubMask[I]] >= TermValue)
678       continue;
679     NewMask[I] = Mask[SubMask[I]];
680   }
681   Mask.swap(NewMask);
682 }
683 
684 /// Order may have elements assigned special value (size) which is out of
685 /// bounds. Such indices only appear on places which correspond to undef values
686 /// (see canReuseExtract for details) and used in order to avoid undef values
687 /// have effect on operands ordering.
688 /// The first loop below simply finds all unused indices and then the next loop
689 /// nest assigns these indices for undef values positions.
690 /// As an example below Order has two undef positions and they have assigned
691 /// values 3 and 7 respectively:
692 /// before:  6 9 5 4 9 2 1 0
693 /// after:   6 3 5 4 7 2 1 0
694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
695   const unsigned Sz = Order.size();
696   SmallBitVector UnusedIndices(Sz, /*t=*/true);
697   SmallBitVector MaskedIndices(Sz);
698   for (unsigned I = 0; I < Sz; ++I) {
699     if (Order[I] < Sz)
700       UnusedIndices.reset(Order[I]);
701     else
702       MaskedIndices.set(I);
703   }
704   if (MaskedIndices.none())
705     return;
706   assert(UnusedIndices.count() == MaskedIndices.count() &&
707          "Non-synced masked/available indices.");
708   int Idx = UnusedIndices.find_first();
709   int MIdx = MaskedIndices.find_first();
710   while (MIdx >= 0) {
711     assert(Idx >= 0 && "Indices must be synced.");
712     Order[MIdx] = Idx;
713     Idx = UnusedIndices.find_next(Idx);
714     MIdx = MaskedIndices.find_next(MIdx);
715   }
716 }
717 
718 namespace llvm {
719 
720 static void inversePermutation(ArrayRef<unsigned> Indices,
721                                SmallVectorImpl<int> &Mask) {
722   Mask.clear();
723   const unsigned E = Indices.size();
724   Mask.resize(E, UndefMaskElem);
725   for (unsigned I = 0; I < E; ++I)
726     Mask[Indices[I]] = I;
727 }
728 
729 /// \returns inserting index of InsertElement or InsertValue instruction,
730 /// using Offset as base offset for index.
731 static Optional<unsigned> getInsertIndex(Value *InsertInst,
732                                          unsigned Offset = 0) {
733   int Index = Offset;
734   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
735     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
736       auto *VT = cast<FixedVectorType>(IE->getType());
737       if (CI->getValue().uge(VT->getNumElements()))
738         return None;
739       Index *= VT->getNumElements();
740       Index += CI->getZExtValue();
741       return Index;
742     }
743     return None;
744   }
745 
746   auto *IV = cast<InsertValueInst>(InsertInst);
747   Type *CurrentType = IV->getType();
748   for (unsigned I : IV->indices()) {
749     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
750       Index *= ST->getNumElements();
751       CurrentType = ST->getElementType(I);
752     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
753       Index *= AT->getNumElements();
754       CurrentType = AT->getElementType();
755     } else {
756       return None;
757     }
758     Index += I;
759   }
760   return Index;
761 }
762 
763 /// Reorders the list of scalars in accordance with the given \p Mask.
764 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
765                            ArrayRef<int> Mask) {
766   assert(!Mask.empty() && "Expected non-empty mask.");
767   SmallVector<Value *> Prev(Scalars.size(),
768                             UndefValue::get(Scalars.front()->getType()));
769   Prev.swap(Scalars);
770   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
771     if (Mask[I] != UndefMaskElem)
772       Scalars[Mask[I]] = Prev[I];
773 }
774 
775 /// Checks if the provided value does not require scheduling. It does not
776 /// require scheduling if this is not an instruction or it is an instruction
777 /// that does not read/write memory and all operands are either not instructions
778 /// or phi nodes or instructions from different blocks.
779 static bool areAllOperandsNonInsts(Value *V) {
780   auto *I = dyn_cast<Instruction>(V);
781   if (!I)
782     return true;
783   return !mayHaveNonDefUseDependency(*I) &&
784     all_of(I->operands(), [I](Value *V) {
785       auto *IO = dyn_cast<Instruction>(V);
786       if (!IO)
787         return true;
788       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
789     });
790 }
791 
792 /// Checks if the provided value does not require scheduling. It does not
793 /// require scheduling if this is not an instruction or it is an instruction
794 /// that does not read/write memory and all users are phi nodes or instructions
795 /// from the different blocks.
796 static bool isUsedOutsideBlock(Value *V) {
797   auto *I = dyn_cast<Instruction>(V);
798   if (!I)
799     return true;
800   // Limits the number of uses to save compile time.
801   constexpr int UsesLimit = 8;
802   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
803          all_of(I->users(), [I](User *U) {
804            auto *IU = dyn_cast<Instruction>(U);
805            if (!IU)
806              return true;
807            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
808          });
809 }
810 
811 /// Checks if the specified value does not require scheduling. It does not
812 /// require scheduling if all operands and all users do not need to be scheduled
813 /// in the current basic block.
814 static bool doesNotNeedToBeScheduled(Value *V) {
815   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
816 }
817 
818 /// Checks if the specified array of instructions does not require scheduling.
819 /// It is so if all either instructions have operands that do not require
820 /// scheduling or their users do not require scheduling since they are phis or
821 /// in other basic blocks.
822 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
823   return !VL.empty() &&
824          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
825 }
826 
827 namespace slpvectorizer {
828 
829 /// Bottom Up SLP Vectorizer.
830 class BoUpSLP {
831   struct TreeEntry;
832   struct ScheduleData;
833 
834 public:
835   using ValueList = SmallVector<Value *, 8>;
836   using InstrList = SmallVector<Instruction *, 16>;
837   using ValueSet = SmallPtrSet<Value *, 16>;
838   using StoreList = SmallVector<StoreInst *, 8>;
839   using ExtraValueToDebugLocsMap =
840       MapVector<Value *, SmallVector<Instruction *, 2>>;
841   using OrdersType = SmallVector<unsigned, 4>;
842 
843   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
844           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
845           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
846           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
847       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
848         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
849     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
850     // Use the vector register size specified by the target unless overridden
851     // by a command-line option.
852     // TODO: It would be better to limit the vectorization factor based on
853     //       data type rather than just register size. For example, x86 AVX has
854     //       256-bit registers, but it does not support integer operations
855     //       at that width (that requires AVX2).
856     if (MaxVectorRegSizeOption.getNumOccurrences())
857       MaxVecRegSize = MaxVectorRegSizeOption;
858     else
859       MaxVecRegSize =
860           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
861               .getFixedSize();
862 
863     if (MinVectorRegSizeOption.getNumOccurrences())
864       MinVecRegSize = MinVectorRegSizeOption;
865     else
866       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
867   }
868 
869   /// Vectorize the tree that starts with the elements in \p VL.
870   /// Returns the vectorized root.
871   Value *vectorizeTree();
872 
873   /// Vectorize the tree but with the list of externally used values \p
874   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
875   /// generated extractvalue instructions.
876   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
877 
878   /// \returns the cost incurred by unwanted spills and fills, caused by
879   /// holding live values over call sites.
880   InstructionCost getSpillCost() const;
881 
882   /// \returns the vectorization cost of the subtree that starts at \p VL.
883   /// A negative number means that this is profitable.
884   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
885 
886   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
887   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
888   void buildTree(ArrayRef<Value *> Roots,
889                  ArrayRef<Value *> UserIgnoreLst = None);
890 
891   /// Builds external uses of the vectorized scalars, i.e. the list of
892   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
893   /// ExternallyUsedValues contains additional list of external uses to handle
894   /// vectorization of reductions.
895   void
896   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
897 
898   /// Clear the internal data structures that are created by 'buildTree'.
899   void deleteTree() {
900     VectorizableTree.clear();
901     ScalarToTreeEntry.clear();
902     MustGather.clear();
903     ExternalUses.clear();
904     for (auto &Iter : BlocksSchedules) {
905       BlockScheduling *BS = Iter.second.get();
906       BS->clear();
907     }
908     MinBWs.clear();
909     InstrElementSize.clear();
910   }
911 
912   unsigned getTreeSize() const { return VectorizableTree.size(); }
913 
914   /// Perform LICM and CSE on the newly generated gather sequences.
915   void optimizeGatherSequence();
916 
917   /// Checks if the specified gather tree entry \p TE can be represented as a
918   /// shuffled vector entry + (possibly) permutation with other gathers. It
919   /// implements the checks only for possibly ordered scalars (Loads,
920   /// ExtractElement, ExtractValue), which can be part of the graph.
921   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
922 
923   /// Gets reordering data for the given tree entry. If the entry is vectorized
924   /// - just return ReorderIndices, otherwise check if the scalars can be
925   /// reordered and return the most optimal order.
926   /// \param TopToBottom If true, include the order of vectorized stores and
927   /// insertelement nodes, otherwise skip them.
928   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
929 
930   /// Reorders the current graph to the most profitable order starting from the
931   /// root node to the leaf nodes. The best order is chosen only from the nodes
932   /// of the same size (vectorization factor). Smaller nodes are considered
933   /// parts of subgraph with smaller VF and they are reordered independently. We
934   /// can make it because we still need to extend smaller nodes to the wider VF
935   /// and we can merge reordering shuffles with the widening shuffles.
936   void reorderTopToBottom();
937 
938   /// Reorders the current graph to the most profitable order starting from
939   /// leaves to the root. It allows to rotate small subgraphs and reduce the
940   /// number of reshuffles if the leaf nodes use the same order. In this case we
941   /// can merge the orders and just shuffle user node instead of shuffling its
942   /// operands. Plus, even the leaf nodes have different orders, it allows to
943   /// sink reordering in the graph closer to the root node and merge it later
944   /// during analysis.
945   void reorderBottomToTop(bool IgnoreReorder = false);
946 
947   /// \return The vector element size in bits to use when vectorizing the
948   /// expression tree ending at \p V. If V is a store, the size is the width of
949   /// the stored value. Otherwise, the size is the width of the largest loaded
950   /// value reaching V. This method is used by the vectorizer to calculate
951   /// vectorization factors.
952   unsigned getVectorElementSize(Value *V);
953 
954   /// Compute the minimum type sizes required to represent the entries in a
955   /// vectorizable tree.
956   void computeMinimumValueSizes();
957 
958   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
959   unsigned getMaxVecRegSize() const {
960     return MaxVecRegSize;
961   }
962 
963   // \returns minimum vector register size as set by cl::opt.
964   unsigned getMinVecRegSize() const {
965     return MinVecRegSize;
966   }
967 
968   unsigned getMinVF(unsigned Sz) const {
969     return std::max(2U, getMinVecRegSize() / Sz);
970   }
971 
972   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
973     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
974       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
975     return MaxVF ? MaxVF : UINT_MAX;
976   }
977 
978   /// Check if homogeneous aggregate is isomorphic to some VectorType.
979   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
980   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
981   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
982   ///
983   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
984   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
985 
986   /// \returns True if the VectorizableTree is both tiny and not fully
987   /// vectorizable. We do not vectorize such trees.
988   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
989 
990   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
991   /// can be load combined in the backend. Load combining may not be allowed in
992   /// the IR optimizer, so we do not want to alter the pattern. For example,
993   /// partially transforming a scalar bswap() pattern into vector code is
994   /// effectively impossible for the backend to undo.
995   /// TODO: If load combining is allowed in the IR optimizer, this analysis
996   ///       may not be necessary.
997   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
998 
999   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1000   /// can be load combined in the backend. Load combining may not be allowed in
1001   /// the IR optimizer, so we do not want to alter the pattern. For example,
1002   /// partially transforming a scalar bswap() pattern into vector code is
1003   /// effectively impossible for the backend to undo.
1004   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1005   ///       may not be necessary.
1006   bool isLoadCombineCandidate() const;
1007 
1008   OptimizationRemarkEmitter *getORE() { return ORE; }
1009 
1010   /// This structure holds any data we need about the edges being traversed
1011   /// during buildTree_rec(). We keep track of:
1012   /// (i) the user TreeEntry index, and
1013   /// (ii) the index of the edge.
1014   struct EdgeInfo {
1015     EdgeInfo() = default;
1016     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1017         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1018     /// The user TreeEntry.
1019     TreeEntry *UserTE = nullptr;
1020     /// The operand index of the use.
1021     unsigned EdgeIdx = UINT_MAX;
1022 #ifndef NDEBUG
1023     friend inline raw_ostream &operator<<(raw_ostream &OS,
1024                                           const BoUpSLP::EdgeInfo &EI) {
1025       EI.dump(OS);
1026       return OS;
1027     }
1028     /// Debug print.
1029     void dump(raw_ostream &OS) const {
1030       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1031          << " EdgeIdx:" << EdgeIdx << "}";
1032     }
1033     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1034 #endif
1035   };
1036 
1037   /// A helper class used for scoring candidates for two consecutive lanes.
1038   class LookAheadHeuristics {
1039     const DataLayout &DL;
1040     ScalarEvolution &SE;
1041     const BoUpSLP &R;
1042     int NumLanes; // Total number of lanes (aka vectorization factor).
1043     int MaxLevel; // The maximum recursion depth for accumulating score.
1044 
1045   public:
1046     LookAheadHeuristics(const DataLayout &DL, ScalarEvolution &SE,
1047                         const BoUpSLP &R, int NumLanes, int MaxLevel)
1048         : DL(DL), SE(SE), R(R), NumLanes(NumLanes), MaxLevel(MaxLevel) {}
1049 
1050     // The hard-coded scores listed here are not very important, though it shall
1051     // be higher for better matches to improve the resulting cost. When
1052     // computing the scores of matching one sub-tree with another, we are
1053     // basically counting the number of values that are matching. So even if all
1054     // scores are set to 1, we would still get a decent matching result.
1055     // However, sometimes we have to break ties. For example we may have to
1056     // choose between matching loads vs matching opcodes. This is what these
1057     // scores are helping us with: they provide the order of preference. Also,
1058     // this is important if the scalar is externally used or used in another
1059     // tree entry node in the different lane.
1060 
1061     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1062     static const int ScoreConsecutiveLoads = 4;
1063     /// The same load multiple times. This should have a better score than
1064     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1065     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1066     /// a vector load and 1.0 for a broadcast.
1067     static const int ScoreSplatLoads = 3;
1068     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1069     static const int ScoreReversedLoads = 3;
1070     /// ExtractElementInst from same vector and consecutive indexes.
1071     static const int ScoreConsecutiveExtracts = 4;
1072     /// ExtractElementInst from same vector and reversed indices.
1073     static const int ScoreReversedExtracts = 3;
1074     /// Constants.
1075     static const int ScoreConstants = 2;
1076     /// Instructions with the same opcode.
1077     static const int ScoreSameOpcode = 2;
1078     /// Instructions with alt opcodes (e.g, add + sub).
1079     static const int ScoreAltOpcodes = 1;
1080     /// Identical instructions (a.k.a. splat or broadcast).
1081     static const int ScoreSplat = 1;
1082     /// Matching with an undef is preferable to failing.
1083     static const int ScoreUndef = 1;
1084     /// Score for failing to find a decent match.
1085     static const int ScoreFail = 0;
1086     /// Score if all users are vectorized.
1087     static const int ScoreAllUserVectorized = 1;
1088 
1089     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1090     /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1091     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1092     /// MainAltOps.
1093     int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
1094                         ArrayRef<Value *> MainAltOps) const {
1095       if (V1 == V2) {
1096         if (isa<LoadInst>(V1)) {
1097           // Retruns true if the users of V1 and V2 won't need to be extracted.
1098           auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1099             // Bail out if we have too many uses to save compilation time.
1100             static constexpr unsigned Limit = 8;
1101             if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1102               return false;
1103 
1104             auto AllUsersVectorized = [U1, U2, this](Value *V) {
1105               return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1106                 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1107               });
1108             };
1109             return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1110           };
1111           // A broadcast of a load can be cheaper on some targets.
1112           if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1113                                           ElementCount::getFixed(NumLanes)) &&
1114               ((int)V1->getNumUses() == NumLanes ||
1115                AllUsersAreInternal(V1, V2)))
1116             return LookAheadHeuristics::ScoreSplatLoads;
1117         }
1118         return LookAheadHeuristics::ScoreSplat;
1119       }
1120 
1121       auto *LI1 = dyn_cast<LoadInst>(V1);
1122       auto *LI2 = dyn_cast<LoadInst>(V2);
1123       if (LI1 && LI2) {
1124         if (LI1->getParent() != LI2->getParent())
1125           return LookAheadHeuristics::ScoreFail;
1126 
1127         Optional<int> Dist = getPointersDiff(
1128             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1129             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1130         if (!Dist || *Dist == 0)
1131           return LookAheadHeuristics::ScoreFail;
1132         // The distance is too large - still may be profitable to use masked
1133         // loads/gathers.
1134         if (std::abs(*Dist) > NumLanes / 2)
1135           return LookAheadHeuristics::ScoreAltOpcodes;
1136         // This still will detect consecutive loads, but we might have "holes"
1137         // in some cases. It is ok for non-power-2 vectorization and may produce
1138         // better results. It should not affect current vectorization.
1139         return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
1140                            : LookAheadHeuristics::ScoreReversedLoads;
1141       }
1142 
1143       auto *C1 = dyn_cast<Constant>(V1);
1144       auto *C2 = dyn_cast<Constant>(V2);
1145       if (C1 && C2)
1146         return LookAheadHeuristics::ScoreConstants;
1147 
1148       // Extracts from consecutive indexes of the same vector better score as
1149       // the extracts could be optimized away.
1150       Value *EV1;
1151       ConstantInt *Ex1Idx;
1152       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1153         // Undefs are always profitable for extractelements.
1154         if (isa<UndefValue>(V2))
1155           return LookAheadHeuristics::ScoreConsecutiveExtracts;
1156         Value *EV2 = nullptr;
1157         ConstantInt *Ex2Idx = nullptr;
1158         if (match(V2,
1159                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1160                                                          m_Undef())))) {
1161           // Undefs are always profitable for extractelements.
1162           if (!Ex2Idx)
1163             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1164           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1165             return LookAheadHeuristics::ScoreConsecutiveExtracts;
1166           if (EV2 == EV1) {
1167             int Idx1 = Ex1Idx->getZExtValue();
1168             int Idx2 = Ex2Idx->getZExtValue();
1169             int Dist = Idx2 - Idx1;
1170             // The distance is too large - still may be profitable to use
1171             // shuffles.
1172             if (std::abs(Dist) == 0)
1173               return LookAheadHeuristics::ScoreSplat;
1174             if (std::abs(Dist) > NumLanes / 2)
1175               return LookAheadHeuristics::ScoreSameOpcode;
1176             return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
1177                               : LookAheadHeuristics::ScoreReversedExtracts;
1178           }
1179           return LookAheadHeuristics::ScoreAltOpcodes;
1180         }
1181         return LookAheadHeuristics::ScoreFail;
1182       }
1183 
1184       auto *I1 = dyn_cast<Instruction>(V1);
1185       auto *I2 = dyn_cast<Instruction>(V2);
1186       if (I1 && I2) {
1187         if (I1->getParent() != I2->getParent())
1188           return LookAheadHeuristics::ScoreFail;
1189         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1190         Ops.push_back(I1);
1191         Ops.push_back(I2);
1192         InstructionsState S = getSameOpcode(Ops);
1193         // Note: Only consider instructions with <= 2 operands to avoid
1194         // complexity explosion.
1195         if (S.getOpcode() &&
1196             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1197              !S.isAltShuffle()) &&
1198             all_of(Ops, [&S](Value *V) {
1199               return cast<Instruction>(V)->getNumOperands() ==
1200                      S.MainOp->getNumOperands();
1201             }))
1202           return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1203                                   : LookAheadHeuristics::ScoreSameOpcode;
1204       }
1205 
1206       if (isa<UndefValue>(V2))
1207         return LookAheadHeuristics::ScoreUndef;
1208 
1209       return LookAheadHeuristics::ScoreFail;
1210     }
1211 
1212     /// Go through the operands of \p LHS and \p RHS recursively until
1213     /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1214     /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1215     /// of \p U1 and \p U2), except at the beginning of the recursion where
1216     /// these are set to nullptr.
1217     ///
1218     /// For example:
1219     /// \verbatim
1220     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1221     ///     \ /         \ /         \ /        \ /
1222     ///      +           +           +          +
1223     ///     G1          G2          G3         G4
1224     /// \endverbatim
1225     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1226     /// each level recursively, accumulating the score. It starts from matching
1227     /// the additions at level 0, then moves on to the loads (level 1). The
1228     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1229     /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1230     /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1231     /// Please note that the order of the operands does not matter, as we
1232     /// evaluate the score of all profitable combinations of operands. In
1233     /// other words the score of G1 and G4 is the same as G1 and G2. This
1234     /// heuristic is based on ideas described in:
1235     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1236     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1237     ///   Luís F. W. Góes
1238     int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
1239                            Instruction *U2, int CurrLevel,
1240                            ArrayRef<Value *> MainAltOps) const {
1241 
1242       // Get the shallow score of V1 and V2.
1243       int ShallowScoreAtThisLevel =
1244           getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1245 
1246       // If reached MaxLevel,
1247       //  or if V1 and V2 are not instructions,
1248       //  or if they are SPLAT,
1249       //  or if they are not consecutive,
1250       //  or if profitable to vectorize loads or extractelements, early return
1251       //  the current cost.
1252       auto *I1 = dyn_cast<Instruction>(LHS);
1253       auto *I2 = dyn_cast<Instruction>(RHS);
1254       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1255           ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1256           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1257             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1258             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1259            ShallowScoreAtThisLevel))
1260         return ShallowScoreAtThisLevel;
1261       assert(I1 && I2 && "Should have early exited.");
1262 
1263       // Contains the I2 operand indexes that got matched with I1 operands.
1264       SmallSet<unsigned, 4> Op2Used;
1265 
1266       // Recursion towards the operands of I1 and I2. We are trying all possible
1267       // operand pairs, and keeping track of the best score.
1268       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1269            OpIdx1 != NumOperands1; ++OpIdx1) {
1270         // Try to pair op1I with the best operand of I2.
1271         int MaxTmpScore = 0;
1272         unsigned MaxOpIdx2 = 0;
1273         bool FoundBest = false;
1274         // If I2 is commutative try all combinations.
1275         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1276         unsigned ToIdx = isCommutative(I2)
1277                              ? I2->getNumOperands()
1278                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1279         assert(FromIdx <= ToIdx && "Bad index");
1280         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1281           // Skip operands already paired with OpIdx1.
1282           if (Op2Used.count(OpIdx2))
1283             continue;
1284           // Recursively calculate the cost at each level
1285           int TmpScore =
1286               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1287                                  I1, I2, CurrLevel + 1, None);
1288           // Look for the best score.
1289           if (TmpScore > LookAheadHeuristics::ScoreFail &&
1290               TmpScore > MaxTmpScore) {
1291             MaxTmpScore = TmpScore;
1292             MaxOpIdx2 = OpIdx2;
1293             FoundBest = true;
1294           }
1295         }
1296         if (FoundBest) {
1297           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1298           Op2Used.insert(MaxOpIdx2);
1299           ShallowScoreAtThisLevel += MaxTmpScore;
1300         }
1301       }
1302       return ShallowScoreAtThisLevel;
1303     }
1304   };
1305   /// A helper data structure to hold the operands of a vector of instructions.
1306   /// This supports a fixed vector length for all operand vectors.
1307   class VLOperands {
1308     /// For each operand we need (i) the value, and (ii) the opcode that it
1309     /// would be attached to if the expression was in a left-linearized form.
1310     /// This is required to avoid illegal operand reordering.
1311     /// For example:
1312     /// \verbatim
1313     ///                         0 Op1
1314     ///                         |/
1315     /// Op1 Op2   Linearized    + Op2
1316     ///   \ /     ---------->   |/
1317     ///    -                    -
1318     ///
1319     /// Op1 - Op2            (0 + Op1) - Op2
1320     /// \endverbatim
1321     ///
1322     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1323     ///
1324     /// Another way to think of this is to track all the operations across the
1325     /// path from the operand all the way to the root of the tree and to
1326     /// calculate the operation that corresponds to this path. For example, the
1327     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1328     /// corresponding operation is a '-' (which matches the one in the
1329     /// linearized tree, as shown above).
1330     ///
1331     /// For lack of a better term, we refer to this operation as Accumulated
1332     /// Path Operation (APO).
1333     struct OperandData {
1334       OperandData() = default;
1335       OperandData(Value *V, bool APO, bool IsUsed)
1336           : V(V), APO(APO), IsUsed(IsUsed) {}
1337       /// The operand value.
1338       Value *V = nullptr;
1339       /// TreeEntries only allow a single opcode, or an alternate sequence of
1340       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1341       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1342       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1343       /// (e.g., Add/Mul)
1344       bool APO = false;
1345       /// Helper data for the reordering function.
1346       bool IsUsed = false;
1347     };
1348 
1349     /// During operand reordering, we are trying to select the operand at lane
1350     /// that matches best with the operand at the neighboring lane. Our
1351     /// selection is based on the type of value we are looking for. For example,
1352     /// if the neighboring lane has a load, we need to look for a load that is
1353     /// accessing a consecutive address. These strategies are summarized in the
1354     /// 'ReorderingMode' enumerator.
1355     enum class ReorderingMode {
1356       Load,     ///< Matching loads to consecutive memory addresses
1357       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1358       Constant, ///< Matching constants
1359       Splat,    ///< Matching the same instruction multiple times (broadcast)
1360       Failed,   ///< We failed to create a vectorizable group
1361     };
1362 
1363     using OperandDataVec = SmallVector<OperandData, 2>;
1364 
1365     /// A vector of operand vectors.
1366     SmallVector<OperandDataVec, 4> OpsVec;
1367 
1368     const DataLayout &DL;
1369     ScalarEvolution &SE;
1370     const BoUpSLP &R;
1371 
1372     /// \returns the operand data at \p OpIdx and \p Lane.
1373     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1374       return OpsVec[OpIdx][Lane];
1375     }
1376 
1377     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1378     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1379       return OpsVec[OpIdx][Lane];
1380     }
1381 
1382     /// Clears the used flag for all entries.
1383     void clearUsed() {
1384       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1385            OpIdx != NumOperands; ++OpIdx)
1386         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1387              ++Lane)
1388           OpsVec[OpIdx][Lane].IsUsed = false;
1389     }
1390 
1391     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1392     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1393       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1394     }
1395 
1396     /// \param Lane lane of the operands under analysis.
1397     /// \param OpIdx operand index in \p Lane lane we're looking the best
1398     /// candidate for.
1399     /// \param Idx operand index of the current candidate value.
1400     /// \returns The additional score due to possible broadcasting of the
1401     /// elements in the lane. It is more profitable to have power-of-2 unique
1402     /// elements in the lane, it will be vectorized with higher probability
1403     /// after removing duplicates. Currently the SLP vectorizer supports only
1404     /// vectorization of the power-of-2 number of unique scalars.
1405     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1406       Value *IdxLaneV = getData(Idx, Lane).V;
1407       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1408         return 0;
1409       SmallPtrSet<Value *, 4> Uniques;
1410       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1411         if (Ln == Lane)
1412           continue;
1413         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1414         if (!isa<Instruction>(OpIdxLnV))
1415           return 0;
1416         Uniques.insert(OpIdxLnV);
1417       }
1418       int UniquesCount = Uniques.size();
1419       int UniquesCntWithIdxLaneV =
1420           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1421       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1422       int UniquesCntWithOpIdxLaneV =
1423           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1424       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1425         return 0;
1426       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1427               UniquesCntWithOpIdxLaneV) -
1428              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1429     }
1430 
1431     /// \param Lane lane of the operands under analysis.
1432     /// \param OpIdx operand index in \p Lane lane we're looking the best
1433     /// candidate for.
1434     /// \param Idx operand index of the current candidate value.
1435     /// \returns The additional score for the scalar which users are all
1436     /// vectorized.
1437     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1438       Value *IdxLaneV = getData(Idx, Lane).V;
1439       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1440       // Do not care about number of uses for vector-like instructions
1441       // (extractelement/extractvalue with constant indices), they are extracts
1442       // themselves and already externally used. Vectorization of such
1443       // instructions does not add extra extractelement instruction, just may
1444       // remove it.
1445       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1446           isVectorLikeInstWithConstOps(OpIdxLaneV))
1447         return LookAheadHeuristics::ScoreAllUserVectorized;
1448       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1449       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1450         return 0;
1451       return R.areAllUsersVectorized(IdxLaneI, None)
1452                  ? LookAheadHeuristics::ScoreAllUserVectorized
1453                  : 0;
1454     }
1455 
1456     /// Score scaling factor for fully compatible instructions but with
1457     /// different number of external uses. Allows better selection of the
1458     /// instructions with less external uses.
1459     static const int ScoreScaleFactor = 10;
1460 
1461     /// \Returns the look-ahead score, which tells us how much the sub-trees
1462     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1463     /// score. This helps break ties in an informed way when we cannot decide on
1464     /// the order of the operands by just considering the immediate
1465     /// predecessors.
1466     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1467                           int Lane, unsigned OpIdx, unsigned Idx,
1468                           bool &IsUsed) {
1469       LookAheadHeuristics LookAhead(DL, SE, R, getNumLanes(),
1470                                     LookAheadMaxDepth);
1471       // Keep track of the instruction stack as we recurse into the operands
1472       // during the look-ahead score exploration.
1473       int Score =
1474           LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1475                                        /*CurrLevel=*/1, MainAltOps);
1476       if (Score) {
1477         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1478         if (Score <= -SplatScore) {
1479           // Set the minimum score for splat-like sequence to avoid setting
1480           // failed state.
1481           Score = 1;
1482         } else {
1483           Score += SplatScore;
1484           // Scale score to see the difference between different operands
1485           // and similar operands but all vectorized/not all vectorized
1486           // uses. It does not affect actual selection of the best
1487           // compatible operand in general, just allows to select the
1488           // operand with all vectorized uses.
1489           Score *= ScoreScaleFactor;
1490           Score += getExternalUseScore(Lane, OpIdx, Idx);
1491           IsUsed = true;
1492         }
1493       }
1494       return Score;
1495     }
1496 
1497     /// Best defined scores per lanes between the passes. Used to choose the
1498     /// best operand (with the highest score) between the passes.
1499     /// The key - {Operand Index, Lane}.
1500     /// The value - the best score between the passes for the lane and the
1501     /// operand.
1502     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1503         BestScoresPerLanes;
1504 
1505     // Search all operands in Ops[*][Lane] for the one that matches best
1506     // Ops[OpIdx][LastLane] and return its opreand index.
1507     // If no good match can be found, return None.
1508     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1509                                       ArrayRef<ReorderingMode> ReorderingModes,
1510                                       ArrayRef<Value *> MainAltOps) {
1511       unsigned NumOperands = getNumOperands();
1512 
1513       // The operand of the previous lane at OpIdx.
1514       Value *OpLastLane = getData(OpIdx, LastLane).V;
1515 
1516       // Our strategy mode for OpIdx.
1517       ReorderingMode RMode = ReorderingModes[OpIdx];
1518       if (RMode == ReorderingMode::Failed)
1519         return None;
1520 
1521       // The linearized opcode of the operand at OpIdx, Lane.
1522       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1523 
1524       // The best operand index and its score.
1525       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1526       // are using the score to differentiate between the two.
1527       struct BestOpData {
1528         Optional<unsigned> Idx = None;
1529         unsigned Score = 0;
1530       } BestOp;
1531       BestOp.Score =
1532           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1533               .first->second;
1534 
1535       // Track if the operand must be marked as used. If the operand is set to
1536       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1537       // want to reestimate the operands again on the following iterations).
1538       bool IsUsed =
1539           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1540       // Iterate through all unused operands and look for the best.
1541       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1542         // Get the operand at Idx and Lane.
1543         OperandData &OpData = getData(Idx, Lane);
1544         Value *Op = OpData.V;
1545         bool OpAPO = OpData.APO;
1546 
1547         // Skip already selected operands.
1548         if (OpData.IsUsed)
1549           continue;
1550 
1551         // Skip if we are trying to move the operand to a position with a
1552         // different opcode in the linearized tree form. This would break the
1553         // semantics.
1554         if (OpAPO != OpIdxAPO)
1555           continue;
1556 
1557         // Look for an operand that matches the current mode.
1558         switch (RMode) {
1559         case ReorderingMode::Load:
1560         case ReorderingMode::Constant:
1561         case ReorderingMode::Opcode: {
1562           bool LeftToRight = Lane > LastLane;
1563           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1564           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1565           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1566                                         OpIdx, Idx, IsUsed);
1567           if (Score > static_cast<int>(BestOp.Score)) {
1568             BestOp.Idx = Idx;
1569             BestOp.Score = Score;
1570             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1571           }
1572           break;
1573         }
1574         case ReorderingMode::Splat:
1575           if (Op == OpLastLane)
1576             BestOp.Idx = Idx;
1577           break;
1578         case ReorderingMode::Failed:
1579           llvm_unreachable("Not expected Failed reordering mode.");
1580         }
1581       }
1582 
1583       if (BestOp.Idx) {
1584         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1585         return BestOp.Idx;
1586       }
1587       // If we could not find a good match return None.
1588       return None;
1589     }
1590 
1591     /// Helper for reorderOperandVecs.
1592     /// \returns the lane that we should start reordering from. This is the one
1593     /// which has the least number of operands that can freely move about or
1594     /// less profitable because it already has the most optimal set of operands.
1595     unsigned getBestLaneToStartReordering() const {
1596       unsigned Min = UINT_MAX;
1597       unsigned SameOpNumber = 0;
1598       // std::pair<unsigned, unsigned> is used to implement a simple voting
1599       // algorithm and choose the lane with the least number of operands that
1600       // can freely move about or less profitable because it already has the
1601       // most optimal set of operands. The first unsigned is a counter for
1602       // voting, the second unsigned is the counter of lanes with instructions
1603       // with same/alternate opcodes and same parent basic block.
1604       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1605       // Try to be closer to the original results, if we have multiple lanes
1606       // with same cost. If 2 lanes have the same cost, use the one with the
1607       // lowest index.
1608       for (int I = getNumLanes(); I > 0; --I) {
1609         unsigned Lane = I - 1;
1610         OperandsOrderData NumFreeOpsHash =
1611             getMaxNumOperandsThatCanBeReordered(Lane);
1612         // Compare the number of operands that can move and choose the one with
1613         // the least number.
1614         if (NumFreeOpsHash.NumOfAPOs < Min) {
1615           Min = NumFreeOpsHash.NumOfAPOs;
1616           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1617           HashMap.clear();
1618           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1619         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1620                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1621           // Select the most optimal lane in terms of number of operands that
1622           // should be moved around.
1623           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1624           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1625         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1626                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1627           auto It = HashMap.find(NumFreeOpsHash.Hash);
1628           if (It == HashMap.end())
1629             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1630           else
1631             ++It->second.first;
1632         }
1633       }
1634       // Select the lane with the minimum counter.
1635       unsigned BestLane = 0;
1636       unsigned CntMin = UINT_MAX;
1637       for (const auto &Data : reverse(HashMap)) {
1638         if (Data.second.first < CntMin) {
1639           CntMin = Data.second.first;
1640           BestLane = Data.second.second;
1641         }
1642       }
1643       return BestLane;
1644     }
1645 
1646     /// Data structure that helps to reorder operands.
1647     struct OperandsOrderData {
1648       /// The best number of operands with the same APOs, which can be
1649       /// reordered.
1650       unsigned NumOfAPOs = UINT_MAX;
1651       /// Number of operands with the same/alternate instruction opcode and
1652       /// parent.
1653       unsigned NumOpsWithSameOpcodeParent = 0;
1654       /// Hash for the actual operands ordering.
1655       /// Used to count operands, actually their position id and opcode
1656       /// value. It is used in the voting mechanism to find the lane with the
1657       /// least number of operands that can freely move about or less profitable
1658       /// because it already has the most optimal set of operands. Can be
1659       /// replaced with SmallVector<unsigned> instead but hash code is faster
1660       /// and requires less memory.
1661       unsigned Hash = 0;
1662     };
1663     /// \returns the maximum number of operands that are allowed to be reordered
1664     /// for \p Lane and the number of compatible instructions(with the same
1665     /// parent/opcode). This is used as a heuristic for selecting the first lane
1666     /// to start operand reordering.
1667     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1668       unsigned CntTrue = 0;
1669       unsigned NumOperands = getNumOperands();
1670       // Operands with the same APO can be reordered. We therefore need to count
1671       // how many of them we have for each APO, like this: Cnt[APO] = x.
1672       // Since we only have two APOs, namely true and false, we can avoid using
1673       // a map. Instead we can simply count the number of operands that
1674       // correspond to one of them (in this case the 'true' APO), and calculate
1675       // the other by subtracting it from the total number of operands.
1676       // Operands with the same instruction opcode and parent are more
1677       // profitable since we don't need to move them in many cases, with a high
1678       // probability such lane already can be vectorized effectively.
1679       bool AllUndefs = true;
1680       unsigned NumOpsWithSameOpcodeParent = 0;
1681       Instruction *OpcodeI = nullptr;
1682       BasicBlock *Parent = nullptr;
1683       unsigned Hash = 0;
1684       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1685         const OperandData &OpData = getData(OpIdx, Lane);
1686         if (OpData.APO)
1687           ++CntTrue;
1688         // Use Boyer-Moore majority voting for finding the majority opcode and
1689         // the number of times it occurs.
1690         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1691           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1692               I->getParent() != Parent) {
1693             if (NumOpsWithSameOpcodeParent == 0) {
1694               NumOpsWithSameOpcodeParent = 1;
1695               OpcodeI = I;
1696               Parent = I->getParent();
1697             } else {
1698               --NumOpsWithSameOpcodeParent;
1699             }
1700           } else {
1701             ++NumOpsWithSameOpcodeParent;
1702           }
1703         }
1704         Hash = hash_combine(
1705             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1706         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1707       }
1708       if (AllUndefs)
1709         return {};
1710       OperandsOrderData Data;
1711       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1712       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1713       Data.Hash = Hash;
1714       return Data;
1715     }
1716 
1717     /// Go through the instructions in VL and append their operands.
1718     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1719       assert(!VL.empty() && "Bad VL");
1720       assert((empty() || VL.size() == getNumLanes()) &&
1721              "Expected same number of lanes");
1722       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1723       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1724       OpsVec.resize(NumOperands);
1725       unsigned NumLanes = VL.size();
1726       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1727         OpsVec[OpIdx].resize(NumLanes);
1728         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1729           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1730           // Our tree has just 3 nodes: the root and two operands.
1731           // It is therefore trivial to get the APO. We only need to check the
1732           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1733           // RHS operand. The LHS operand of both add and sub is never attached
1734           // to an inversese operation in the linearized form, therefore its APO
1735           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1736 
1737           // Since operand reordering is performed on groups of commutative
1738           // operations or alternating sequences (e.g., +, -), we can safely
1739           // tell the inverse operations by checking commutativity.
1740           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1741           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1742           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1743                                  APO, false};
1744         }
1745       }
1746     }
1747 
1748     /// \returns the number of operands.
1749     unsigned getNumOperands() const { return OpsVec.size(); }
1750 
1751     /// \returns the number of lanes.
1752     unsigned getNumLanes() const { return OpsVec[0].size(); }
1753 
1754     /// \returns the operand value at \p OpIdx and \p Lane.
1755     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1756       return getData(OpIdx, Lane).V;
1757     }
1758 
1759     /// \returns true if the data structure is empty.
1760     bool empty() const { return OpsVec.empty(); }
1761 
1762     /// Clears the data.
1763     void clear() { OpsVec.clear(); }
1764 
1765     /// \Returns true if there are enough operands identical to \p Op to fill
1766     /// the whole vector.
1767     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1768     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1769       bool OpAPO = getData(OpIdx, Lane).APO;
1770       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1771         if (Ln == Lane)
1772           continue;
1773         // This is set to true if we found a candidate for broadcast at Lane.
1774         bool FoundCandidate = false;
1775         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1776           OperandData &Data = getData(OpI, Ln);
1777           if (Data.APO != OpAPO || Data.IsUsed)
1778             continue;
1779           if (Data.V == Op) {
1780             FoundCandidate = true;
1781             Data.IsUsed = true;
1782             break;
1783           }
1784         }
1785         if (!FoundCandidate)
1786           return false;
1787       }
1788       return true;
1789     }
1790 
1791   public:
1792     /// Initialize with all the operands of the instruction vector \p RootVL.
1793     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1794                ScalarEvolution &SE, const BoUpSLP &R)
1795         : DL(DL), SE(SE), R(R) {
1796       // Append all the operands of RootVL.
1797       appendOperandsOfVL(RootVL);
1798     }
1799 
1800     /// \Returns a value vector with the operands across all lanes for the
1801     /// opearnd at \p OpIdx.
1802     ValueList getVL(unsigned OpIdx) const {
1803       ValueList OpVL(OpsVec[OpIdx].size());
1804       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1805              "Expected same num of lanes across all operands");
1806       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1807         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1808       return OpVL;
1809     }
1810 
1811     // Performs operand reordering for 2 or more operands.
1812     // The original operands are in OrigOps[OpIdx][Lane].
1813     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1814     void reorder() {
1815       unsigned NumOperands = getNumOperands();
1816       unsigned NumLanes = getNumLanes();
1817       // Each operand has its own mode. We are using this mode to help us select
1818       // the instructions for each lane, so that they match best with the ones
1819       // we have selected so far.
1820       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1821 
1822       // This is a greedy single-pass algorithm. We are going over each lane
1823       // once and deciding on the best order right away with no back-tracking.
1824       // However, in order to increase its effectiveness, we start with the lane
1825       // that has operands that can move the least. For example, given the
1826       // following lanes:
1827       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1828       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1829       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1830       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1831       // we will start at Lane 1, since the operands of the subtraction cannot
1832       // be reordered. Then we will visit the rest of the lanes in a circular
1833       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1834 
1835       // Find the first lane that we will start our search from.
1836       unsigned FirstLane = getBestLaneToStartReordering();
1837 
1838       // Initialize the modes.
1839       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1840         Value *OpLane0 = getValue(OpIdx, FirstLane);
1841         // Keep track if we have instructions with all the same opcode on one
1842         // side.
1843         if (isa<LoadInst>(OpLane0))
1844           ReorderingModes[OpIdx] = ReorderingMode::Load;
1845         else if (isa<Instruction>(OpLane0)) {
1846           // Check if OpLane0 should be broadcast.
1847           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1848             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1849           else
1850             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1851         }
1852         else if (isa<Constant>(OpLane0))
1853           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1854         else if (isa<Argument>(OpLane0))
1855           // Our best hope is a Splat. It may save some cost in some cases.
1856           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1857         else
1858           // NOTE: This should be unreachable.
1859           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1860       }
1861 
1862       // Check that we don't have same operands. No need to reorder if operands
1863       // are just perfect diamond or shuffled diamond match. Do not do it only
1864       // for possible broadcasts or non-power of 2 number of scalars (just for
1865       // now).
1866       auto &&SkipReordering = [this]() {
1867         SmallPtrSet<Value *, 4> UniqueValues;
1868         ArrayRef<OperandData> Op0 = OpsVec.front();
1869         for (const OperandData &Data : Op0)
1870           UniqueValues.insert(Data.V);
1871         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1872           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1873                 return !UniqueValues.contains(Data.V);
1874               }))
1875             return false;
1876         }
1877         // TODO: Check if we can remove a check for non-power-2 number of
1878         // scalars after full support of non-power-2 vectorization.
1879         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1880       };
1881 
1882       // If the initial strategy fails for any of the operand indexes, then we
1883       // perform reordering again in a second pass. This helps avoid assigning
1884       // high priority to the failed strategy, and should improve reordering for
1885       // the non-failed operand indexes.
1886       for (int Pass = 0; Pass != 2; ++Pass) {
1887         // Check if no need to reorder operands since they're are perfect or
1888         // shuffled diamond match.
1889         // Need to to do it to avoid extra external use cost counting for
1890         // shuffled matches, which may cause regressions.
1891         if (SkipReordering())
1892           break;
1893         // Skip the second pass if the first pass did not fail.
1894         bool StrategyFailed = false;
1895         // Mark all operand data as free to use.
1896         clearUsed();
1897         // We keep the original operand order for the FirstLane, so reorder the
1898         // rest of the lanes. We are visiting the nodes in a circular fashion,
1899         // using FirstLane as the center point and increasing the radius
1900         // distance.
1901         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1902         for (unsigned I = 0; I < NumOperands; ++I)
1903           MainAltOps[I].push_back(getData(I, FirstLane).V);
1904 
1905         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1906           // Visit the lane on the right and then the lane on the left.
1907           for (int Direction : {+1, -1}) {
1908             int Lane = FirstLane + Direction * Distance;
1909             if (Lane < 0 || Lane >= (int)NumLanes)
1910               continue;
1911             int LastLane = Lane - Direction;
1912             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1913                    "Out of bounds");
1914             // Look for a good match for each operand.
1915             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1916               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1917               Optional<unsigned> BestIdx = getBestOperand(
1918                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1919               // By not selecting a value, we allow the operands that follow to
1920               // select a better matching value. We will get a non-null value in
1921               // the next run of getBestOperand().
1922               if (BestIdx) {
1923                 // Swap the current operand with the one returned by
1924                 // getBestOperand().
1925                 swap(OpIdx, BestIdx.getValue(), Lane);
1926               } else {
1927                 // We failed to find a best operand, set mode to 'Failed'.
1928                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1929                 // Enable the second pass.
1930                 StrategyFailed = true;
1931               }
1932               // Try to get the alternate opcode and follow it during analysis.
1933               if (MainAltOps[OpIdx].size() != 2) {
1934                 OperandData &AltOp = getData(OpIdx, Lane);
1935                 InstructionsState OpS =
1936                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1937                 if (OpS.getOpcode() && OpS.isAltShuffle())
1938                   MainAltOps[OpIdx].push_back(AltOp.V);
1939               }
1940             }
1941           }
1942         }
1943         // Skip second pass if the strategy did not fail.
1944         if (!StrategyFailed)
1945           break;
1946       }
1947     }
1948 
1949 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1950     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1951       switch (RMode) {
1952       case ReorderingMode::Load:
1953         return "Load";
1954       case ReorderingMode::Opcode:
1955         return "Opcode";
1956       case ReorderingMode::Constant:
1957         return "Constant";
1958       case ReorderingMode::Splat:
1959         return "Splat";
1960       case ReorderingMode::Failed:
1961         return "Failed";
1962       }
1963       llvm_unreachable("Unimplemented Reordering Type");
1964     }
1965 
1966     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1967                                                    raw_ostream &OS) {
1968       return OS << getModeStr(RMode);
1969     }
1970 
1971     /// Debug print.
1972     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1973       printMode(RMode, dbgs());
1974     }
1975 
1976     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1977       return printMode(RMode, OS);
1978     }
1979 
1980     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1981       const unsigned Indent = 2;
1982       unsigned Cnt = 0;
1983       for (const OperandDataVec &OpDataVec : OpsVec) {
1984         OS << "Operand " << Cnt++ << "\n";
1985         for (const OperandData &OpData : OpDataVec) {
1986           OS.indent(Indent) << "{";
1987           if (Value *V = OpData.V)
1988             OS << *V;
1989           else
1990             OS << "null";
1991           OS << ", APO:" << OpData.APO << "}\n";
1992         }
1993         OS << "\n";
1994       }
1995       return OS;
1996     }
1997 
1998     /// Debug print.
1999     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2000 #endif
2001   };
2002 
2003   /// Checks if the instruction is marked for deletion.
2004   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2005 
2006   /// Removes an instruction from its block and eventually deletes it.
2007   /// It's like Instruction::eraseFromParent() except that the actual deletion
2008   /// is delayed until BoUpSLP is destructed.
2009   void eraseInstruction(Instruction *I) {
2010     DeletedInstructions.insert(I);
2011   }
2012 
2013   ~BoUpSLP();
2014 
2015 private:
2016   /// Check if the operands on the edges \p Edges of the \p UserTE allows
2017   /// reordering (i.e. the operands can be reordered because they have only one
2018   /// user and reordarable).
2019   /// \param ReorderableGathers List of all gather nodes that require reordering
2020   /// (e.g., gather of extractlements or partially vectorizable loads).
2021   /// \param GatherOps List of gather operand nodes for \p UserTE that require
2022   /// reordering, subset of \p NonVectorized.
2023   bool
2024   canReorderOperands(TreeEntry *UserTE,
2025                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2026                      ArrayRef<TreeEntry *> ReorderableGathers,
2027                      SmallVectorImpl<TreeEntry *> &GatherOps);
2028 
2029   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2030   /// if any. If it is not vectorized (gather node), returns nullptr.
2031   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2032     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2033     TreeEntry *TE = nullptr;
2034     const auto *It = find_if(VL, [this, &TE](Value *V) {
2035       TE = getTreeEntry(V);
2036       return TE;
2037     });
2038     if (It != VL.end() && TE->isSame(VL))
2039       return TE;
2040     return nullptr;
2041   }
2042 
2043   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2044   /// if any. If it is not vectorized (gather node), returns nullptr.
2045   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2046                                         unsigned OpIdx) const {
2047     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2048         const_cast<TreeEntry *>(UserTE), OpIdx);
2049   }
2050 
2051   /// Checks if all users of \p I are the part of the vectorization tree.
2052   bool areAllUsersVectorized(Instruction *I,
2053                              ArrayRef<Value *> VectorizedVals) const;
2054 
2055   /// \returns the cost of the vectorizable entry.
2056   InstructionCost getEntryCost(const TreeEntry *E,
2057                                ArrayRef<Value *> VectorizedVals);
2058 
2059   /// This is the recursive part of buildTree.
2060   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2061                      const EdgeInfo &EI);
2062 
2063   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2064   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2065   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2066   /// returns false, setting \p CurrentOrder to either an empty vector or a
2067   /// non-identity permutation that allows to reuse extract instructions.
2068   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2069                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2070 
2071   /// Vectorize a single entry in the tree.
2072   Value *vectorizeTree(TreeEntry *E);
2073 
2074   /// Vectorize a single entry in the tree, starting in \p VL.
2075   Value *vectorizeTree(ArrayRef<Value *> VL);
2076 
2077   /// Create a new vector from a list of scalar values.  Produces a sequence
2078   /// which exploits values reused across lanes, and arranges the inserts
2079   /// for ease of later optimization.
2080   Value *createBuildVector(ArrayRef<Value *> VL);
2081 
2082   /// \returns the scalarization cost for this type. Scalarization in this
2083   /// context means the creation of vectors from a group of scalars. If \p
2084   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2085   /// vector elements.
2086   InstructionCost getGatherCost(FixedVectorType *Ty,
2087                                 const APInt &ShuffledIndices,
2088                                 bool NeedToShuffle) const;
2089 
2090   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2091   /// tree entries.
2092   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2093   /// previous tree entries. \p Mask is filled with the shuffle mask.
2094   Optional<TargetTransformInfo::ShuffleKind>
2095   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2096                         SmallVectorImpl<const TreeEntry *> &Entries);
2097 
2098   /// \returns the scalarization cost for this list of values. Assuming that
2099   /// this subtree gets vectorized, we may need to extract the values from the
2100   /// roots. This method calculates the cost of extracting the values.
2101   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2102 
2103   /// Set the Builder insert point to one after the last instruction in
2104   /// the bundle
2105   void setInsertPointAfterBundle(const TreeEntry *E);
2106 
2107   /// \returns a vector from a collection of scalars in \p VL.
2108   Value *gather(ArrayRef<Value *> VL);
2109 
2110   /// \returns whether the VectorizableTree is fully vectorizable and will
2111   /// be beneficial even the tree height is tiny.
2112   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2113 
2114   /// Reorder commutative or alt operands to get better probability of
2115   /// generating vectorized code.
2116   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2117                                              SmallVectorImpl<Value *> &Left,
2118                                              SmallVectorImpl<Value *> &Right,
2119                                              const DataLayout &DL,
2120                                              ScalarEvolution &SE,
2121                                              const BoUpSLP &R);
2122   struct TreeEntry {
2123     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2124     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2125 
2126     /// \returns true if the scalars in VL are equal to this entry.
2127     bool isSame(ArrayRef<Value *> VL) const {
2128       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2129         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2130           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2131         return VL.size() == Mask.size() &&
2132                std::equal(VL.begin(), VL.end(), Mask.begin(),
2133                           [Scalars](Value *V, int Idx) {
2134                             return (isa<UndefValue>(V) &&
2135                                     Idx == UndefMaskElem) ||
2136                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2137                           });
2138       };
2139       if (!ReorderIndices.empty()) {
2140         // TODO: implement matching if the nodes are just reordered, still can
2141         // treat the vector as the same if the list of scalars matches VL
2142         // directly, without reordering.
2143         SmallVector<int> Mask;
2144         inversePermutation(ReorderIndices, Mask);
2145         if (VL.size() == Scalars.size())
2146           return IsSame(Scalars, Mask);
2147         if (VL.size() == ReuseShuffleIndices.size()) {
2148           ::addMask(Mask, ReuseShuffleIndices);
2149           return IsSame(Scalars, Mask);
2150         }
2151         return false;
2152       }
2153       return IsSame(Scalars, ReuseShuffleIndices);
2154     }
2155 
2156     /// \returns true if current entry has same operands as \p TE.
2157     bool hasEqualOperands(const TreeEntry &TE) const {
2158       if (TE.getNumOperands() != getNumOperands())
2159         return false;
2160       SmallBitVector Used(getNumOperands());
2161       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2162         unsigned PrevCount = Used.count();
2163         for (unsigned K = 0; K < E; ++K) {
2164           if (Used.test(K))
2165             continue;
2166           if (getOperand(K) == TE.getOperand(I)) {
2167             Used.set(K);
2168             break;
2169           }
2170         }
2171         // Check if we actually found the matching operand.
2172         if (PrevCount == Used.count())
2173           return false;
2174       }
2175       return true;
2176     }
2177 
2178     /// \return Final vectorization factor for the node. Defined by the total
2179     /// number of vectorized scalars, including those, used several times in the
2180     /// entry and counted in the \a ReuseShuffleIndices, if any.
2181     unsigned getVectorFactor() const {
2182       if (!ReuseShuffleIndices.empty())
2183         return ReuseShuffleIndices.size();
2184       return Scalars.size();
2185     };
2186 
2187     /// A vector of scalars.
2188     ValueList Scalars;
2189 
2190     /// The Scalars are vectorized into this value. It is initialized to Null.
2191     Value *VectorizedValue = nullptr;
2192 
2193     /// Do we need to gather this sequence or vectorize it
2194     /// (either with vector instruction or with scatter/gather
2195     /// intrinsics for store/load)?
2196     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2197     EntryState State;
2198 
2199     /// Does this sequence require some shuffling?
2200     SmallVector<int, 4> ReuseShuffleIndices;
2201 
2202     /// Does this entry require reordering?
2203     SmallVector<unsigned, 4> ReorderIndices;
2204 
2205     /// Points back to the VectorizableTree.
2206     ///
2207     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2208     /// to be a pointer and needs to be able to initialize the child iterator.
2209     /// Thus we need a reference back to the container to translate the indices
2210     /// to entries.
2211     VecTreeTy &Container;
2212 
2213     /// The TreeEntry index containing the user of this entry.  We can actually
2214     /// have multiple users so the data structure is not truly a tree.
2215     SmallVector<EdgeInfo, 1> UserTreeIndices;
2216 
2217     /// The index of this treeEntry in VectorizableTree.
2218     int Idx = -1;
2219 
2220   private:
2221     /// The operands of each instruction in each lane Operands[op_index][lane].
2222     /// Note: This helps avoid the replication of the code that performs the
2223     /// reordering of operands during buildTree_rec() and vectorizeTree().
2224     SmallVector<ValueList, 2> Operands;
2225 
2226     /// The main/alternate instruction.
2227     Instruction *MainOp = nullptr;
2228     Instruction *AltOp = nullptr;
2229 
2230   public:
2231     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2232     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2233       if (Operands.size() < OpIdx + 1)
2234         Operands.resize(OpIdx + 1);
2235       assert(Operands[OpIdx].empty() && "Already resized?");
2236       assert(OpVL.size() <= Scalars.size() &&
2237              "Number of operands is greater than the number of scalars.");
2238       Operands[OpIdx].resize(OpVL.size());
2239       copy(OpVL, Operands[OpIdx].begin());
2240     }
2241 
2242     /// Set the operands of this bundle in their original order.
2243     void setOperandsInOrder() {
2244       assert(Operands.empty() && "Already initialized?");
2245       auto *I0 = cast<Instruction>(Scalars[0]);
2246       Operands.resize(I0->getNumOperands());
2247       unsigned NumLanes = Scalars.size();
2248       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2249            OpIdx != NumOperands; ++OpIdx) {
2250         Operands[OpIdx].resize(NumLanes);
2251         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2252           auto *I = cast<Instruction>(Scalars[Lane]);
2253           assert(I->getNumOperands() == NumOperands &&
2254                  "Expected same number of operands");
2255           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2256         }
2257       }
2258     }
2259 
2260     /// Reorders operands of the node to the given mask \p Mask.
2261     void reorderOperands(ArrayRef<int> Mask) {
2262       for (ValueList &Operand : Operands)
2263         reorderScalars(Operand, Mask);
2264     }
2265 
2266     /// \returns the \p OpIdx operand of this TreeEntry.
2267     ValueList &getOperand(unsigned OpIdx) {
2268       assert(OpIdx < Operands.size() && "Off bounds");
2269       return Operands[OpIdx];
2270     }
2271 
2272     /// \returns the \p OpIdx operand of this TreeEntry.
2273     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2274       assert(OpIdx < Operands.size() && "Off bounds");
2275       return Operands[OpIdx];
2276     }
2277 
2278     /// \returns the number of operands.
2279     unsigned getNumOperands() const { return Operands.size(); }
2280 
2281     /// \return the single \p OpIdx operand.
2282     Value *getSingleOperand(unsigned OpIdx) const {
2283       assert(OpIdx < Operands.size() && "Off bounds");
2284       assert(!Operands[OpIdx].empty() && "No operand available");
2285       return Operands[OpIdx][0];
2286     }
2287 
2288     /// Some of the instructions in the list have alternate opcodes.
2289     bool isAltShuffle() const { return MainOp != AltOp; }
2290 
2291     bool isOpcodeOrAlt(Instruction *I) const {
2292       unsigned CheckedOpcode = I->getOpcode();
2293       return (getOpcode() == CheckedOpcode ||
2294               getAltOpcode() == CheckedOpcode);
2295     }
2296 
2297     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2298     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2299     /// \p OpValue.
2300     Value *isOneOf(Value *Op) const {
2301       auto *I = dyn_cast<Instruction>(Op);
2302       if (I && isOpcodeOrAlt(I))
2303         return Op;
2304       return MainOp;
2305     }
2306 
2307     void setOperations(const InstructionsState &S) {
2308       MainOp = S.MainOp;
2309       AltOp = S.AltOp;
2310     }
2311 
2312     Instruction *getMainOp() const {
2313       return MainOp;
2314     }
2315 
2316     Instruction *getAltOp() const {
2317       return AltOp;
2318     }
2319 
2320     /// The main/alternate opcodes for the list of instructions.
2321     unsigned getOpcode() const {
2322       return MainOp ? MainOp->getOpcode() : 0;
2323     }
2324 
2325     unsigned getAltOpcode() const {
2326       return AltOp ? AltOp->getOpcode() : 0;
2327     }
2328 
2329     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2330     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2331     int findLaneForValue(Value *V) const {
2332       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2333       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2334       if (!ReorderIndices.empty())
2335         FoundLane = ReorderIndices[FoundLane];
2336       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2337       if (!ReuseShuffleIndices.empty()) {
2338         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2339                                   find(ReuseShuffleIndices, FoundLane));
2340       }
2341       return FoundLane;
2342     }
2343 
2344 #ifndef NDEBUG
2345     /// Debug printer.
2346     LLVM_DUMP_METHOD void dump() const {
2347       dbgs() << Idx << ".\n";
2348       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2349         dbgs() << "Operand " << OpI << ":\n";
2350         for (const Value *V : Operands[OpI])
2351           dbgs().indent(2) << *V << "\n";
2352       }
2353       dbgs() << "Scalars: \n";
2354       for (Value *V : Scalars)
2355         dbgs().indent(2) << *V << "\n";
2356       dbgs() << "State: ";
2357       switch (State) {
2358       case Vectorize:
2359         dbgs() << "Vectorize\n";
2360         break;
2361       case ScatterVectorize:
2362         dbgs() << "ScatterVectorize\n";
2363         break;
2364       case NeedToGather:
2365         dbgs() << "NeedToGather\n";
2366         break;
2367       }
2368       dbgs() << "MainOp: ";
2369       if (MainOp)
2370         dbgs() << *MainOp << "\n";
2371       else
2372         dbgs() << "NULL\n";
2373       dbgs() << "AltOp: ";
2374       if (AltOp)
2375         dbgs() << *AltOp << "\n";
2376       else
2377         dbgs() << "NULL\n";
2378       dbgs() << "VectorizedValue: ";
2379       if (VectorizedValue)
2380         dbgs() << *VectorizedValue << "\n";
2381       else
2382         dbgs() << "NULL\n";
2383       dbgs() << "ReuseShuffleIndices: ";
2384       if (ReuseShuffleIndices.empty())
2385         dbgs() << "Empty";
2386       else
2387         for (int ReuseIdx : ReuseShuffleIndices)
2388           dbgs() << ReuseIdx << ", ";
2389       dbgs() << "\n";
2390       dbgs() << "ReorderIndices: ";
2391       for (unsigned ReorderIdx : ReorderIndices)
2392         dbgs() << ReorderIdx << ", ";
2393       dbgs() << "\n";
2394       dbgs() << "UserTreeIndices: ";
2395       for (const auto &EInfo : UserTreeIndices)
2396         dbgs() << EInfo << ", ";
2397       dbgs() << "\n";
2398     }
2399 #endif
2400   };
2401 
2402 #ifndef NDEBUG
2403   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2404                      InstructionCost VecCost,
2405                      InstructionCost ScalarCost) const {
2406     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2407     dbgs() << "SLP: Costs:\n";
2408     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2409     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2410     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2411     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2412                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2413   }
2414 #endif
2415 
2416   /// Create a new VectorizableTree entry.
2417   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2418                           const InstructionsState &S,
2419                           const EdgeInfo &UserTreeIdx,
2420                           ArrayRef<int> ReuseShuffleIndices = None,
2421                           ArrayRef<unsigned> ReorderIndices = None) {
2422     TreeEntry::EntryState EntryState =
2423         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2424     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2425                         ReuseShuffleIndices, ReorderIndices);
2426   }
2427 
2428   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2429                           TreeEntry::EntryState EntryState,
2430                           Optional<ScheduleData *> Bundle,
2431                           const InstructionsState &S,
2432                           const EdgeInfo &UserTreeIdx,
2433                           ArrayRef<int> ReuseShuffleIndices = None,
2434                           ArrayRef<unsigned> ReorderIndices = None) {
2435     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2436             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2437            "Need to vectorize gather entry?");
2438     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2439     TreeEntry *Last = VectorizableTree.back().get();
2440     Last->Idx = VectorizableTree.size() - 1;
2441     Last->State = EntryState;
2442     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2443                                      ReuseShuffleIndices.end());
2444     if (ReorderIndices.empty()) {
2445       Last->Scalars.assign(VL.begin(), VL.end());
2446       Last->setOperations(S);
2447     } else {
2448       // Reorder scalars and build final mask.
2449       Last->Scalars.assign(VL.size(), nullptr);
2450       transform(ReorderIndices, Last->Scalars.begin(),
2451                 [VL](unsigned Idx) -> Value * {
2452                   if (Idx >= VL.size())
2453                     return UndefValue::get(VL.front()->getType());
2454                   return VL[Idx];
2455                 });
2456       InstructionsState S = getSameOpcode(Last->Scalars);
2457       Last->setOperations(S);
2458       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2459     }
2460     if (Last->State != TreeEntry::NeedToGather) {
2461       for (Value *V : VL) {
2462         assert(!getTreeEntry(V) && "Scalar already in tree!");
2463         ScalarToTreeEntry[V] = Last;
2464       }
2465       // Update the scheduler bundle to point to this TreeEntry.
2466       ScheduleData *BundleMember = Bundle.getValue();
2467       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2468               isVectorLikeInstWithConstOps(S.MainOp) ||
2469               doesNotNeedToSchedule(VL)) &&
2470              "Bundle and VL out of sync");
2471       if (BundleMember) {
2472         for (Value *V : VL) {
2473           if (doesNotNeedToBeScheduled(V))
2474             continue;
2475           assert(BundleMember && "Unexpected end of bundle.");
2476           BundleMember->TE = Last;
2477           BundleMember = BundleMember->NextInBundle;
2478         }
2479       }
2480       assert(!BundleMember && "Bundle and VL out of sync");
2481     } else {
2482       MustGather.insert(VL.begin(), VL.end());
2483     }
2484 
2485     if (UserTreeIdx.UserTE)
2486       Last->UserTreeIndices.push_back(UserTreeIdx);
2487 
2488     return Last;
2489   }
2490 
2491   /// -- Vectorization State --
2492   /// Holds all of the tree entries.
2493   TreeEntry::VecTreeTy VectorizableTree;
2494 
2495 #ifndef NDEBUG
2496   /// Debug printer.
2497   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2498     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2499       VectorizableTree[Id]->dump();
2500       dbgs() << "\n";
2501     }
2502   }
2503 #endif
2504 
2505   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2506 
2507   const TreeEntry *getTreeEntry(Value *V) const {
2508     return ScalarToTreeEntry.lookup(V);
2509   }
2510 
2511   /// Maps a specific scalar to its tree entry.
2512   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2513 
2514   /// Maps a value to the proposed vectorizable size.
2515   SmallDenseMap<Value *, unsigned> InstrElementSize;
2516 
2517   /// A list of scalars that we found that we need to keep as scalars.
2518   ValueSet MustGather;
2519 
2520   /// This POD struct describes one external user in the vectorized tree.
2521   struct ExternalUser {
2522     ExternalUser(Value *S, llvm::User *U, int L)
2523         : Scalar(S), User(U), Lane(L) {}
2524 
2525     // Which scalar in our function.
2526     Value *Scalar;
2527 
2528     // Which user that uses the scalar.
2529     llvm::User *User;
2530 
2531     // Which lane does the scalar belong to.
2532     int Lane;
2533   };
2534   using UserList = SmallVector<ExternalUser, 16>;
2535 
2536   /// Checks if two instructions may access the same memory.
2537   ///
2538   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2539   /// is invariant in the calling loop.
2540   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2541                  Instruction *Inst2) {
2542     // First check if the result is already in the cache.
2543     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2544     Optional<bool> &result = AliasCache[key];
2545     if (result.hasValue()) {
2546       return result.getValue();
2547     }
2548     bool aliased = true;
2549     if (Loc1.Ptr && isSimple(Inst1))
2550       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2551     // Store the result in the cache.
2552     result = aliased;
2553     return aliased;
2554   }
2555 
2556   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2557 
2558   /// Cache for alias results.
2559   /// TODO: consider moving this to the AliasAnalysis itself.
2560   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2561 
2562   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2563   // globally through SLP because we don't perform any action which
2564   // invalidates capture results.
2565   BatchAAResults BatchAA;
2566 
2567   /// Temporary store for deleted instructions. Instructions will be deleted
2568   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2569   /// ensure that there are no incorrect collisions in the AliasCache, which
2570   /// can happen if a new instruction is allocated at the same address as a
2571   /// previously deleted instruction.
2572   DenseSet<Instruction *> DeletedInstructions;
2573 
2574   /// A list of values that need to extracted out of the tree.
2575   /// This list holds pairs of (Internal Scalar : External User). External User
2576   /// can be nullptr, it means that this Internal Scalar will be used later,
2577   /// after vectorization.
2578   UserList ExternalUses;
2579 
2580   /// Values used only by @llvm.assume calls.
2581   SmallPtrSet<const Value *, 32> EphValues;
2582 
2583   /// Holds all of the instructions that we gathered.
2584   SetVector<Instruction *> GatherShuffleSeq;
2585 
2586   /// A list of blocks that we are going to CSE.
2587   SetVector<BasicBlock *> CSEBlocks;
2588 
2589   /// Contains all scheduling relevant data for an instruction.
2590   /// A ScheduleData either represents a single instruction or a member of an
2591   /// instruction bundle (= a group of instructions which is combined into a
2592   /// vector instruction).
2593   struct ScheduleData {
2594     // The initial value for the dependency counters. It means that the
2595     // dependencies are not calculated yet.
2596     enum { InvalidDeps = -1 };
2597 
2598     ScheduleData() = default;
2599 
2600     void init(int BlockSchedulingRegionID, Value *OpVal) {
2601       FirstInBundle = this;
2602       NextInBundle = nullptr;
2603       NextLoadStore = nullptr;
2604       IsScheduled = false;
2605       SchedulingRegionID = BlockSchedulingRegionID;
2606       clearDependencies();
2607       OpValue = OpVal;
2608       TE = nullptr;
2609     }
2610 
2611     /// Verify basic self consistency properties
2612     void verify() {
2613       if (hasValidDependencies()) {
2614         assert(UnscheduledDeps <= Dependencies && "invariant");
2615       } else {
2616         assert(UnscheduledDeps == Dependencies && "invariant");
2617       }
2618 
2619       if (IsScheduled) {
2620         assert(isSchedulingEntity() &&
2621                 "unexpected scheduled state");
2622         for (const ScheduleData *BundleMember = this; BundleMember;
2623              BundleMember = BundleMember->NextInBundle) {
2624           assert(BundleMember->hasValidDependencies() &&
2625                  BundleMember->UnscheduledDeps == 0 &&
2626                  "unexpected scheduled state");
2627           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2628                  "only bundle is marked scheduled");
2629         }
2630       }
2631 
2632       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2633              "all bundle members must be in same basic block");
2634     }
2635 
2636     /// Returns true if the dependency information has been calculated.
2637     /// Note that depenendency validity can vary between instructions within
2638     /// a single bundle.
2639     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2640 
2641     /// Returns true for single instructions and for bundle representatives
2642     /// (= the head of a bundle).
2643     bool isSchedulingEntity() const { return FirstInBundle == this; }
2644 
2645     /// Returns true if it represents an instruction bundle and not only a
2646     /// single instruction.
2647     bool isPartOfBundle() const {
2648       return NextInBundle != nullptr || FirstInBundle != this || TE;
2649     }
2650 
2651     /// Returns true if it is ready for scheduling, i.e. it has no more
2652     /// unscheduled depending instructions/bundles.
2653     bool isReady() const {
2654       assert(isSchedulingEntity() &&
2655              "can't consider non-scheduling entity for ready list");
2656       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2657     }
2658 
2659     /// Modifies the number of unscheduled dependencies for this instruction,
2660     /// and returns the number of remaining dependencies for the containing
2661     /// bundle.
2662     int incrementUnscheduledDeps(int Incr) {
2663       assert(hasValidDependencies() &&
2664              "increment of unscheduled deps would be meaningless");
2665       UnscheduledDeps += Incr;
2666       return FirstInBundle->unscheduledDepsInBundle();
2667     }
2668 
2669     /// Sets the number of unscheduled dependencies to the number of
2670     /// dependencies.
2671     void resetUnscheduledDeps() {
2672       UnscheduledDeps = Dependencies;
2673     }
2674 
2675     /// Clears all dependency information.
2676     void clearDependencies() {
2677       Dependencies = InvalidDeps;
2678       resetUnscheduledDeps();
2679       MemoryDependencies.clear();
2680       ControlDependencies.clear();
2681     }
2682 
2683     int unscheduledDepsInBundle() const {
2684       assert(isSchedulingEntity() && "only meaningful on the bundle");
2685       int Sum = 0;
2686       for (const ScheduleData *BundleMember = this; BundleMember;
2687            BundleMember = BundleMember->NextInBundle) {
2688         if (BundleMember->UnscheduledDeps == InvalidDeps)
2689           return InvalidDeps;
2690         Sum += BundleMember->UnscheduledDeps;
2691       }
2692       return Sum;
2693     }
2694 
2695     void dump(raw_ostream &os) const {
2696       if (!isSchedulingEntity()) {
2697         os << "/ " << *Inst;
2698       } else if (NextInBundle) {
2699         os << '[' << *Inst;
2700         ScheduleData *SD = NextInBundle;
2701         while (SD) {
2702           os << ';' << *SD->Inst;
2703           SD = SD->NextInBundle;
2704         }
2705         os << ']';
2706       } else {
2707         os << *Inst;
2708       }
2709     }
2710 
2711     Instruction *Inst = nullptr;
2712 
2713     /// Opcode of the current instruction in the schedule data.
2714     Value *OpValue = nullptr;
2715 
2716     /// The TreeEntry that this instruction corresponds to.
2717     TreeEntry *TE = nullptr;
2718 
2719     /// Points to the head in an instruction bundle (and always to this for
2720     /// single instructions).
2721     ScheduleData *FirstInBundle = nullptr;
2722 
2723     /// Single linked list of all instructions in a bundle. Null if it is a
2724     /// single instruction.
2725     ScheduleData *NextInBundle = nullptr;
2726 
2727     /// Single linked list of all memory instructions (e.g. load, store, call)
2728     /// in the block - until the end of the scheduling region.
2729     ScheduleData *NextLoadStore = nullptr;
2730 
2731     /// The dependent memory instructions.
2732     /// This list is derived on demand in calculateDependencies().
2733     SmallVector<ScheduleData *, 4> MemoryDependencies;
2734 
2735     /// List of instructions which this instruction could be control dependent
2736     /// on.  Allowing such nodes to be scheduled below this one could introduce
2737     /// a runtime fault which didn't exist in the original program.
2738     /// ex: this is a load or udiv following a readonly call which inf loops
2739     SmallVector<ScheduleData *, 4> ControlDependencies;
2740 
2741     /// This ScheduleData is in the current scheduling region if this matches
2742     /// the current SchedulingRegionID of BlockScheduling.
2743     int SchedulingRegionID = 0;
2744 
2745     /// Used for getting a "good" final ordering of instructions.
2746     int SchedulingPriority = 0;
2747 
2748     /// The number of dependencies. Constitutes of the number of users of the
2749     /// instruction plus the number of dependent memory instructions (if any).
2750     /// This value is calculated on demand.
2751     /// If InvalidDeps, the number of dependencies is not calculated yet.
2752     int Dependencies = InvalidDeps;
2753 
2754     /// The number of dependencies minus the number of dependencies of scheduled
2755     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2756     /// for scheduling.
2757     /// Note that this is negative as long as Dependencies is not calculated.
2758     int UnscheduledDeps = InvalidDeps;
2759 
2760     /// True if this instruction is scheduled (or considered as scheduled in the
2761     /// dry-run).
2762     bool IsScheduled = false;
2763   };
2764 
2765 #ifndef NDEBUG
2766   friend inline raw_ostream &operator<<(raw_ostream &os,
2767                                         const BoUpSLP::ScheduleData &SD) {
2768     SD.dump(os);
2769     return os;
2770   }
2771 #endif
2772 
2773   friend struct GraphTraits<BoUpSLP *>;
2774   friend struct DOTGraphTraits<BoUpSLP *>;
2775 
2776   /// Contains all scheduling data for a basic block.
2777   /// It does not schedules instructions, which are not memory read/write
2778   /// instructions and their operands are either constants, or arguments, or
2779   /// phis, or instructions from others blocks, or their users are phis or from
2780   /// the other blocks. The resulting vector instructions can be placed at the
2781   /// beginning of the basic block without scheduling (if operands does not need
2782   /// to be scheduled) or at the end of the block (if users are outside of the
2783   /// block). It allows to save some compile time and memory used by the
2784   /// compiler.
2785   /// ScheduleData is assigned for each instruction in between the boundaries of
2786   /// the tree entry, even for those, which are not part of the graph. It is
2787   /// required to correctly follow the dependencies between the instructions and
2788   /// their correct scheduling. The ScheduleData is not allocated for the
2789   /// instructions, which do not require scheduling, like phis, nodes with
2790   /// extractelements/insertelements only or nodes with instructions, with
2791   /// uses/operands outside of the block.
2792   struct BlockScheduling {
2793     BlockScheduling(BasicBlock *BB)
2794         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2795 
2796     void clear() {
2797       ReadyInsts.clear();
2798       ScheduleStart = nullptr;
2799       ScheduleEnd = nullptr;
2800       FirstLoadStoreInRegion = nullptr;
2801       LastLoadStoreInRegion = nullptr;
2802       RegionHasStackSave = false;
2803 
2804       // Reduce the maximum schedule region size by the size of the
2805       // previous scheduling run.
2806       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2807       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2808         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2809       ScheduleRegionSize = 0;
2810 
2811       // Make a new scheduling region, i.e. all existing ScheduleData is not
2812       // in the new region yet.
2813       ++SchedulingRegionID;
2814     }
2815 
2816     ScheduleData *getScheduleData(Instruction *I) {
2817       if (BB != I->getParent())
2818         // Avoid lookup if can't possibly be in map.
2819         return nullptr;
2820       ScheduleData *SD = ScheduleDataMap.lookup(I);
2821       if (SD && isInSchedulingRegion(SD))
2822         return SD;
2823       return nullptr;
2824     }
2825 
2826     ScheduleData *getScheduleData(Value *V) {
2827       if (auto *I = dyn_cast<Instruction>(V))
2828         return getScheduleData(I);
2829       return nullptr;
2830     }
2831 
2832     ScheduleData *getScheduleData(Value *V, Value *Key) {
2833       if (V == Key)
2834         return getScheduleData(V);
2835       auto I = ExtraScheduleDataMap.find(V);
2836       if (I != ExtraScheduleDataMap.end()) {
2837         ScheduleData *SD = I->second.lookup(Key);
2838         if (SD && isInSchedulingRegion(SD))
2839           return SD;
2840       }
2841       return nullptr;
2842     }
2843 
2844     bool isInSchedulingRegion(ScheduleData *SD) const {
2845       return SD->SchedulingRegionID == SchedulingRegionID;
2846     }
2847 
2848     /// Marks an instruction as scheduled and puts all dependent ready
2849     /// instructions into the ready-list.
2850     template <typename ReadyListType>
2851     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2852       SD->IsScheduled = true;
2853       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2854 
2855       for (ScheduleData *BundleMember = SD; BundleMember;
2856            BundleMember = BundleMember->NextInBundle) {
2857         if (BundleMember->Inst != BundleMember->OpValue)
2858           continue;
2859 
2860         // Handle the def-use chain dependencies.
2861 
2862         // Decrement the unscheduled counter and insert to ready list if ready.
2863         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2864           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2865             if (OpDef && OpDef->hasValidDependencies() &&
2866                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2867               // There are no more unscheduled dependencies after
2868               // decrementing, so we can put the dependent instruction
2869               // into the ready list.
2870               ScheduleData *DepBundle = OpDef->FirstInBundle;
2871               assert(!DepBundle->IsScheduled &&
2872                      "already scheduled bundle gets ready");
2873               ReadyList.insert(DepBundle);
2874               LLVM_DEBUG(dbgs()
2875                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2876             }
2877           });
2878         };
2879 
2880         // If BundleMember is a vector bundle, its operands may have been
2881         // reordered during buildTree(). We therefore need to get its operands
2882         // through the TreeEntry.
2883         if (TreeEntry *TE = BundleMember->TE) {
2884           // Need to search for the lane since the tree entry can be reordered.
2885           int Lane = std::distance(TE->Scalars.begin(),
2886                                    find(TE->Scalars, BundleMember->Inst));
2887           assert(Lane >= 0 && "Lane not set");
2888 
2889           // Since vectorization tree is being built recursively this assertion
2890           // ensures that the tree entry has all operands set before reaching
2891           // this code. Couple of exceptions known at the moment are extracts
2892           // where their second (immediate) operand is not added. Since
2893           // immediates do not affect scheduler behavior this is considered
2894           // okay.
2895           auto *In = BundleMember->Inst;
2896           assert(In &&
2897                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2898                   In->getNumOperands() == TE->getNumOperands()) &&
2899                  "Missed TreeEntry operands?");
2900           (void)In; // fake use to avoid build failure when assertions disabled
2901 
2902           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2903                OpIdx != NumOperands; ++OpIdx)
2904             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2905               DecrUnsched(I);
2906         } else {
2907           // If BundleMember is a stand-alone instruction, no operand reordering
2908           // has taken place, so we directly access its operands.
2909           for (Use &U : BundleMember->Inst->operands())
2910             if (auto *I = dyn_cast<Instruction>(U.get()))
2911               DecrUnsched(I);
2912         }
2913         // Handle the memory dependencies.
2914         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2915           if (MemoryDepSD->hasValidDependencies() &&
2916               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2917             // There are no more unscheduled dependencies after decrementing,
2918             // so we can put the dependent instruction into the ready list.
2919             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2920             assert(!DepBundle->IsScheduled &&
2921                    "already scheduled bundle gets ready");
2922             ReadyList.insert(DepBundle);
2923             LLVM_DEBUG(dbgs()
2924                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2925           }
2926         }
2927         // Handle the control dependencies.
2928         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2929           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2930             // There are no more unscheduled dependencies after decrementing,
2931             // so we can put the dependent instruction into the ready list.
2932             ScheduleData *DepBundle = DepSD->FirstInBundle;
2933             assert(!DepBundle->IsScheduled &&
2934                    "already scheduled bundle gets ready");
2935             ReadyList.insert(DepBundle);
2936             LLVM_DEBUG(dbgs()
2937                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2938           }
2939         }
2940 
2941       }
2942     }
2943 
2944     /// Verify basic self consistency properties of the data structure.
2945     void verify() {
2946       if (!ScheduleStart)
2947         return;
2948 
2949       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2950              ScheduleStart->comesBefore(ScheduleEnd) &&
2951              "Not a valid scheduling region?");
2952 
2953       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2954         auto *SD = getScheduleData(I);
2955         if (!SD)
2956           continue;
2957         assert(isInSchedulingRegion(SD) &&
2958                "primary schedule data not in window?");
2959         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2960                "entire bundle in window!");
2961         (void)SD;
2962         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2963       }
2964 
2965       for (auto *SD : ReadyInsts) {
2966         assert(SD->isSchedulingEntity() && SD->isReady() &&
2967                "item in ready list not ready?");
2968         (void)SD;
2969       }
2970     }
2971 
2972     void doForAllOpcodes(Value *V,
2973                          function_ref<void(ScheduleData *SD)> Action) {
2974       if (ScheduleData *SD = getScheduleData(V))
2975         Action(SD);
2976       auto I = ExtraScheduleDataMap.find(V);
2977       if (I != ExtraScheduleDataMap.end())
2978         for (auto &P : I->second)
2979           if (isInSchedulingRegion(P.second))
2980             Action(P.second);
2981     }
2982 
2983     /// Put all instructions into the ReadyList which are ready for scheduling.
2984     template <typename ReadyListType>
2985     void initialFillReadyList(ReadyListType &ReadyList) {
2986       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2987         doForAllOpcodes(I, [&](ScheduleData *SD) {
2988           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
2989               SD->isReady()) {
2990             ReadyList.insert(SD);
2991             LLVM_DEBUG(dbgs()
2992                        << "SLP:    initially in ready list: " << *SD << "\n");
2993           }
2994         });
2995       }
2996     }
2997 
2998     /// Build a bundle from the ScheduleData nodes corresponding to the
2999     /// scalar instruction for each lane.
3000     ScheduleData *buildBundle(ArrayRef<Value *> VL);
3001 
3002     /// Checks if a bundle of instructions can be scheduled, i.e. has no
3003     /// cyclic dependencies. This is only a dry-run, no instructions are
3004     /// actually moved at this stage.
3005     /// \returns the scheduling bundle. The returned Optional value is non-None
3006     /// if \p VL is allowed to be scheduled.
3007     Optional<ScheduleData *>
3008     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3009                       const InstructionsState &S);
3010 
3011     /// Un-bundles a group of instructions.
3012     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3013 
3014     /// Allocates schedule data chunk.
3015     ScheduleData *allocateScheduleDataChunks();
3016 
3017     /// Extends the scheduling region so that V is inside the region.
3018     /// \returns true if the region size is within the limit.
3019     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3020 
3021     /// Initialize the ScheduleData structures for new instructions in the
3022     /// scheduling region.
3023     void initScheduleData(Instruction *FromI, Instruction *ToI,
3024                           ScheduleData *PrevLoadStore,
3025                           ScheduleData *NextLoadStore);
3026 
3027     /// Updates the dependency information of a bundle and of all instructions/
3028     /// bundles which depend on the original bundle.
3029     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3030                                BoUpSLP *SLP);
3031 
3032     /// Sets all instruction in the scheduling region to un-scheduled.
3033     void resetSchedule();
3034 
3035     BasicBlock *BB;
3036 
3037     /// Simple memory allocation for ScheduleData.
3038     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3039 
3040     /// The size of a ScheduleData array in ScheduleDataChunks.
3041     int ChunkSize;
3042 
3043     /// The allocator position in the current chunk, which is the last entry
3044     /// of ScheduleDataChunks.
3045     int ChunkPos;
3046 
3047     /// Attaches ScheduleData to Instruction.
3048     /// Note that the mapping survives during all vectorization iterations, i.e.
3049     /// ScheduleData structures are recycled.
3050     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3051 
3052     /// Attaches ScheduleData to Instruction with the leading key.
3053     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3054         ExtraScheduleDataMap;
3055 
3056     /// The ready-list for scheduling (only used for the dry-run).
3057     SetVector<ScheduleData *> ReadyInsts;
3058 
3059     /// The first instruction of the scheduling region.
3060     Instruction *ScheduleStart = nullptr;
3061 
3062     /// The first instruction _after_ the scheduling region.
3063     Instruction *ScheduleEnd = nullptr;
3064 
3065     /// The first memory accessing instruction in the scheduling region
3066     /// (can be null).
3067     ScheduleData *FirstLoadStoreInRegion = nullptr;
3068 
3069     /// The last memory accessing instruction in the scheduling region
3070     /// (can be null).
3071     ScheduleData *LastLoadStoreInRegion = nullptr;
3072 
3073     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3074     /// region?  Used to optimize the dependence calculation for the
3075     /// common case where there isn't.
3076     bool RegionHasStackSave = false;
3077 
3078     /// The current size of the scheduling region.
3079     int ScheduleRegionSize = 0;
3080 
3081     /// The maximum size allowed for the scheduling region.
3082     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3083 
3084     /// The ID of the scheduling region. For a new vectorization iteration this
3085     /// is incremented which "removes" all ScheduleData from the region.
3086     /// Make sure that the initial SchedulingRegionID is greater than the
3087     /// initial SchedulingRegionID in ScheduleData (which is 0).
3088     int SchedulingRegionID = 1;
3089   };
3090 
3091   /// Attaches the BlockScheduling structures to basic blocks.
3092   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3093 
3094   /// Performs the "real" scheduling. Done before vectorization is actually
3095   /// performed in a basic block.
3096   void scheduleBlock(BlockScheduling *BS);
3097 
3098   /// List of users to ignore during scheduling and that don't need extracting.
3099   ArrayRef<Value *> UserIgnoreList;
3100 
3101   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3102   /// sorted SmallVectors of unsigned.
3103   struct OrdersTypeDenseMapInfo {
3104     static OrdersType getEmptyKey() {
3105       OrdersType V;
3106       V.push_back(~1U);
3107       return V;
3108     }
3109 
3110     static OrdersType getTombstoneKey() {
3111       OrdersType V;
3112       V.push_back(~2U);
3113       return V;
3114     }
3115 
3116     static unsigned getHashValue(const OrdersType &V) {
3117       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3118     }
3119 
3120     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3121       return LHS == RHS;
3122     }
3123   };
3124 
3125   // Analysis and block reference.
3126   Function *F;
3127   ScalarEvolution *SE;
3128   TargetTransformInfo *TTI;
3129   TargetLibraryInfo *TLI;
3130   LoopInfo *LI;
3131   DominatorTree *DT;
3132   AssumptionCache *AC;
3133   DemandedBits *DB;
3134   const DataLayout *DL;
3135   OptimizationRemarkEmitter *ORE;
3136 
3137   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3138   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3139 
3140   /// Instruction builder to construct the vectorized tree.
3141   IRBuilder<> Builder;
3142 
3143   /// A map of scalar integer values to the smallest bit width with which they
3144   /// can legally be represented. The values map to (width, signed) pairs,
3145   /// where "width" indicates the minimum bit width and "signed" is True if the
3146   /// value must be signed-extended, rather than zero-extended, back to its
3147   /// original width.
3148   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3149 };
3150 
3151 } // end namespace slpvectorizer
3152 
3153 template <> struct GraphTraits<BoUpSLP *> {
3154   using TreeEntry = BoUpSLP::TreeEntry;
3155 
3156   /// NodeRef has to be a pointer per the GraphWriter.
3157   using NodeRef = TreeEntry *;
3158 
3159   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3160 
3161   /// Add the VectorizableTree to the index iterator to be able to return
3162   /// TreeEntry pointers.
3163   struct ChildIteratorType
3164       : public iterator_adaptor_base<
3165             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3166     ContainerTy &VectorizableTree;
3167 
3168     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3169                       ContainerTy &VT)
3170         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3171 
3172     NodeRef operator*() { return I->UserTE; }
3173   };
3174 
3175   static NodeRef getEntryNode(BoUpSLP &R) {
3176     return R.VectorizableTree[0].get();
3177   }
3178 
3179   static ChildIteratorType child_begin(NodeRef N) {
3180     return {N->UserTreeIndices.begin(), N->Container};
3181   }
3182 
3183   static ChildIteratorType child_end(NodeRef N) {
3184     return {N->UserTreeIndices.end(), N->Container};
3185   }
3186 
3187   /// For the node iterator we just need to turn the TreeEntry iterator into a
3188   /// TreeEntry* iterator so that it dereferences to NodeRef.
3189   class nodes_iterator {
3190     using ItTy = ContainerTy::iterator;
3191     ItTy It;
3192 
3193   public:
3194     nodes_iterator(const ItTy &It2) : It(It2) {}
3195     NodeRef operator*() { return It->get(); }
3196     nodes_iterator operator++() {
3197       ++It;
3198       return *this;
3199     }
3200     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3201   };
3202 
3203   static nodes_iterator nodes_begin(BoUpSLP *R) {
3204     return nodes_iterator(R->VectorizableTree.begin());
3205   }
3206 
3207   static nodes_iterator nodes_end(BoUpSLP *R) {
3208     return nodes_iterator(R->VectorizableTree.end());
3209   }
3210 
3211   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3212 };
3213 
3214 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3215   using TreeEntry = BoUpSLP::TreeEntry;
3216 
3217   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3218 
3219   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3220     std::string Str;
3221     raw_string_ostream OS(Str);
3222     if (isSplat(Entry->Scalars))
3223       OS << "<splat> ";
3224     for (auto V : Entry->Scalars) {
3225       OS << *V;
3226       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3227             return EU.Scalar == V;
3228           }))
3229         OS << " <extract>";
3230       OS << "\n";
3231     }
3232     return Str;
3233   }
3234 
3235   static std::string getNodeAttributes(const TreeEntry *Entry,
3236                                        const BoUpSLP *) {
3237     if (Entry->State == TreeEntry::NeedToGather)
3238       return "color=red";
3239     return "";
3240   }
3241 };
3242 
3243 } // end namespace llvm
3244 
3245 BoUpSLP::~BoUpSLP() {
3246   SmallVector<WeakTrackingVH> DeadInsts;
3247   for (auto *I : DeletedInstructions) {
3248     for (Use &U : I->operands()) {
3249       auto *Op = dyn_cast<Instruction>(U.get());
3250       if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3251           wouldInstructionBeTriviallyDead(Op, TLI))
3252         DeadInsts.emplace_back(Op);
3253     }
3254     I->dropAllReferences();
3255   }
3256   for (auto *I : DeletedInstructions) {
3257     assert(I->use_empty() &&
3258            "trying to erase instruction with users.");
3259     I->eraseFromParent();
3260   }
3261 
3262   // Cleanup any dead scalar code feeding the vectorized instructions
3263   RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
3264 
3265 #ifdef EXPENSIVE_CHECKS
3266   // If we could guarantee that this call is not extremely slow, we could
3267   // remove the ifdef limitation (see PR47712).
3268   assert(!verifyFunction(*F, &dbgs()));
3269 #endif
3270 }
3271 
3272 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3273 /// contains original mask for the scalars reused in the node. Procedure
3274 /// transform this mask in accordance with the given \p Mask.
3275 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3276   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3277          "Expected non-empty mask.");
3278   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3279   Prev.swap(Reuses);
3280   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3281     if (Mask[I] != UndefMaskElem)
3282       Reuses[Mask[I]] = Prev[I];
3283 }
3284 
3285 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3286 /// the original order of the scalars. Procedure transforms the provided order
3287 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3288 /// identity order, \p Order is cleared.
3289 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3290   assert(!Mask.empty() && "Expected non-empty mask.");
3291   SmallVector<int> MaskOrder;
3292   if (Order.empty()) {
3293     MaskOrder.resize(Mask.size());
3294     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3295   } else {
3296     inversePermutation(Order, MaskOrder);
3297   }
3298   reorderReuses(MaskOrder, Mask);
3299   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3300     Order.clear();
3301     return;
3302   }
3303   Order.assign(Mask.size(), Mask.size());
3304   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3305     if (MaskOrder[I] != UndefMaskElem)
3306       Order[MaskOrder[I]] = I;
3307   fixupOrderingIndices(Order);
3308 }
3309 
3310 Optional<BoUpSLP::OrdersType>
3311 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3312   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3313   unsigned NumScalars = TE.Scalars.size();
3314   OrdersType CurrentOrder(NumScalars, NumScalars);
3315   SmallVector<int> Positions;
3316   SmallBitVector UsedPositions(NumScalars);
3317   const TreeEntry *STE = nullptr;
3318   // Try to find all gathered scalars that are gets vectorized in other
3319   // vectorize node. Here we can have only one single tree vector node to
3320   // correctly identify order of the gathered scalars.
3321   for (unsigned I = 0; I < NumScalars; ++I) {
3322     Value *V = TE.Scalars[I];
3323     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3324       continue;
3325     if (const auto *LocalSTE = getTreeEntry(V)) {
3326       if (!STE)
3327         STE = LocalSTE;
3328       else if (STE != LocalSTE)
3329         // Take the order only from the single vector node.
3330         return None;
3331       unsigned Lane =
3332           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3333       if (Lane >= NumScalars)
3334         return None;
3335       if (CurrentOrder[Lane] != NumScalars) {
3336         if (Lane != I)
3337           continue;
3338         UsedPositions.reset(CurrentOrder[Lane]);
3339       }
3340       // The partial identity (where only some elements of the gather node are
3341       // in the identity order) is good.
3342       CurrentOrder[Lane] = I;
3343       UsedPositions.set(I);
3344     }
3345   }
3346   // Need to keep the order if we have a vector entry and at least 2 scalars or
3347   // the vectorized entry has just 2 scalars.
3348   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3349     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3350       for (unsigned I = 0; I < NumScalars; ++I)
3351         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3352           return false;
3353       return true;
3354     };
3355     if (IsIdentityOrder(CurrentOrder)) {
3356       CurrentOrder.clear();
3357       return CurrentOrder;
3358     }
3359     auto *It = CurrentOrder.begin();
3360     for (unsigned I = 0; I < NumScalars;) {
3361       if (UsedPositions.test(I)) {
3362         ++I;
3363         continue;
3364       }
3365       if (*It == NumScalars) {
3366         *It = I;
3367         ++I;
3368       }
3369       ++It;
3370     }
3371     return CurrentOrder;
3372   }
3373   return None;
3374 }
3375 
3376 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3377                                                          bool TopToBottom) {
3378   // No need to reorder if need to shuffle reuses, still need to shuffle the
3379   // node.
3380   if (!TE.ReuseShuffleIndices.empty())
3381     return None;
3382   if (TE.State == TreeEntry::Vectorize &&
3383       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3384        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3385       !TE.isAltShuffle())
3386     return TE.ReorderIndices;
3387   if (TE.State == TreeEntry::NeedToGather) {
3388     // TODO: add analysis of other gather nodes with extractelement
3389     // instructions and other values/instructions, not only undefs.
3390     if (((TE.getOpcode() == Instruction::ExtractElement &&
3391           !TE.isAltShuffle()) ||
3392          (all_of(TE.Scalars,
3393                  [](Value *V) {
3394                    return isa<UndefValue, ExtractElementInst>(V);
3395                  }) &&
3396           any_of(TE.Scalars,
3397                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3398         all_of(TE.Scalars,
3399                [](Value *V) {
3400                  auto *EE = dyn_cast<ExtractElementInst>(V);
3401                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3402                }) &&
3403         allSameType(TE.Scalars)) {
3404       // Check that gather of extractelements can be represented as
3405       // just a shuffle of a single vector.
3406       OrdersType CurrentOrder;
3407       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3408       if (Reuse || !CurrentOrder.empty()) {
3409         if (!CurrentOrder.empty())
3410           fixupOrderingIndices(CurrentOrder);
3411         return CurrentOrder;
3412       }
3413     }
3414     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3415       return CurrentOrder;
3416   }
3417   return None;
3418 }
3419 
3420 void BoUpSLP::reorderTopToBottom() {
3421   // Maps VF to the graph nodes.
3422   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3423   // ExtractElement gather nodes which can be vectorized and need to handle
3424   // their ordering.
3425   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3426   // Find all reorderable nodes with the given VF.
3427   // Currently the are vectorized stores,loads,extracts + some gathering of
3428   // extracts.
3429   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3430                                  const std::unique_ptr<TreeEntry> &TE) {
3431     if (Optional<OrdersType> CurrentOrder =
3432             getReorderingData(*TE, /*TopToBottom=*/true)) {
3433       // Do not include ordering for nodes used in the alt opcode vectorization,
3434       // better to reorder them during bottom-to-top stage. If follow the order
3435       // here, it causes reordering of the whole graph though actually it is
3436       // profitable just to reorder the subgraph that starts from the alternate
3437       // opcode vectorization node. Such nodes already end-up with the shuffle
3438       // instruction and it is just enough to change this shuffle rather than
3439       // rotate the scalars for the whole graph.
3440       unsigned Cnt = 0;
3441       const TreeEntry *UserTE = TE.get();
3442       while (UserTE && Cnt < RecursionMaxDepth) {
3443         if (UserTE->UserTreeIndices.size() != 1)
3444           break;
3445         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3446               return EI.UserTE->State == TreeEntry::Vectorize &&
3447                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3448             }))
3449           return;
3450         if (UserTE->UserTreeIndices.empty())
3451           UserTE = nullptr;
3452         else
3453           UserTE = UserTE->UserTreeIndices.back().UserTE;
3454         ++Cnt;
3455       }
3456       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3457       if (TE->State != TreeEntry::Vectorize)
3458         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3459     }
3460   });
3461 
3462   // Reorder the graph nodes according to their vectorization factor.
3463   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3464        VF /= 2) {
3465     auto It = VFToOrderedEntries.find(VF);
3466     if (It == VFToOrderedEntries.end())
3467       continue;
3468     // Try to find the most profitable order. We just are looking for the most
3469     // used order and reorder scalar elements in the nodes according to this
3470     // mostly used order.
3471     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3472     // All operands are reordered and used only in this node - propagate the
3473     // most used order to the user node.
3474     MapVector<OrdersType, unsigned,
3475               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3476         OrdersUses;
3477     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3478     for (const TreeEntry *OpTE : OrderedEntries) {
3479       // No need to reorder this nodes, still need to extend and to use shuffle,
3480       // just need to merge reordering shuffle and the reuse shuffle.
3481       if (!OpTE->ReuseShuffleIndices.empty())
3482         continue;
3483       // Count number of orders uses.
3484       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3485         if (OpTE->State == TreeEntry::NeedToGather)
3486           return GathersToOrders.find(OpTE)->second;
3487         return OpTE->ReorderIndices;
3488       }();
3489       // Stores actually store the mask, not the order, need to invert.
3490       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3491           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3492         SmallVector<int> Mask;
3493         inversePermutation(Order, Mask);
3494         unsigned E = Order.size();
3495         OrdersType CurrentOrder(E, E);
3496         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3497           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3498         });
3499         fixupOrderingIndices(CurrentOrder);
3500         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3501       } else {
3502         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3503       }
3504     }
3505     // Set order of the user node.
3506     if (OrdersUses.empty())
3507       continue;
3508     // Choose the most used order.
3509     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3510     unsigned Cnt = OrdersUses.front().second;
3511     for (const auto &Pair : drop_begin(OrdersUses)) {
3512       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3513         BestOrder = Pair.first;
3514         Cnt = Pair.second;
3515       }
3516     }
3517     // Set order of the user node.
3518     if (BestOrder.empty())
3519       continue;
3520     SmallVector<int> Mask;
3521     inversePermutation(BestOrder, Mask);
3522     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3523     unsigned E = BestOrder.size();
3524     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3525       return I < E ? static_cast<int>(I) : UndefMaskElem;
3526     });
3527     // Do an actual reordering, if profitable.
3528     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3529       // Just do the reordering for the nodes with the given VF.
3530       if (TE->Scalars.size() != VF) {
3531         if (TE->ReuseShuffleIndices.size() == VF) {
3532           // Need to reorder the reuses masks of the operands with smaller VF to
3533           // be able to find the match between the graph nodes and scalar
3534           // operands of the given node during vectorization/cost estimation.
3535           assert(all_of(TE->UserTreeIndices,
3536                         [VF, &TE](const EdgeInfo &EI) {
3537                           return EI.UserTE->Scalars.size() == VF ||
3538                                  EI.UserTE->Scalars.size() ==
3539                                      TE->Scalars.size();
3540                         }) &&
3541                  "All users must be of VF size.");
3542           // Update ordering of the operands with the smaller VF than the given
3543           // one.
3544           reorderReuses(TE->ReuseShuffleIndices, Mask);
3545         }
3546         continue;
3547       }
3548       if (TE->State == TreeEntry::Vectorize &&
3549           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3550               InsertElementInst>(TE->getMainOp()) &&
3551           !TE->isAltShuffle()) {
3552         // Build correct orders for extract{element,value}, loads and
3553         // stores.
3554         reorderOrder(TE->ReorderIndices, Mask);
3555         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3556           TE->reorderOperands(Mask);
3557       } else {
3558         // Reorder the node and its operands.
3559         TE->reorderOperands(Mask);
3560         assert(TE->ReorderIndices.empty() &&
3561                "Expected empty reorder sequence.");
3562         reorderScalars(TE->Scalars, Mask);
3563       }
3564       if (!TE->ReuseShuffleIndices.empty()) {
3565         // Apply reversed order to keep the original ordering of the reused
3566         // elements to avoid extra reorder indices shuffling.
3567         OrdersType CurrentOrder;
3568         reorderOrder(CurrentOrder, MaskOrder);
3569         SmallVector<int> NewReuses;
3570         inversePermutation(CurrentOrder, NewReuses);
3571         addMask(NewReuses, TE->ReuseShuffleIndices);
3572         TE->ReuseShuffleIndices.swap(NewReuses);
3573       }
3574     }
3575   }
3576 }
3577 
3578 bool BoUpSLP::canReorderOperands(
3579     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3580     ArrayRef<TreeEntry *> ReorderableGathers,
3581     SmallVectorImpl<TreeEntry *> &GatherOps) {
3582   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3583     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3584           return OpData.first == I &&
3585                  OpData.second->State == TreeEntry::Vectorize;
3586         }))
3587       continue;
3588     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3589       // Do not reorder if operand node is used by many user nodes.
3590       if (any_of(TE->UserTreeIndices,
3591                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3592         return false;
3593       // Add the node to the list of the ordered nodes with the identity
3594       // order.
3595       Edges.emplace_back(I, TE);
3596       continue;
3597     }
3598     ArrayRef<Value *> VL = UserTE->getOperand(I);
3599     TreeEntry *Gather = nullptr;
3600     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3601           assert(TE->State != TreeEntry::Vectorize &&
3602                  "Only non-vectorized nodes are expected.");
3603           if (TE->isSame(VL)) {
3604             Gather = TE;
3605             return true;
3606           }
3607           return false;
3608         }) > 1)
3609       return false;
3610     if (Gather)
3611       GatherOps.push_back(Gather);
3612   }
3613   return true;
3614 }
3615 
3616 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3617   SetVector<TreeEntry *> OrderedEntries;
3618   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3619   // Find all reorderable leaf nodes with the given VF.
3620   // Currently the are vectorized loads,extracts without alternate operands +
3621   // some gathering of extracts.
3622   SmallVector<TreeEntry *> NonVectorized;
3623   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3624                               &NonVectorized](
3625                                  const std::unique_ptr<TreeEntry> &TE) {
3626     if (TE->State != TreeEntry::Vectorize)
3627       NonVectorized.push_back(TE.get());
3628     if (Optional<OrdersType> CurrentOrder =
3629             getReorderingData(*TE, /*TopToBottom=*/false)) {
3630       OrderedEntries.insert(TE.get());
3631       if (TE->State != TreeEntry::Vectorize)
3632         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3633     }
3634   });
3635 
3636   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3637   // I.e., if the node has operands, that are reordered, try to make at least
3638   // one operand order in the natural order and reorder others + reorder the
3639   // user node itself.
3640   SmallPtrSet<const TreeEntry *, 4> Visited;
3641   while (!OrderedEntries.empty()) {
3642     // 1. Filter out only reordered nodes.
3643     // 2. If the entry has multiple uses - skip it and jump to the next node.
3644     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3645     SmallVector<TreeEntry *> Filtered;
3646     for (TreeEntry *TE : OrderedEntries) {
3647       if (!(TE->State == TreeEntry::Vectorize ||
3648             (TE->State == TreeEntry::NeedToGather &&
3649              GathersToOrders.count(TE))) ||
3650           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3651           !all_of(drop_begin(TE->UserTreeIndices),
3652                   [TE](const EdgeInfo &EI) {
3653                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3654                   }) ||
3655           !Visited.insert(TE).second) {
3656         Filtered.push_back(TE);
3657         continue;
3658       }
3659       // Build a map between user nodes and their operands order to speedup
3660       // search. The graph currently does not provide this dependency directly.
3661       for (EdgeInfo &EI : TE->UserTreeIndices) {
3662         TreeEntry *UserTE = EI.UserTE;
3663         auto It = Users.find(UserTE);
3664         if (It == Users.end())
3665           It = Users.insert({UserTE, {}}).first;
3666         It->second.emplace_back(EI.EdgeIdx, TE);
3667       }
3668     }
3669     // Erase filtered entries.
3670     for_each(Filtered,
3671              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3672     for (auto &Data : Users) {
3673       // Check that operands are used only in the User node.
3674       SmallVector<TreeEntry *> GatherOps;
3675       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3676                               GatherOps)) {
3677         for_each(Data.second,
3678                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3679                    OrderedEntries.remove(Op.second);
3680                  });
3681         continue;
3682       }
3683       // All operands are reordered and used only in this node - propagate the
3684       // most used order to the user node.
3685       MapVector<OrdersType, unsigned,
3686                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3687           OrdersUses;
3688       // Do the analysis for each tree entry only once, otherwise the order of
3689       // the same node my be considered several times, though might be not
3690       // profitable.
3691       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3692       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3693       for (const auto &Op : Data.second) {
3694         TreeEntry *OpTE = Op.second;
3695         if (!VisitedOps.insert(OpTE).second)
3696           continue;
3697         if (!OpTE->ReuseShuffleIndices.empty() ||
3698             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3699           continue;
3700         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3701           if (OpTE->State == TreeEntry::NeedToGather)
3702             return GathersToOrders.find(OpTE)->second;
3703           return OpTE->ReorderIndices;
3704         }();
3705         unsigned NumOps = count_if(
3706             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3707               return P.second == OpTE;
3708             });
3709         // Stores actually store the mask, not the order, need to invert.
3710         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3711             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3712           SmallVector<int> Mask;
3713           inversePermutation(Order, Mask);
3714           unsigned E = Order.size();
3715           OrdersType CurrentOrder(E, E);
3716           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3717             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3718           });
3719           fixupOrderingIndices(CurrentOrder);
3720           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3721               NumOps;
3722         } else {
3723           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3724         }
3725         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3726         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3727                                             const TreeEntry *TE) {
3728           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3729               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3730               (IgnoreReorder && TE->Idx == 0))
3731             return true;
3732           if (TE->State == TreeEntry::NeedToGather) {
3733             auto It = GathersToOrders.find(TE);
3734             if (It != GathersToOrders.end())
3735               return !It->second.empty();
3736             return true;
3737           }
3738           return false;
3739         };
3740         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3741           TreeEntry *UserTE = EI.UserTE;
3742           if (!VisitedUsers.insert(UserTE).second)
3743             continue;
3744           // May reorder user node if it requires reordering, has reused
3745           // scalars, is an alternate op vectorize node or its op nodes require
3746           // reordering.
3747           if (AllowsReordering(UserTE))
3748             continue;
3749           // Check if users allow reordering.
3750           // Currently look up just 1 level of operands to avoid increase of
3751           // the compile time.
3752           // Profitable to reorder if definitely more operands allow
3753           // reordering rather than those with natural order.
3754           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3755           if (static_cast<unsigned>(count_if(
3756                   Ops, [UserTE, &AllowsReordering](
3757                            const std::pair<unsigned, TreeEntry *> &Op) {
3758                     return AllowsReordering(Op.second) &&
3759                            all_of(Op.second->UserTreeIndices,
3760                                   [UserTE](const EdgeInfo &EI) {
3761                                     return EI.UserTE == UserTE;
3762                                   });
3763                   })) <= Ops.size() / 2)
3764             ++Res.first->second;
3765         }
3766       }
3767       // If no orders - skip current nodes and jump to the next one, if any.
3768       if (OrdersUses.empty()) {
3769         for_each(Data.second,
3770                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3771                    OrderedEntries.remove(Op.second);
3772                  });
3773         continue;
3774       }
3775       // Choose the best order.
3776       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3777       unsigned Cnt = OrdersUses.front().second;
3778       for (const auto &Pair : drop_begin(OrdersUses)) {
3779         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3780           BestOrder = Pair.first;
3781           Cnt = Pair.second;
3782         }
3783       }
3784       // Set order of the user node (reordering of operands and user nodes).
3785       if (BestOrder.empty()) {
3786         for_each(Data.second,
3787                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3788                    OrderedEntries.remove(Op.second);
3789                  });
3790         continue;
3791       }
3792       // Erase operands from OrderedEntries list and adjust their orders.
3793       VisitedOps.clear();
3794       SmallVector<int> Mask;
3795       inversePermutation(BestOrder, Mask);
3796       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3797       unsigned E = BestOrder.size();
3798       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3799         return I < E ? static_cast<int>(I) : UndefMaskElem;
3800       });
3801       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3802         TreeEntry *TE = Op.second;
3803         OrderedEntries.remove(TE);
3804         if (!VisitedOps.insert(TE).second)
3805           continue;
3806         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3807           // Just reorder reuses indices.
3808           reorderReuses(TE->ReuseShuffleIndices, Mask);
3809           continue;
3810         }
3811         // Gathers are processed separately.
3812         if (TE->State != TreeEntry::Vectorize)
3813           continue;
3814         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3815                 TE->ReorderIndices.empty()) &&
3816                "Non-matching sizes of user/operand entries.");
3817         reorderOrder(TE->ReorderIndices, Mask);
3818       }
3819       // For gathers just need to reorder its scalars.
3820       for (TreeEntry *Gather : GatherOps) {
3821         assert(Gather->ReorderIndices.empty() &&
3822                "Unexpected reordering of gathers.");
3823         if (!Gather->ReuseShuffleIndices.empty()) {
3824           // Just reorder reuses indices.
3825           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3826           continue;
3827         }
3828         reorderScalars(Gather->Scalars, Mask);
3829         OrderedEntries.remove(Gather);
3830       }
3831       // Reorder operands of the user node and set the ordering for the user
3832       // node itself.
3833       if (Data.first->State != TreeEntry::Vectorize ||
3834           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3835               Data.first->getMainOp()) ||
3836           Data.first->isAltShuffle())
3837         Data.first->reorderOperands(Mask);
3838       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3839           Data.first->isAltShuffle()) {
3840         reorderScalars(Data.first->Scalars, Mask);
3841         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3842         if (Data.first->ReuseShuffleIndices.empty() &&
3843             !Data.first->ReorderIndices.empty() &&
3844             !Data.first->isAltShuffle()) {
3845           // Insert user node to the list to try to sink reordering deeper in
3846           // the graph.
3847           OrderedEntries.insert(Data.first);
3848         }
3849       } else {
3850         reorderOrder(Data.first->ReorderIndices, Mask);
3851       }
3852     }
3853   }
3854   // If the reordering is unnecessary, just remove the reorder.
3855   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3856       VectorizableTree.front()->ReuseShuffleIndices.empty())
3857     VectorizableTree.front()->ReorderIndices.clear();
3858 }
3859 
3860 void BoUpSLP::buildExternalUses(
3861     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3862   // Collect the values that we need to extract from the tree.
3863   for (auto &TEPtr : VectorizableTree) {
3864     TreeEntry *Entry = TEPtr.get();
3865 
3866     // No need to handle users of gathered values.
3867     if (Entry->State == TreeEntry::NeedToGather)
3868       continue;
3869 
3870     // For each lane:
3871     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3872       Value *Scalar = Entry->Scalars[Lane];
3873       int FoundLane = Entry->findLaneForValue(Scalar);
3874 
3875       // Check if the scalar is externally used as an extra arg.
3876       auto ExtI = ExternallyUsedValues.find(Scalar);
3877       if (ExtI != ExternallyUsedValues.end()) {
3878         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3879                           << Lane << " from " << *Scalar << ".\n");
3880         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3881       }
3882       for (User *U : Scalar->users()) {
3883         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3884 
3885         Instruction *UserInst = dyn_cast<Instruction>(U);
3886         if (!UserInst)
3887           continue;
3888 
3889         if (isDeleted(UserInst))
3890           continue;
3891 
3892         // Skip in-tree scalars that become vectors
3893         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3894           Value *UseScalar = UseEntry->Scalars[0];
3895           // Some in-tree scalars will remain as scalar in vectorized
3896           // instructions. If that is the case, the one in Lane 0 will
3897           // be used.
3898           if (UseScalar != U ||
3899               UseEntry->State == TreeEntry::ScatterVectorize ||
3900               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3901             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3902                               << ".\n");
3903             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3904             continue;
3905           }
3906         }
3907 
3908         // Ignore users in the user ignore list.
3909         if (is_contained(UserIgnoreList, UserInst))
3910           continue;
3911 
3912         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3913                           << Lane << " from " << *Scalar << ".\n");
3914         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3915       }
3916     }
3917   }
3918 }
3919 
3920 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3921                         ArrayRef<Value *> UserIgnoreLst) {
3922   deleteTree();
3923   UserIgnoreList = UserIgnoreLst;
3924   if (!allSameType(Roots))
3925     return;
3926   buildTree_rec(Roots, 0, EdgeInfo());
3927 }
3928 
3929 namespace {
3930 /// Tracks the state we can represent the loads in the given sequence.
3931 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3932 } // anonymous namespace
3933 
3934 /// Checks if the given array of loads can be represented as a vectorized,
3935 /// scatter or just simple gather.
3936 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3937                                     const TargetTransformInfo &TTI,
3938                                     const DataLayout &DL, ScalarEvolution &SE,
3939                                     SmallVectorImpl<unsigned> &Order,
3940                                     SmallVectorImpl<Value *> &PointerOps) {
3941   // Check that a vectorized load would load the same memory as a scalar
3942   // load. For example, we don't want to vectorize loads that are smaller
3943   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3944   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3945   // from such a struct, we read/write packed bits disagreeing with the
3946   // unvectorized version.
3947   Type *ScalarTy = VL0->getType();
3948 
3949   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3950     return LoadsState::Gather;
3951 
3952   // Make sure all loads in the bundle are simple - we can't vectorize
3953   // atomic or volatile loads.
3954   PointerOps.clear();
3955   PointerOps.resize(VL.size());
3956   auto *POIter = PointerOps.begin();
3957   for (Value *V : VL) {
3958     auto *L = cast<LoadInst>(V);
3959     if (!L->isSimple())
3960       return LoadsState::Gather;
3961     *POIter = L->getPointerOperand();
3962     ++POIter;
3963   }
3964 
3965   Order.clear();
3966   // Check the order of pointer operands.
3967   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3968     Value *Ptr0;
3969     Value *PtrN;
3970     if (Order.empty()) {
3971       Ptr0 = PointerOps.front();
3972       PtrN = PointerOps.back();
3973     } else {
3974       Ptr0 = PointerOps[Order.front()];
3975       PtrN = PointerOps[Order.back()];
3976     }
3977     Optional<int> Diff =
3978         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3979     // Check that the sorted loads are consecutive.
3980     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3981       return LoadsState::Vectorize;
3982     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3983     for (Value *V : VL)
3984       CommonAlignment =
3985           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3986     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3987                                 CommonAlignment))
3988       return LoadsState::ScatterVectorize;
3989   }
3990 
3991   return LoadsState::Gather;
3992 }
3993 
3994 /// \return true if the specified list of values has only one instruction that
3995 /// requires scheduling, false otherwise.
3996 #ifndef NDEBUG
3997 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3998   Value *NeedsScheduling = nullptr;
3999   for (Value *V : VL) {
4000     if (doesNotNeedToBeScheduled(V))
4001       continue;
4002     if (!NeedsScheduling) {
4003       NeedsScheduling = V;
4004       continue;
4005     }
4006     return false;
4007   }
4008   return NeedsScheduling;
4009 }
4010 #endif
4011 
4012 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4013                             const EdgeInfo &UserTreeIdx) {
4014   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4015 
4016   SmallVector<int> ReuseShuffleIndicies;
4017   SmallVector<Value *> UniqueValues;
4018   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4019                                 &UserTreeIdx,
4020                                 this](const InstructionsState &S) {
4021     // Check that every instruction appears once in this bundle.
4022     DenseMap<Value *, unsigned> UniquePositions;
4023     for (Value *V : VL) {
4024       if (isConstant(V)) {
4025         ReuseShuffleIndicies.emplace_back(
4026             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4027         UniqueValues.emplace_back(V);
4028         continue;
4029       }
4030       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4031       ReuseShuffleIndicies.emplace_back(Res.first->second);
4032       if (Res.second)
4033         UniqueValues.emplace_back(V);
4034     }
4035     size_t NumUniqueScalarValues = UniqueValues.size();
4036     if (NumUniqueScalarValues == VL.size()) {
4037       ReuseShuffleIndicies.clear();
4038     } else {
4039       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
4040       if (NumUniqueScalarValues <= 1 ||
4041           (UniquePositions.size() == 1 && all_of(UniqueValues,
4042                                                  [](Value *V) {
4043                                                    return isa<UndefValue>(V) ||
4044                                                           !isConstant(V);
4045                                                  })) ||
4046           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
4047         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
4048         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4049         return false;
4050       }
4051       VL = UniqueValues;
4052     }
4053     return true;
4054   };
4055 
4056   InstructionsState S = getSameOpcode(VL);
4057   if (Depth == RecursionMaxDepth) {
4058     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4059     if (TryToFindDuplicates(S))
4060       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4061                    ReuseShuffleIndicies);
4062     return;
4063   }
4064 
4065   // Don't handle scalable vectors
4066   if (S.getOpcode() == Instruction::ExtractElement &&
4067       isa<ScalableVectorType>(
4068           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4069     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4070     if (TryToFindDuplicates(S))
4071       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4072                    ReuseShuffleIndicies);
4073     return;
4074   }
4075 
4076   // Don't handle vectors.
4077   if (S.OpValue->getType()->isVectorTy() &&
4078       !isa<InsertElementInst>(S.OpValue)) {
4079     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4080     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4081     return;
4082   }
4083 
4084   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4085     if (SI->getValueOperand()->getType()->isVectorTy()) {
4086       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4087       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4088       return;
4089     }
4090 
4091   // If all of the operands are identical or constant we have a simple solution.
4092   // If we deal with insert/extract instructions, they all must have constant
4093   // indices, otherwise we should gather them, not try to vectorize.
4094   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4095       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4096        !all_of(VL, isVectorLikeInstWithConstOps))) {
4097     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4098     if (TryToFindDuplicates(S))
4099       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4100                    ReuseShuffleIndicies);
4101     return;
4102   }
4103 
4104   // We now know that this is a vector of instructions of the same type from
4105   // the same block.
4106 
4107   // Don't vectorize ephemeral values.
4108   for (Value *V : VL) {
4109     if (EphValues.count(V)) {
4110       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4111                         << ") is ephemeral.\n");
4112       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4113       return;
4114     }
4115   }
4116 
4117   // Check if this is a duplicate of another entry.
4118   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4119     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4120     if (!E->isSame(VL)) {
4121       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4122       if (TryToFindDuplicates(S))
4123         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4124                      ReuseShuffleIndicies);
4125       return;
4126     }
4127     // Record the reuse of the tree node.  FIXME, currently this is only used to
4128     // properly draw the graph rather than for the actual vectorization.
4129     E->UserTreeIndices.push_back(UserTreeIdx);
4130     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4131                       << ".\n");
4132     return;
4133   }
4134 
4135   // Check that none of the instructions in the bundle are already in the tree.
4136   for (Value *V : VL) {
4137     auto *I = dyn_cast<Instruction>(V);
4138     if (!I)
4139       continue;
4140     if (getTreeEntry(I)) {
4141       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4142                         << ") is already in tree.\n");
4143       if (TryToFindDuplicates(S))
4144         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4145                      ReuseShuffleIndicies);
4146       return;
4147     }
4148   }
4149 
4150   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4151   for (Value *V : VL) {
4152     if (is_contained(UserIgnoreList, V)) {
4153       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4154       if (TryToFindDuplicates(S))
4155         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4156                      ReuseShuffleIndicies);
4157       return;
4158     }
4159   }
4160 
4161   // Check that all of the users of the scalars that we want to vectorize are
4162   // schedulable.
4163   auto *VL0 = cast<Instruction>(S.OpValue);
4164   BasicBlock *BB = VL0->getParent();
4165 
4166   if (!DT->isReachableFromEntry(BB)) {
4167     // Don't go into unreachable blocks. They may contain instructions with
4168     // dependency cycles which confuse the final scheduling.
4169     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4170     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4171     return;
4172   }
4173 
4174   // Check that every instruction appears once in this bundle.
4175   if (!TryToFindDuplicates(S))
4176     return;
4177 
4178   auto &BSRef = BlocksSchedules[BB];
4179   if (!BSRef)
4180     BSRef = std::make_unique<BlockScheduling>(BB);
4181 
4182   BlockScheduling &BS = *BSRef;
4183 
4184   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4185 #ifdef EXPENSIVE_CHECKS
4186   // Make sure we didn't break any internal invariants
4187   BS.verify();
4188 #endif
4189   if (!Bundle) {
4190     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4191     assert((!BS.getScheduleData(VL0) ||
4192             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4193            "tryScheduleBundle should cancelScheduling on failure");
4194     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4195                  ReuseShuffleIndicies);
4196     return;
4197   }
4198   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4199 
4200   unsigned ShuffleOrOp = S.isAltShuffle() ?
4201                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4202   switch (ShuffleOrOp) {
4203     case Instruction::PHI: {
4204       auto *PH = cast<PHINode>(VL0);
4205 
4206       // Check for terminator values (e.g. invoke).
4207       for (Value *V : VL)
4208         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4209           Instruction *Term = dyn_cast<Instruction>(Incoming);
4210           if (Term && Term->isTerminator()) {
4211             LLVM_DEBUG(dbgs()
4212                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4213             BS.cancelScheduling(VL, VL0);
4214             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4215                          ReuseShuffleIndicies);
4216             return;
4217           }
4218         }
4219 
4220       TreeEntry *TE =
4221           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4222       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4223 
4224       // Keeps the reordered operands to avoid code duplication.
4225       SmallVector<ValueList, 2> OperandsVec;
4226       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4227         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4228           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4229           TE->setOperand(I, Operands);
4230           OperandsVec.push_back(Operands);
4231           continue;
4232         }
4233         ValueList Operands;
4234         // Prepare the operand vector.
4235         for (Value *V : VL)
4236           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4237               PH->getIncomingBlock(I)));
4238         TE->setOperand(I, Operands);
4239         OperandsVec.push_back(Operands);
4240       }
4241       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4242         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4243       return;
4244     }
4245     case Instruction::ExtractValue:
4246     case Instruction::ExtractElement: {
4247       OrdersType CurrentOrder;
4248       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4249       if (Reuse) {
4250         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4251         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4252                      ReuseShuffleIndicies);
4253         // This is a special case, as it does not gather, but at the same time
4254         // we are not extending buildTree_rec() towards the operands.
4255         ValueList Op0;
4256         Op0.assign(VL.size(), VL0->getOperand(0));
4257         VectorizableTree.back()->setOperand(0, Op0);
4258         return;
4259       }
4260       if (!CurrentOrder.empty()) {
4261         LLVM_DEBUG({
4262           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4263                     "with order";
4264           for (unsigned Idx : CurrentOrder)
4265             dbgs() << " " << Idx;
4266           dbgs() << "\n";
4267         });
4268         fixupOrderingIndices(CurrentOrder);
4269         // Insert new order with initial value 0, if it does not exist,
4270         // otherwise return the iterator to the existing one.
4271         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4272                      ReuseShuffleIndicies, CurrentOrder);
4273         // This is a special case, as it does not gather, but at the same time
4274         // we are not extending buildTree_rec() towards the operands.
4275         ValueList Op0;
4276         Op0.assign(VL.size(), VL0->getOperand(0));
4277         VectorizableTree.back()->setOperand(0, Op0);
4278         return;
4279       }
4280       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4281       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4282                    ReuseShuffleIndicies);
4283       BS.cancelScheduling(VL, VL0);
4284       return;
4285     }
4286     case Instruction::InsertElement: {
4287       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4288 
4289       // Check that we have a buildvector and not a shuffle of 2 or more
4290       // different vectors.
4291       ValueSet SourceVectors;
4292       for (Value *V : VL) {
4293         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4294         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4295       }
4296 
4297       if (count_if(VL, [&SourceVectors](Value *V) {
4298             return !SourceVectors.contains(V);
4299           }) >= 2) {
4300         // Found 2nd source vector - cancel.
4301         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4302                              "different source vectors.\n");
4303         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4304         BS.cancelScheduling(VL, VL0);
4305         return;
4306       }
4307 
4308       auto OrdCompare = [](const std::pair<int, int> &P1,
4309                            const std::pair<int, int> &P2) {
4310         return P1.first > P2.first;
4311       };
4312       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4313                     decltype(OrdCompare)>
4314           Indices(OrdCompare);
4315       for (int I = 0, E = VL.size(); I < E; ++I) {
4316         unsigned Idx = *getInsertIndex(VL[I]);
4317         Indices.emplace(Idx, I);
4318       }
4319       OrdersType CurrentOrder(VL.size(), VL.size());
4320       bool IsIdentity = true;
4321       for (int I = 0, E = VL.size(); I < E; ++I) {
4322         CurrentOrder[Indices.top().second] = I;
4323         IsIdentity &= Indices.top().second == I;
4324         Indices.pop();
4325       }
4326       if (IsIdentity)
4327         CurrentOrder.clear();
4328       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4329                                    None, CurrentOrder);
4330       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4331 
4332       constexpr int NumOps = 2;
4333       ValueList VectorOperands[NumOps];
4334       for (int I = 0; I < NumOps; ++I) {
4335         for (Value *V : VL)
4336           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4337 
4338         TE->setOperand(I, VectorOperands[I]);
4339       }
4340       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4341       return;
4342     }
4343     case Instruction::Load: {
4344       // Check that a vectorized load would load the same memory as a scalar
4345       // load. For example, we don't want to vectorize loads that are smaller
4346       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4347       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4348       // from such a struct, we read/write packed bits disagreeing with the
4349       // unvectorized version.
4350       SmallVector<Value *> PointerOps;
4351       OrdersType CurrentOrder;
4352       TreeEntry *TE = nullptr;
4353       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4354                                 PointerOps)) {
4355       case LoadsState::Vectorize:
4356         if (CurrentOrder.empty()) {
4357           // Original loads are consecutive and does not require reordering.
4358           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4359                             ReuseShuffleIndicies);
4360           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4361         } else {
4362           fixupOrderingIndices(CurrentOrder);
4363           // Need to reorder.
4364           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4365                             ReuseShuffleIndicies, CurrentOrder);
4366           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4367         }
4368         TE->setOperandsInOrder();
4369         break;
4370       case LoadsState::ScatterVectorize:
4371         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4372         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4373                           UserTreeIdx, ReuseShuffleIndicies);
4374         TE->setOperandsInOrder();
4375         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4376         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4377         break;
4378       case LoadsState::Gather:
4379         BS.cancelScheduling(VL, VL0);
4380         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4381                      ReuseShuffleIndicies);
4382 #ifndef NDEBUG
4383         Type *ScalarTy = VL0->getType();
4384         if (DL->getTypeSizeInBits(ScalarTy) !=
4385             DL->getTypeAllocSizeInBits(ScalarTy))
4386           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4387         else if (any_of(VL, [](Value *V) {
4388                    return !cast<LoadInst>(V)->isSimple();
4389                  }))
4390           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4391         else
4392           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4393 #endif // NDEBUG
4394         break;
4395       }
4396       return;
4397     }
4398     case Instruction::ZExt:
4399     case Instruction::SExt:
4400     case Instruction::FPToUI:
4401     case Instruction::FPToSI:
4402     case Instruction::FPExt:
4403     case Instruction::PtrToInt:
4404     case Instruction::IntToPtr:
4405     case Instruction::SIToFP:
4406     case Instruction::UIToFP:
4407     case Instruction::Trunc:
4408     case Instruction::FPTrunc:
4409     case Instruction::BitCast: {
4410       Type *SrcTy = VL0->getOperand(0)->getType();
4411       for (Value *V : VL) {
4412         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4413         if (Ty != SrcTy || !isValidElementType(Ty)) {
4414           BS.cancelScheduling(VL, VL0);
4415           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4416                        ReuseShuffleIndicies);
4417           LLVM_DEBUG(dbgs()
4418                      << "SLP: Gathering casts with different src types.\n");
4419           return;
4420         }
4421       }
4422       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4423                                    ReuseShuffleIndicies);
4424       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4425 
4426       TE->setOperandsInOrder();
4427       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4428         ValueList Operands;
4429         // Prepare the operand vector.
4430         for (Value *V : VL)
4431           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4432 
4433         buildTree_rec(Operands, Depth + 1, {TE, i});
4434       }
4435       return;
4436     }
4437     case Instruction::ICmp:
4438     case Instruction::FCmp: {
4439       // Check that all of the compares have the same predicate.
4440       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4441       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4442       Type *ComparedTy = VL0->getOperand(0)->getType();
4443       for (Value *V : VL) {
4444         CmpInst *Cmp = cast<CmpInst>(V);
4445         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4446             Cmp->getOperand(0)->getType() != ComparedTy) {
4447           BS.cancelScheduling(VL, VL0);
4448           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4449                        ReuseShuffleIndicies);
4450           LLVM_DEBUG(dbgs()
4451                      << "SLP: Gathering cmp with different predicate.\n");
4452           return;
4453         }
4454       }
4455 
4456       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4457                                    ReuseShuffleIndicies);
4458       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4459 
4460       ValueList Left, Right;
4461       if (cast<CmpInst>(VL0)->isCommutative()) {
4462         // Commutative predicate - collect + sort operands of the instructions
4463         // so that each side is more likely to have the same opcode.
4464         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4465         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4466       } else {
4467         // Collect operands - commute if it uses the swapped predicate.
4468         for (Value *V : VL) {
4469           auto *Cmp = cast<CmpInst>(V);
4470           Value *LHS = Cmp->getOperand(0);
4471           Value *RHS = Cmp->getOperand(1);
4472           if (Cmp->getPredicate() != P0)
4473             std::swap(LHS, RHS);
4474           Left.push_back(LHS);
4475           Right.push_back(RHS);
4476         }
4477       }
4478       TE->setOperand(0, Left);
4479       TE->setOperand(1, Right);
4480       buildTree_rec(Left, Depth + 1, {TE, 0});
4481       buildTree_rec(Right, Depth + 1, {TE, 1});
4482       return;
4483     }
4484     case Instruction::Select:
4485     case Instruction::FNeg:
4486     case Instruction::Add:
4487     case Instruction::FAdd:
4488     case Instruction::Sub:
4489     case Instruction::FSub:
4490     case Instruction::Mul:
4491     case Instruction::FMul:
4492     case Instruction::UDiv:
4493     case Instruction::SDiv:
4494     case Instruction::FDiv:
4495     case Instruction::URem:
4496     case Instruction::SRem:
4497     case Instruction::FRem:
4498     case Instruction::Shl:
4499     case Instruction::LShr:
4500     case Instruction::AShr:
4501     case Instruction::And:
4502     case Instruction::Or:
4503     case Instruction::Xor: {
4504       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4505                                    ReuseShuffleIndicies);
4506       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4507 
4508       // Sort operands of the instructions so that each side is more likely to
4509       // have the same opcode.
4510       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4511         ValueList Left, Right;
4512         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4513         TE->setOperand(0, Left);
4514         TE->setOperand(1, Right);
4515         buildTree_rec(Left, Depth + 1, {TE, 0});
4516         buildTree_rec(Right, Depth + 1, {TE, 1});
4517         return;
4518       }
4519 
4520       TE->setOperandsInOrder();
4521       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4522         ValueList Operands;
4523         // Prepare the operand vector.
4524         for (Value *V : VL)
4525           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4526 
4527         buildTree_rec(Operands, Depth + 1, {TE, i});
4528       }
4529       return;
4530     }
4531     case Instruction::GetElementPtr: {
4532       // We don't combine GEPs with complicated (nested) indexing.
4533       for (Value *V : VL) {
4534         if (cast<Instruction>(V)->getNumOperands() != 2) {
4535           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4536           BS.cancelScheduling(VL, VL0);
4537           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4538                        ReuseShuffleIndicies);
4539           return;
4540         }
4541       }
4542 
4543       // We can't combine several GEPs into one vector if they operate on
4544       // different types.
4545       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4546       for (Value *V : VL) {
4547         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4548         if (Ty0 != CurTy) {
4549           LLVM_DEBUG(dbgs()
4550                      << "SLP: not-vectorizable GEP (different types).\n");
4551           BS.cancelScheduling(VL, VL0);
4552           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4553                        ReuseShuffleIndicies);
4554           return;
4555         }
4556       }
4557 
4558       // We don't combine GEPs with non-constant indexes.
4559       Type *Ty1 = VL0->getOperand(1)->getType();
4560       for (Value *V : VL) {
4561         auto Op = cast<Instruction>(V)->getOperand(1);
4562         if (!isa<ConstantInt>(Op) ||
4563             (Op->getType() != Ty1 &&
4564              Op->getType()->getScalarSizeInBits() >
4565                  DL->getIndexSizeInBits(
4566                      V->getType()->getPointerAddressSpace()))) {
4567           LLVM_DEBUG(dbgs()
4568                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4569           BS.cancelScheduling(VL, VL0);
4570           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4571                        ReuseShuffleIndicies);
4572           return;
4573         }
4574       }
4575 
4576       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4577                                    ReuseShuffleIndicies);
4578       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4579       SmallVector<ValueList, 2> Operands(2);
4580       // Prepare the operand vector for pointer operands.
4581       for (Value *V : VL)
4582         Operands.front().push_back(
4583             cast<GetElementPtrInst>(V)->getPointerOperand());
4584       TE->setOperand(0, Operands.front());
4585       // Need to cast all indices to the same type before vectorization to
4586       // avoid crash.
4587       // Required to be able to find correct matches between different gather
4588       // nodes and reuse the vectorized values rather than trying to gather them
4589       // again.
4590       int IndexIdx = 1;
4591       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4592       Type *Ty = all_of(VL,
4593                         [VL0Ty, IndexIdx](Value *V) {
4594                           return VL0Ty == cast<GetElementPtrInst>(V)
4595                                               ->getOperand(IndexIdx)
4596                                               ->getType();
4597                         })
4598                      ? VL0Ty
4599                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4600                                             ->getPointerOperandType()
4601                                             ->getScalarType());
4602       // Prepare the operand vector.
4603       for (Value *V : VL) {
4604         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4605         auto *CI = cast<ConstantInt>(Op);
4606         Operands.back().push_back(ConstantExpr::getIntegerCast(
4607             CI, Ty, CI->getValue().isSignBitSet()));
4608       }
4609       TE->setOperand(IndexIdx, Operands.back());
4610 
4611       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4612         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4613       return;
4614     }
4615     case Instruction::Store: {
4616       // Check if the stores are consecutive or if we need to swizzle them.
4617       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4618       // Avoid types that are padded when being allocated as scalars, while
4619       // being packed together in a vector (such as i1).
4620       if (DL->getTypeSizeInBits(ScalarTy) !=
4621           DL->getTypeAllocSizeInBits(ScalarTy)) {
4622         BS.cancelScheduling(VL, VL0);
4623         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4624                      ReuseShuffleIndicies);
4625         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4626         return;
4627       }
4628       // Make sure all stores in the bundle are simple - we can't vectorize
4629       // atomic or volatile stores.
4630       SmallVector<Value *, 4> PointerOps(VL.size());
4631       ValueList Operands(VL.size());
4632       auto POIter = PointerOps.begin();
4633       auto OIter = Operands.begin();
4634       for (Value *V : VL) {
4635         auto *SI = cast<StoreInst>(V);
4636         if (!SI->isSimple()) {
4637           BS.cancelScheduling(VL, VL0);
4638           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4639                        ReuseShuffleIndicies);
4640           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4641           return;
4642         }
4643         *POIter = SI->getPointerOperand();
4644         *OIter = SI->getValueOperand();
4645         ++POIter;
4646         ++OIter;
4647       }
4648 
4649       OrdersType CurrentOrder;
4650       // Check the order of pointer operands.
4651       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4652         Value *Ptr0;
4653         Value *PtrN;
4654         if (CurrentOrder.empty()) {
4655           Ptr0 = PointerOps.front();
4656           PtrN = PointerOps.back();
4657         } else {
4658           Ptr0 = PointerOps[CurrentOrder.front()];
4659           PtrN = PointerOps[CurrentOrder.back()];
4660         }
4661         Optional<int> Dist =
4662             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4663         // Check that the sorted pointer operands are consecutive.
4664         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4665           if (CurrentOrder.empty()) {
4666             // Original stores are consecutive and does not require reordering.
4667             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4668                                          UserTreeIdx, ReuseShuffleIndicies);
4669             TE->setOperandsInOrder();
4670             buildTree_rec(Operands, Depth + 1, {TE, 0});
4671             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4672           } else {
4673             fixupOrderingIndices(CurrentOrder);
4674             TreeEntry *TE =
4675                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4676                              ReuseShuffleIndicies, CurrentOrder);
4677             TE->setOperandsInOrder();
4678             buildTree_rec(Operands, Depth + 1, {TE, 0});
4679             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4680           }
4681           return;
4682         }
4683       }
4684 
4685       BS.cancelScheduling(VL, VL0);
4686       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4687                    ReuseShuffleIndicies);
4688       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4689       return;
4690     }
4691     case Instruction::Call: {
4692       // Check if the calls are all to the same vectorizable intrinsic or
4693       // library function.
4694       CallInst *CI = cast<CallInst>(VL0);
4695       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4696 
4697       VFShape Shape = VFShape::get(
4698           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4699           false /*HasGlobalPred*/);
4700       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4701 
4702       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4703         BS.cancelScheduling(VL, VL0);
4704         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4705                      ReuseShuffleIndicies);
4706         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4707         return;
4708       }
4709       Function *F = CI->getCalledFunction();
4710       unsigned NumArgs = CI->arg_size();
4711       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4712       for (unsigned j = 0; j != NumArgs; ++j)
4713         if (hasVectorInstrinsicScalarOpd(ID, j))
4714           ScalarArgs[j] = CI->getArgOperand(j);
4715       for (Value *V : VL) {
4716         CallInst *CI2 = dyn_cast<CallInst>(V);
4717         if (!CI2 || CI2->getCalledFunction() != F ||
4718             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4719             (VecFunc &&
4720              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4721             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4722           BS.cancelScheduling(VL, VL0);
4723           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4724                        ReuseShuffleIndicies);
4725           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4726                             << "\n");
4727           return;
4728         }
4729         // Some intrinsics have scalar arguments and should be same in order for
4730         // them to be vectorized.
4731         for (unsigned j = 0; j != NumArgs; ++j) {
4732           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4733             Value *A1J = CI2->getArgOperand(j);
4734             if (ScalarArgs[j] != A1J) {
4735               BS.cancelScheduling(VL, VL0);
4736               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4737                            ReuseShuffleIndicies);
4738               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4739                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4740                                 << "\n");
4741               return;
4742             }
4743           }
4744         }
4745         // Verify that the bundle operands are identical between the two calls.
4746         if (CI->hasOperandBundles() &&
4747             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4748                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4749                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4750           BS.cancelScheduling(VL, VL0);
4751           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4752                        ReuseShuffleIndicies);
4753           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4754                             << *CI << "!=" << *V << '\n');
4755           return;
4756         }
4757       }
4758 
4759       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4760                                    ReuseShuffleIndicies);
4761       TE->setOperandsInOrder();
4762       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4763         // For scalar operands no need to to create an entry since no need to
4764         // vectorize it.
4765         if (hasVectorInstrinsicScalarOpd(ID, i))
4766           continue;
4767         ValueList Operands;
4768         // Prepare the operand vector.
4769         for (Value *V : VL) {
4770           auto *CI2 = cast<CallInst>(V);
4771           Operands.push_back(CI2->getArgOperand(i));
4772         }
4773         buildTree_rec(Operands, Depth + 1, {TE, i});
4774       }
4775       return;
4776     }
4777     case Instruction::ShuffleVector: {
4778       // If this is not an alternate sequence of opcode like add-sub
4779       // then do not vectorize this instruction.
4780       if (!S.isAltShuffle()) {
4781         BS.cancelScheduling(VL, VL0);
4782         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4783                      ReuseShuffleIndicies);
4784         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4785         return;
4786       }
4787       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4788                                    ReuseShuffleIndicies);
4789       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4790 
4791       // Reorder operands if reordering would enable vectorization.
4792       auto *CI = dyn_cast<CmpInst>(VL0);
4793       if (isa<BinaryOperator>(VL0) || CI) {
4794         ValueList Left, Right;
4795         if (!CI || all_of(VL, [](Value *V) {
4796               return cast<CmpInst>(V)->isCommutative();
4797             })) {
4798           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4799         } else {
4800           CmpInst::Predicate P0 = CI->getPredicate();
4801           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4802           assert(P0 != AltP0 &&
4803                  "Expected different main/alternate predicates.");
4804           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4805           Value *BaseOp0 = VL0->getOperand(0);
4806           Value *BaseOp1 = VL0->getOperand(1);
4807           // Collect operands - commute if it uses the swapped predicate or
4808           // alternate operation.
4809           for (Value *V : VL) {
4810             auto *Cmp = cast<CmpInst>(V);
4811             Value *LHS = Cmp->getOperand(0);
4812             Value *RHS = Cmp->getOperand(1);
4813             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4814             if (P0 == AltP0Swapped) {
4815               if (CI != Cmp && S.AltOp != Cmp &&
4816                   ((P0 == CurrentPred &&
4817                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4818                    (AltP0 == CurrentPred &&
4819                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4820                 std::swap(LHS, RHS);
4821             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4822               std::swap(LHS, RHS);
4823             }
4824             Left.push_back(LHS);
4825             Right.push_back(RHS);
4826           }
4827         }
4828         TE->setOperand(0, Left);
4829         TE->setOperand(1, Right);
4830         buildTree_rec(Left, Depth + 1, {TE, 0});
4831         buildTree_rec(Right, Depth + 1, {TE, 1});
4832         return;
4833       }
4834 
4835       TE->setOperandsInOrder();
4836       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4837         ValueList Operands;
4838         // Prepare the operand vector.
4839         for (Value *V : VL)
4840           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4841 
4842         buildTree_rec(Operands, Depth + 1, {TE, i});
4843       }
4844       return;
4845     }
4846     default:
4847       BS.cancelScheduling(VL, VL0);
4848       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4849                    ReuseShuffleIndicies);
4850       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4851       return;
4852   }
4853 }
4854 
4855 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4856   unsigned N = 1;
4857   Type *EltTy = T;
4858 
4859   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4860          isa<VectorType>(EltTy)) {
4861     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4862       // Check that struct is homogeneous.
4863       for (const auto *Ty : ST->elements())
4864         if (Ty != *ST->element_begin())
4865           return 0;
4866       N *= ST->getNumElements();
4867       EltTy = *ST->element_begin();
4868     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4869       N *= AT->getNumElements();
4870       EltTy = AT->getElementType();
4871     } else {
4872       auto *VT = cast<FixedVectorType>(EltTy);
4873       N *= VT->getNumElements();
4874       EltTy = VT->getElementType();
4875     }
4876   }
4877 
4878   if (!isValidElementType(EltTy))
4879     return 0;
4880   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4881   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4882     return 0;
4883   return N;
4884 }
4885 
4886 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4887                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4888   const auto *It = find_if(VL, [](Value *V) {
4889     return isa<ExtractElementInst, ExtractValueInst>(V);
4890   });
4891   assert(It != VL.end() && "Expected at least one extract instruction.");
4892   auto *E0 = cast<Instruction>(*It);
4893   assert(all_of(VL,
4894                 [](Value *V) {
4895                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4896                       V);
4897                 }) &&
4898          "Invalid opcode");
4899   // Check if all of the extracts come from the same vector and from the
4900   // correct offset.
4901   Value *Vec = E0->getOperand(0);
4902 
4903   CurrentOrder.clear();
4904 
4905   // We have to extract from a vector/aggregate with the same number of elements.
4906   unsigned NElts;
4907   if (E0->getOpcode() == Instruction::ExtractValue) {
4908     const DataLayout &DL = E0->getModule()->getDataLayout();
4909     NElts = canMapToVector(Vec->getType(), DL);
4910     if (!NElts)
4911       return false;
4912     // Check if load can be rewritten as load of vector.
4913     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4914     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4915       return false;
4916   } else {
4917     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4918   }
4919 
4920   if (NElts != VL.size())
4921     return false;
4922 
4923   // Check that all of the indices extract from the correct offset.
4924   bool ShouldKeepOrder = true;
4925   unsigned E = VL.size();
4926   // Assign to all items the initial value E + 1 so we can check if the extract
4927   // instruction index was used already.
4928   // Also, later we can check that all the indices are used and we have a
4929   // consecutive access in the extract instructions, by checking that no
4930   // element of CurrentOrder still has value E + 1.
4931   CurrentOrder.assign(E, E);
4932   unsigned I = 0;
4933   for (; I < E; ++I) {
4934     auto *Inst = dyn_cast<Instruction>(VL[I]);
4935     if (!Inst)
4936       continue;
4937     if (Inst->getOperand(0) != Vec)
4938       break;
4939     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4940       if (isa<UndefValue>(EE->getIndexOperand()))
4941         continue;
4942     Optional<unsigned> Idx = getExtractIndex(Inst);
4943     if (!Idx)
4944       break;
4945     const unsigned ExtIdx = *Idx;
4946     if (ExtIdx != I) {
4947       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4948         break;
4949       ShouldKeepOrder = false;
4950       CurrentOrder[ExtIdx] = I;
4951     } else {
4952       if (CurrentOrder[I] != E)
4953         break;
4954       CurrentOrder[I] = I;
4955     }
4956   }
4957   if (I < E) {
4958     CurrentOrder.clear();
4959     return false;
4960   }
4961   if (ShouldKeepOrder)
4962     CurrentOrder.clear();
4963 
4964   return ShouldKeepOrder;
4965 }
4966 
4967 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4968                                     ArrayRef<Value *> VectorizedVals) const {
4969   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4970          all_of(I->users(), [this](User *U) {
4971            return ScalarToTreeEntry.count(U) > 0 ||
4972                   isVectorLikeInstWithConstOps(U) ||
4973                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4974          });
4975 }
4976 
4977 static std::pair<InstructionCost, InstructionCost>
4978 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4979                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4980   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4981 
4982   // Calculate the cost of the scalar and vector calls.
4983   SmallVector<Type *, 4> VecTys;
4984   for (Use &Arg : CI->args())
4985     VecTys.push_back(
4986         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4987   FastMathFlags FMF;
4988   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4989     FMF = FPCI->getFastMathFlags();
4990   SmallVector<const Value *> Arguments(CI->args());
4991   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4992                                     dyn_cast<IntrinsicInst>(CI));
4993   auto IntrinsicCost =
4994     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4995 
4996   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4997                                      VecTy->getNumElements())),
4998                             false /*HasGlobalPred*/);
4999   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
5000   auto LibCost = IntrinsicCost;
5001   if (!CI->isNoBuiltin() && VecFunc) {
5002     // Calculate the cost of the vector library call.
5003     // If the corresponding vector call is cheaper, return its cost.
5004     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
5005                                     TTI::TCK_RecipThroughput);
5006   }
5007   return {IntrinsicCost, LibCost};
5008 }
5009 
5010 /// Compute the cost of creating a vector of type \p VecTy containing the
5011 /// extracted values from \p VL.
5012 static InstructionCost
5013 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
5014                    TargetTransformInfo::ShuffleKind ShuffleKind,
5015                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
5016   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
5017 
5018   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
5019       VecTy->getNumElements() < NumOfParts)
5020     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
5021 
5022   bool AllConsecutive = true;
5023   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
5024   unsigned Idx = -1;
5025   InstructionCost Cost = 0;
5026 
5027   // Process extracts in blocks of EltsPerVector to check if the source vector
5028   // operand can be re-used directly. If not, add the cost of creating a shuffle
5029   // to extract the values into a vector register.
5030   for (auto *V : VL) {
5031     ++Idx;
5032 
5033     // Need to exclude undefs from analysis.
5034     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
5035       continue;
5036 
5037     // Reached the start of a new vector registers.
5038     if (Idx % EltsPerVector == 0) {
5039       AllConsecutive = true;
5040       continue;
5041     }
5042 
5043     // Check all extracts for a vector register on the target directly
5044     // extract values in order.
5045     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
5046     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
5047       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
5048       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
5049                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
5050     }
5051 
5052     if (AllConsecutive)
5053       continue;
5054 
5055     // Skip all indices, except for the last index per vector block.
5056     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5057       continue;
5058 
5059     // If we have a series of extracts which are not consecutive and hence
5060     // cannot re-use the source vector register directly, compute the shuffle
5061     // cost to extract the a vector with EltsPerVector elements.
5062     Cost += TTI.getShuffleCost(
5063         TargetTransformInfo::SK_PermuteSingleSrc,
5064         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5065   }
5066   return Cost;
5067 }
5068 
5069 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5070 /// operations operands.
5071 static void
5072 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5073                       ArrayRef<int> ReusesIndices,
5074                       const function_ref<bool(Instruction *)> IsAltOp,
5075                       SmallVectorImpl<int> &Mask,
5076                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5077                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5078   unsigned Sz = VL.size();
5079   Mask.assign(Sz, UndefMaskElem);
5080   SmallVector<int> OrderMask;
5081   if (!ReorderIndices.empty())
5082     inversePermutation(ReorderIndices, OrderMask);
5083   for (unsigned I = 0; I < Sz; ++I) {
5084     unsigned Idx = I;
5085     if (!ReorderIndices.empty())
5086       Idx = OrderMask[I];
5087     auto *OpInst = cast<Instruction>(VL[Idx]);
5088     if (IsAltOp(OpInst)) {
5089       Mask[I] = Sz + Idx;
5090       if (AltScalars)
5091         AltScalars->push_back(OpInst);
5092     } else {
5093       Mask[I] = Idx;
5094       if (OpScalars)
5095         OpScalars->push_back(OpInst);
5096     }
5097   }
5098   if (!ReusesIndices.empty()) {
5099     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5100     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5101       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5102     });
5103     Mask.swap(NewMask);
5104   }
5105 }
5106 
5107 /// Checks if the specified instruction \p I is an alternate operation for the
5108 /// given \p MainOp and \p AltOp instructions.
5109 static bool isAlternateInstruction(const Instruction *I,
5110                                    const Instruction *MainOp,
5111                                    const Instruction *AltOp) {
5112   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5113     auto *AltCI0 = cast<CmpInst>(AltOp);
5114     auto *CI = cast<CmpInst>(I);
5115     CmpInst::Predicate P0 = CI0->getPredicate();
5116     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5117     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5118     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5119     CmpInst::Predicate CurrentPred = CI->getPredicate();
5120     if (P0 == AltP0Swapped)
5121       return I == AltCI0 ||
5122              (I != MainOp &&
5123               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5124                                    CI->getOperand(0), CI->getOperand(1)));
5125     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5126   }
5127   return I->getOpcode() == AltOp->getOpcode();
5128 }
5129 
5130 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5131                                       ArrayRef<Value *> VectorizedVals) {
5132   ArrayRef<Value*> VL = E->Scalars;
5133 
5134   Type *ScalarTy = VL[0]->getType();
5135   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5136     ScalarTy = SI->getValueOperand()->getType();
5137   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5138     ScalarTy = CI->getOperand(0)->getType();
5139   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5140     ScalarTy = IE->getOperand(1)->getType();
5141   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5142   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5143 
5144   // If we have computed a smaller type for the expression, update VecTy so
5145   // that the costs will be accurate.
5146   if (MinBWs.count(VL[0]))
5147     VecTy = FixedVectorType::get(
5148         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5149   unsigned EntryVF = E->getVectorFactor();
5150   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5151 
5152   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5153   // FIXME: it tries to fix a problem with MSVC buildbots.
5154   TargetTransformInfo &TTIRef = *TTI;
5155   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5156                                VectorizedVals, E](InstructionCost &Cost) {
5157     DenseMap<Value *, int> ExtractVectorsTys;
5158     SmallPtrSet<Value *, 4> CheckedExtracts;
5159     for (auto *V : VL) {
5160       if (isa<UndefValue>(V))
5161         continue;
5162       // If all users of instruction are going to be vectorized and this
5163       // instruction itself is not going to be vectorized, consider this
5164       // instruction as dead and remove its cost from the final cost of the
5165       // vectorized tree.
5166       // Also, avoid adjusting the cost for extractelements with multiple uses
5167       // in different graph entries.
5168       const TreeEntry *VE = getTreeEntry(V);
5169       if (!CheckedExtracts.insert(V).second ||
5170           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5171           (VE && VE != E))
5172         continue;
5173       auto *EE = cast<ExtractElementInst>(V);
5174       Optional<unsigned> EEIdx = getExtractIndex(EE);
5175       if (!EEIdx)
5176         continue;
5177       unsigned Idx = *EEIdx;
5178       if (TTIRef.getNumberOfParts(VecTy) !=
5179           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5180         auto It =
5181             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5182         It->getSecond() = std::min<int>(It->second, Idx);
5183       }
5184       // Take credit for instruction that will become dead.
5185       if (EE->hasOneUse()) {
5186         Instruction *Ext = EE->user_back();
5187         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5188             all_of(Ext->users(),
5189                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5190           // Use getExtractWithExtendCost() to calculate the cost of
5191           // extractelement/ext pair.
5192           Cost -=
5193               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5194                                               EE->getVectorOperandType(), Idx);
5195           // Add back the cost of s|zext which is subtracted separately.
5196           Cost += TTIRef.getCastInstrCost(
5197               Ext->getOpcode(), Ext->getType(), EE->getType(),
5198               TTI::getCastContextHint(Ext), CostKind, Ext);
5199           continue;
5200         }
5201       }
5202       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5203                                         EE->getVectorOperandType(), Idx);
5204     }
5205     // Add a cost for subvector extracts/inserts if required.
5206     for (const auto &Data : ExtractVectorsTys) {
5207       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5208       unsigned NumElts = VecTy->getNumElements();
5209       if (Data.second % NumElts == 0)
5210         continue;
5211       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5212         unsigned Idx = (Data.second / NumElts) * NumElts;
5213         unsigned EENumElts = EEVTy->getNumElements();
5214         if (Idx + NumElts <= EENumElts) {
5215           Cost +=
5216               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5217                                     EEVTy, None, Idx, VecTy);
5218         } else {
5219           // Need to round up the subvector type vectorization factor to avoid a
5220           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5221           // <= EENumElts.
5222           auto *SubVT =
5223               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5224           Cost +=
5225               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5226                                     EEVTy, None, Idx, SubVT);
5227         }
5228       } else {
5229         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5230                                       VecTy, None, 0, EEVTy);
5231       }
5232     }
5233   };
5234   if (E->State == TreeEntry::NeedToGather) {
5235     if (allConstant(VL))
5236       return 0;
5237     if (isa<InsertElementInst>(VL[0]))
5238       return InstructionCost::getInvalid();
5239     SmallVector<int> Mask;
5240     SmallVector<const TreeEntry *> Entries;
5241     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5242         isGatherShuffledEntry(E, Mask, Entries);
5243     if (Shuffle.hasValue()) {
5244       InstructionCost GatherCost = 0;
5245       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5246         // Perfect match in the graph, will reuse the previously vectorized
5247         // node. Cost is 0.
5248         LLVM_DEBUG(
5249             dbgs()
5250             << "SLP: perfect diamond match for gather bundle that starts with "
5251             << *VL.front() << ".\n");
5252         if (NeedToShuffleReuses)
5253           GatherCost =
5254               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5255                                   FinalVecTy, E->ReuseShuffleIndices);
5256       } else {
5257         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5258                           << " entries for bundle that starts with "
5259                           << *VL.front() << ".\n");
5260         // Detected that instead of gather we can emit a shuffle of single/two
5261         // previously vectorized nodes. Add the cost of the permutation rather
5262         // than gather.
5263         ::addMask(Mask, E->ReuseShuffleIndices);
5264         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5265       }
5266       return GatherCost;
5267     }
5268     if ((E->getOpcode() == Instruction::ExtractElement ||
5269          all_of(E->Scalars,
5270                 [](Value *V) {
5271                   return isa<ExtractElementInst, UndefValue>(V);
5272                 })) &&
5273         allSameType(VL)) {
5274       // Check that gather of extractelements can be represented as just a
5275       // shuffle of a single/two vectors the scalars are extracted from.
5276       SmallVector<int> Mask;
5277       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5278           isFixedVectorShuffle(VL, Mask);
5279       if (ShuffleKind.hasValue()) {
5280         // Found the bunch of extractelement instructions that must be gathered
5281         // into a vector and can be represented as a permutation elements in a
5282         // single input vector or of 2 input vectors.
5283         InstructionCost Cost =
5284             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5285         AdjustExtractsCost(Cost);
5286         if (NeedToShuffleReuses)
5287           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5288                                       FinalVecTy, E->ReuseShuffleIndices);
5289         return Cost;
5290       }
5291     }
5292     if (isSplat(VL)) {
5293       // Found the broadcasting of the single scalar, calculate the cost as the
5294       // broadcast.
5295       assert(VecTy == FinalVecTy &&
5296              "No reused scalars expected for broadcast.");
5297       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5298                                  /*Mask=*/None, /*Index=*/0,
5299                                  /*SubTp=*/nullptr, /*Args=*/VL);
5300     }
5301     InstructionCost ReuseShuffleCost = 0;
5302     if (NeedToShuffleReuses)
5303       ReuseShuffleCost = TTI->getShuffleCost(
5304           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5305     // Improve gather cost for gather of loads, if we can group some of the
5306     // loads into vector loads.
5307     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5308         !E->isAltShuffle()) {
5309       BoUpSLP::ValueSet VectorizedLoads;
5310       unsigned StartIdx = 0;
5311       unsigned VF = VL.size() / 2;
5312       unsigned VectorizedCnt = 0;
5313       unsigned ScatterVectorizeCnt = 0;
5314       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5315       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5316         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5317              Cnt += VF) {
5318           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5319           if (!VectorizedLoads.count(Slice.front()) &&
5320               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5321             SmallVector<Value *> PointerOps;
5322             OrdersType CurrentOrder;
5323             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5324                                               *SE, CurrentOrder, PointerOps);
5325             switch (LS) {
5326             case LoadsState::Vectorize:
5327             case LoadsState::ScatterVectorize:
5328               // Mark the vectorized loads so that we don't vectorize them
5329               // again.
5330               if (LS == LoadsState::Vectorize)
5331                 ++VectorizedCnt;
5332               else
5333                 ++ScatterVectorizeCnt;
5334               VectorizedLoads.insert(Slice.begin(), Slice.end());
5335               // If we vectorized initial block, no need to try to vectorize it
5336               // again.
5337               if (Cnt == StartIdx)
5338                 StartIdx += VF;
5339               break;
5340             case LoadsState::Gather:
5341               break;
5342             }
5343           }
5344         }
5345         // Check if the whole array was vectorized already - exit.
5346         if (StartIdx >= VL.size())
5347           break;
5348         // Found vectorizable parts - exit.
5349         if (!VectorizedLoads.empty())
5350           break;
5351       }
5352       if (!VectorizedLoads.empty()) {
5353         InstructionCost GatherCost = 0;
5354         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5355         bool NeedInsertSubvectorAnalysis =
5356             !NumParts || (VL.size() / VF) > NumParts;
5357         // Get the cost for gathered loads.
5358         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5359           if (VectorizedLoads.contains(VL[I]))
5360             continue;
5361           GatherCost += getGatherCost(VL.slice(I, VF));
5362         }
5363         // The cost for vectorized loads.
5364         InstructionCost ScalarsCost = 0;
5365         for (Value *V : VectorizedLoads) {
5366           auto *LI = cast<LoadInst>(V);
5367           ScalarsCost += TTI->getMemoryOpCost(
5368               Instruction::Load, LI->getType(), LI->getAlign(),
5369               LI->getPointerAddressSpace(), CostKind, LI);
5370         }
5371         auto *LI = cast<LoadInst>(E->getMainOp());
5372         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5373         Align Alignment = LI->getAlign();
5374         GatherCost +=
5375             VectorizedCnt *
5376             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5377                                  LI->getPointerAddressSpace(), CostKind, LI);
5378         GatherCost += ScatterVectorizeCnt *
5379                       TTI->getGatherScatterOpCost(
5380                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5381                           /*VariableMask=*/false, Alignment, CostKind, LI);
5382         if (NeedInsertSubvectorAnalysis) {
5383           // Add the cost for the subvectors insert.
5384           for (int I = VF, E = VL.size(); I < E; I += VF)
5385             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5386                                               None, I, LoadTy);
5387         }
5388         return ReuseShuffleCost + GatherCost - ScalarsCost;
5389       }
5390     }
5391     return ReuseShuffleCost + getGatherCost(VL);
5392   }
5393   InstructionCost CommonCost = 0;
5394   SmallVector<int> Mask;
5395   if (!E->ReorderIndices.empty()) {
5396     SmallVector<int> NewMask;
5397     if (E->getOpcode() == Instruction::Store) {
5398       // For stores the order is actually a mask.
5399       NewMask.resize(E->ReorderIndices.size());
5400       copy(E->ReorderIndices, NewMask.begin());
5401     } else {
5402       inversePermutation(E->ReorderIndices, NewMask);
5403     }
5404     ::addMask(Mask, NewMask);
5405   }
5406   if (NeedToShuffleReuses)
5407     ::addMask(Mask, E->ReuseShuffleIndices);
5408   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5409     CommonCost =
5410         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5411   assert((E->State == TreeEntry::Vectorize ||
5412           E->State == TreeEntry::ScatterVectorize) &&
5413          "Unhandled state");
5414   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5415   Instruction *VL0 = E->getMainOp();
5416   unsigned ShuffleOrOp =
5417       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5418   switch (ShuffleOrOp) {
5419     case Instruction::PHI:
5420       return 0;
5421 
5422     case Instruction::ExtractValue:
5423     case Instruction::ExtractElement: {
5424       // The common cost of removal ExtractElement/ExtractValue instructions +
5425       // the cost of shuffles, if required to resuffle the original vector.
5426       if (NeedToShuffleReuses) {
5427         unsigned Idx = 0;
5428         for (unsigned I : E->ReuseShuffleIndices) {
5429           if (ShuffleOrOp == Instruction::ExtractElement) {
5430             auto *EE = cast<ExtractElementInst>(VL[I]);
5431             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5432                                                   EE->getVectorOperandType(),
5433                                                   *getExtractIndex(EE));
5434           } else {
5435             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5436                                                   VecTy, Idx);
5437             ++Idx;
5438           }
5439         }
5440         Idx = EntryVF;
5441         for (Value *V : VL) {
5442           if (ShuffleOrOp == Instruction::ExtractElement) {
5443             auto *EE = cast<ExtractElementInst>(V);
5444             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5445                                                   EE->getVectorOperandType(),
5446                                                   *getExtractIndex(EE));
5447           } else {
5448             --Idx;
5449             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5450                                                   VecTy, Idx);
5451           }
5452         }
5453       }
5454       if (ShuffleOrOp == Instruction::ExtractValue) {
5455         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5456           auto *EI = cast<Instruction>(VL[I]);
5457           // Take credit for instruction that will become dead.
5458           if (EI->hasOneUse()) {
5459             Instruction *Ext = EI->user_back();
5460             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5461                 all_of(Ext->users(),
5462                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5463               // Use getExtractWithExtendCost() to calculate the cost of
5464               // extractelement/ext pair.
5465               CommonCost -= TTI->getExtractWithExtendCost(
5466                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5467               // Add back the cost of s|zext which is subtracted separately.
5468               CommonCost += TTI->getCastInstrCost(
5469                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5470                   TTI::getCastContextHint(Ext), CostKind, Ext);
5471               continue;
5472             }
5473           }
5474           CommonCost -=
5475               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5476         }
5477       } else {
5478         AdjustExtractsCost(CommonCost);
5479       }
5480       return CommonCost;
5481     }
5482     case Instruction::InsertElement: {
5483       assert(E->ReuseShuffleIndices.empty() &&
5484              "Unique insertelements only are expected.");
5485       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5486 
5487       unsigned const NumElts = SrcVecTy->getNumElements();
5488       unsigned const NumScalars = VL.size();
5489       APInt DemandedElts = APInt::getZero(NumElts);
5490       // TODO: Add support for Instruction::InsertValue.
5491       SmallVector<int> Mask;
5492       if (!E->ReorderIndices.empty()) {
5493         inversePermutation(E->ReorderIndices, Mask);
5494         Mask.append(NumElts - NumScalars, UndefMaskElem);
5495       } else {
5496         Mask.assign(NumElts, UndefMaskElem);
5497         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5498       }
5499       unsigned Offset = *getInsertIndex(VL0);
5500       bool IsIdentity = true;
5501       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5502       Mask.swap(PrevMask);
5503       for (unsigned I = 0; I < NumScalars; ++I) {
5504         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5505         DemandedElts.setBit(InsertIdx);
5506         IsIdentity &= InsertIdx - Offset == I;
5507         Mask[InsertIdx - Offset] = I;
5508       }
5509       assert(Offset < NumElts && "Failed to find vector index offset");
5510 
5511       InstructionCost Cost = 0;
5512       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5513                                             /*Insert*/ true, /*Extract*/ false);
5514 
5515       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5516         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5517         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5518         Cost += TTI->getShuffleCost(
5519             TargetTransformInfo::SK_PermuteSingleSrc,
5520             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5521       } else if (!IsIdentity) {
5522         auto *FirstInsert =
5523             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5524               return !is_contained(E->Scalars,
5525                                    cast<Instruction>(V)->getOperand(0));
5526             }));
5527         if (isUndefVector(FirstInsert->getOperand(0))) {
5528           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5529         } else {
5530           SmallVector<int> InsertMask(NumElts);
5531           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5532           for (unsigned I = 0; I < NumElts; I++) {
5533             if (Mask[I] != UndefMaskElem)
5534               InsertMask[Offset + I] = NumElts + I;
5535           }
5536           Cost +=
5537               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5538         }
5539       }
5540 
5541       return Cost;
5542     }
5543     case Instruction::ZExt:
5544     case Instruction::SExt:
5545     case Instruction::FPToUI:
5546     case Instruction::FPToSI:
5547     case Instruction::FPExt:
5548     case Instruction::PtrToInt:
5549     case Instruction::IntToPtr:
5550     case Instruction::SIToFP:
5551     case Instruction::UIToFP:
5552     case Instruction::Trunc:
5553     case Instruction::FPTrunc:
5554     case Instruction::BitCast: {
5555       Type *SrcTy = VL0->getOperand(0)->getType();
5556       InstructionCost ScalarEltCost =
5557           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5558                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5559       if (NeedToShuffleReuses) {
5560         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5561       }
5562 
5563       // Calculate the cost of this instruction.
5564       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5565 
5566       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5567       InstructionCost VecCost = 0;
5568       // Check if the values are candidates to demote.
5569       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5570         VecCost = CommonCost + TTI->getCastInstrCost(
5571                                    E->getOpcode(), VecTy, SrcVecTy,
5572                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5573       }
5574       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5575       return VecCost - ScalarCost;
5576     }
5577     case Instruction::FCmp:
5578     case Instruction::ICmp:
5579     case Instruction::Select: {
5580       // Calculate the cost of this instruction.
5581       InstructionCost ScalarEltCost =
5582           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5583                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5584       if (NeedToShuffleReuses) {
5585         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5586       }
5587       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5588       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5589 
5590       // Check if all entries in VL are either compares or selects with compares
5591       // as condition that have the same predicates.
5592       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5593       bool First = true;
5594       for (auto *V : VL) {
5595         CmpInst::Predicate CurrentPred;
5596         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5597         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5598              !match(V, MatchCmp)) ||
5599             (!First && VecPred != CurrentPred)) {
5600           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5601           break;
5602         }
5603         First = false;
5604         VecPred = CurrentPred;
5605       }
5606 
5607       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5608           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5609       // Check if it is possible and profitable to use min/max for selects in
5610       // VL.
5611       //
5612       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5613       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5614         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5615                                           {VecTy, VecTy});
5616         InstructionCost IntrinsicCost =
5617             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5618         // If the selects are the only uses of the compares, they will be dead
5619         // and we can adjust the cost by removing their cost.
5620         if (IntrinsicAndUse.second)
5621           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5622                                                    MaskTy, VecPred, CostKind);
5623         VecCost = std::min(VecCost, IntrinsicCost);
5624       }
5625       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5626       return CommonCost + VecCost - ScalarCost;
5627     }
5628     case Instruction::FNeg:
5629     case Instruction::Add:
5630     case Instruction::FAdd:
5631     case Instruction::Sub:
5632     case Instruction::FSub:
5633     case Instruction::Mul:
5634     case Instruction::FMul:
5635     case Instruction::UDiv:
5636     case Instruction::SDiv:
5637     case Instruction::FDiv:
5638     case Instruction::URem:
5639     case Instruction::SRem:
5640     case Instruction::FRem:
5641     case Instruction::Shl:
5642     case Instruction::LShr:
5643     case Instruction::AShr:
5644     case Instruction::And:
5645     case Instruction::Or:
5646     case Instruction::Xor: {
5647       // Certain instructions can be cheaper to vectorize if they have a
5648       // constant second vector operand.
5649       TargetTransformInfo::OperandValueKind Op1VK =
5650           TargetTransformInfo::OK_AnyValue;
5651       TargetTransformInfo::OperandValueKind Op2VK =
5652           TargetTransformInfo::OK_UniformConstantValue;
5653       TargetTransformInfo::OperandValueProperties Op1VP =
5654           TargetTransformInfo::OP_None;
5655       TargetTransformInfo::OperandValueProperties Op2VP =
5656           TargetTransformInfo::OP_PowerOf2;
5657 
5658       // If all operands are exactly the same ConstantInt then set the
5659       // operand kind to OK_UniformConstantValue.
5660       // If instead not all operands are constants, then set the operand kind
5661       // to OK_AnyValue. If all operands are constants but not the same,
5662       // then set the operand kind to OK_NonUniformConstantValue.
5663       ConstantInt *CInt0 = nullptr;
5664       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5665         const Instruction *I = cast<Instruction>(VL[i]);
5666         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5667         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5668         if (!CInt) {
5669           Op2VK = TargetTransformInfo::OK_AnyValue;
5670           Op2VP = TargetTransformInfo::OP_None;
5671           break;
5672         }
5673         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5674             !CInt->getValue().isPowerOf2())
5675           Op2VP = TargetTransformInfo::OP_None;
5676         if (i == 0) {
5677           CInt0 = CInt;
5678           continue;
5679         }
5680         if (CInt0 != CInt)
5681           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5682       }
5683 
5684       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5685       InstructionCost ScalarEltCost =
5686           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5687                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5688       if (NeedToShuffleReuses) {
5689         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5690       }
5691       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5692       InstructionCost VecCost =
5693           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5694                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5695       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5696       return CommonCost + VecCost - ScalarCost;
5697     }
5698     case Instruction::GetElementPtr: {
5699       TargetTransformInfo::OperandValueKind Op1VK =
5700           TargetTransformInfo::OK_AnyValue;
5701       TargetTransformInfo::OperandValueKind Op2VK =
5702           TargetTransformInfo::OK_UniformConstantValue;
5703 
5704       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5705           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5706       if (NeedToShuffleReuses) {
5707         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5708       }
5709       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5710       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5711           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5712       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5713       return CommonCost + VecCost - ScalarCost;
5714     }
5715     case Instruction::Load: {
5716       // Cost of wide load - cost of scalar loads.
5717       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5718       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5719           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5720       if (NeedToShuffleReuses) {
5721         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5722       }
5723       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5724       InstructionCost VecLdCost;
5725       if (E->State == TreeEntry::Vectorize) {
5726         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5727                                          CostKind, VL0);
5728       } else {
5729         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5730         Align CommonAlignment = Alignment;
5731         for (Value *V : VL)
5732           CommonAlignment =
5733               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5734         VecLdCost = TTI->getGatherScatterOpCost(
5735             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5736             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5737       }
5738       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5739       return CommonCost + VecLdCost - ScalarLdCost;
5740     }
5741     case Instruction::Store: {
5742       // We know that we can merge the stores. Calculate the cost.
5743       bool IsReorder = !E->ReorderIndices.empty();
5744       auto *SI =
5745           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5746       Align Alignment = SI->getAlign();
5747       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5748           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5749       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5750       InstructionCost VecStCost = TTI->getMemoryOpCost(
5751           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5752       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5753       return CommonCost + VecStCost - ScalarStCost;
5754     }
5755     case Instruction::Call: {
5756       CallInst *CI = cast<CallInst>(VL0);
5757       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5758 
5759       // Calculate the cost of the scalar and vector calls.
5760       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5761       InstructionCost ScalarEltCost =
5762           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5763       if (NeedToShuffleReuses) {
5764         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5765       }
5766       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5767 
5768       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5769       InstructionCost VecCallCost =
5770           std::min(VecCallCosts.first, VecCallCosts.second);
5771 
5772       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5773                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5774                         << " for " << *CI << "\n");
5775 
5776       return CommonCost + VecCallCost - ScalarCallCost;
5777     }
5778     case Instruction::ShuffleVector: {
5779       assert(E->isAltShuffle() &&
5780              ((Instruction::isBinaryOp(E->getOpcode()) &&
5781                Instruction::isBinaryOp(E->getAltOpcode())) ||
5782               (Instruction::isCast(E->getOpcode()) &&
5783                Instruction::isCast(E->getAltOpcode())) ||
5784               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5785              "Invalid Shuffle Vector Operand");
5786       InstructionCost ScalarCost = 0;
5787       if (NeedToShuffleReuses) {
5788         for (unsigned Idx : E->ReuseShuffleIndices) {
5789           Instruction *I = cast<Instruction>(VL[Idx]);
5790           CommonCost -= TTI->getInstructionCost(I, CostKind);
5791         }
5792         for (Value *V : VL) {
5793           Instruction *I = cast<Instruction>(V);
5794           CommonCost += TTI->getInstructionCost(I, CostKind);
5795         }
5796       }
5797       for (Value *V : VL) {
5798         Instruction *I = cast<Instruction>(V);
5799         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5800         ScalarCost += TTI->getInstructionCost(I, CostKind);
5801       }
5802       // VecCost is equal to sum of the cost of creating 2 vectors
5803       // and the cost of creating shuffle.
5804       InstructionCost VecCost = 0;
5805       // Try to find the previous shuffle node with the same operands and same
5806       // main/alternate ops.
5807       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5808         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5809           if (TE.get() == E)
5810             break;
5811           if (TE->isAltShuffle() &&
5812               ((TE->getOpcode() == E->getOpcode() &&
5813                 TE->getAltOpcode() == E->getAltOpcode()) ||
5814                (TE->getOpcode() == E->getAltOpcode() &&
5815                 TE->getAltOpcode() == E->getOpcode())) &&
5816               TE->hasEqualOperands(*E))
5817             return true;
5818         }
5819         return false;
5820       };
5821       if (TryFindNodeWithEqualOperands()) {
5822         LLVM_DEBUG({
5823           dbgs() << "SLP: diamond match for alternate node found.\n";
5824           E->dump();
5825         });
5826         // No need to add new vector costs here since we're going to reuse
5827         // same main/alternate vector ops, just do different shuffling.
5828       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5829         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5830         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5831                                                CostKind);
5832       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5833         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5834                                           Builder.getInt1Ty(),
5835                                           CI0->getPredicate(), CostKind, VL0);
5836         VecCost += TTI->getCmpSelInstrCost(
5837             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5838             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5839             E->getAltOp());
5840       } else {
5841         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5842         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5843         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5844         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5845         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5846                                         TTI::CastContextHint::None, CostKind);
5847         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5848                                          TTI::CastContextHint::None, CostKind);
5849       }
5850 
5851       SmallVector<int> Mask;
5852       buildShuffleEntryMask(
5853           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5854           [E](Instruction *I) {
5855             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5856             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5857           },
5858           Mask);
5859       CommonCost =
5860           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5861       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5862       return CommonCost + VecCost - ScalarCost;
5863     }
5864     default:
5865       llvm_unreachable("Unknown instruction");
5866   }
5867 }
5868 
5869 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5870   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5871                     << VectorizableTree.size() << " is fully vectorizable .\n");
5872 
5873   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5874     SmallVector<int> Mask;
5875     return TE->State == TreeEntry::NeedToGather &&
5876            !any_of(TE->Scalars,
5877                    [this](Value *V) { return EphValues.contains(V); }) &&
5878            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5879             TE->Scalars.size() < Limit ||
5880             ((TE->getOpcode() == Instruction::ExtractElement ||
5881               all_of(TE->Scalars,
5882                      [](Value *V) {
5883                        return isa<ExtractElementInst, UndefValue>(V);
5884                      })) &&
5885              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5886             (TE->State == TreeEntry::NeedToGather &&
5887              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5888   };
5889 
5890   // We only handle trees of heights 1 and 2.
5891   if (VectorizableTree.size() == 1 &&
5892       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5893        (ForReduction &&
5894         AreVectorizableGathers(VectorizableTree[0].get(),
5895                                VectorizableTree[0]->Scalars.size()) &&
5896         VectorizableTree[0]->getVectorFactor() > 2)))
5897     return true;
5898 
5899   if (VectorizableTree.size() != 2)
5900     return false;
5901 
5902   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5903   // with the second gather nodes if they have less scalar operands rather than
5904   // the initial tree element (may be profitable to shuffle the second gather)
5905   // or they are extractelements, which form shuffle.
5906   SmallVector<int> Mask;
5907   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5908       AreVectorizableGathers(VectorizableTree[1].get(),
5909                              VectorizableTree[0]->Scalars.size()))
5910     return true;
5911 
5912   // Gathering cost would be too much for tiny trees.
5913   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5914       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5915        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5916     return false;
5917 
5918   return true;
5919 }
5920 
5921 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5922                                        TargetTransformInfo *TTI,
5923                                        bool MustMatchOrInst) {
5924   // Look past the root to find a source value. Arbitrarily follow the
5925   // path through operand 0 of any 'or'. Also, peek through optional
5926   // shift-left-by-multiple-of-8-bits.
5927   Value *ZextLoad = Root;
5928   const APInt *ShAmtC;
5929   bool FoundOr = false;
5930   while (!isa<ConstantExpr>(ZextLoad) &&
5931          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5932           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5933            ShAmtC->urem(8) == 0))) {
5934     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5935     ZextLoad = BinOp->getOperand(0);
5936     if (BinOp->getOpcode() == Instruction::Or)
5937       FoundOr = true;
5938   }
5939   // Check if the input is an extended load of the required or/shift expression.
5940   Value *Load;
5941   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5942       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5943     return false;
5944 
5945   // Require that the total load bit width is a legal integer type.
5946   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5947   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5948   Type *SrcTy = Load->getType();
5949   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5950   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5951     return false;
5952 
5953   // Everything matched - assume that we can fold the whole sequence using
5954   // load combining.
5955   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5956              << *(cast<Instruction>(Root)) << "\n");
5957 
5958   return true;
5959 }
5960 
5961 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5962   if (RdxKind != RecurKind::Or)
5963     return false;
5964 
5965   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5966   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5967   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5968                                     /* MatchOr */ false);
5969 }
5970 
5971 bool BoUpSLP::isLoadCombineCandidate() const {
5972   // Peek through a final sequence of stores and check if all operations are
5973   // likely to be load-combined.
5974   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5975   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5976     Value *X;
5977     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5978         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5979       return false;
5980   }
5981   return true;
5982 }
5983 
5984 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5985   // No need to vectorize inserts of gathered values.
5986   if (VectorizableTree.size() == 2 &&
5987       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5988       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5989     return true;
5990 
5991   // We can vectorize the tree if its size is greater than or equal to the
5992   // minimum size specified by the MinTreeSize command line option.
5993   if (VectorizableTree.size() >= MinTreeSize)
5994     return false;
5995 
5996   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5997   // can vectorize it if we can prove it fully vectorizable.
5998   if (isFullyVectorizableTinyTree(ForReduction))
5999     return false;
6000 
6001   assert(VectorizableTree.empty()
6002              ? ExternalUses.empty()
6003              : true && "We shouldn't have any external users");
6004 
6005   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
6006   // vectorizable.
6007   return true;
6008 }
6009 
6010 InstructionCost BoUpSLP::getSpillCost() const {
6011   // Walk from the bottom of the tree to the top, tracking which values are
6012   // live. When we see a call instruction that is not part of our tree,
6013   // query TTI to see if there is a cost to keeping values live over it
6014   // (for example, if spills and fills are required).
6015   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
6016   InstructionCost Cost = 0;
6017 
6018   SmallPtrSet<Instruction*, 4> LiveValues;
6019   Instruction *PrevInst = nullptr;
6020 
6021   // The entries in VectorizableTree are not necessarily ordered by their
6022   // position in basic blocks. Collect them and order them by dominance so later
6023   // instructions are guaranteed to be visited first. For instructions in
6024   // different basic blocks, we only scan to the beginning of the block, so
6025   // their order does not matter, as long as all instructions in a basic block
6026   // are grouped together. Using dominance ensures a deterministic order.
6027   SmallVector<Instruction *, 16> OrderedScalars;
6028   for (const auto &TEPtr : VectorizableTree) {
6029     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
6030     if (!Inst)
6031       continue;
6032     OrderedScalars.push_back(Inst);
6033   }
6034   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
6035     auto *NodeA = DT->getNode(A->getParent());
6036     auto *NodeB = DT->getNode(B->getParent());
6037     assert(NodeA && "Should only process reachable instructions");
6038     assert(NodeB && "Should only process reachable instructions");
6039     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
6040            "Different nodes should have different DFS numbers");
6041     if (NodeA != NodeB)
6042       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
6043     return B->comesBefore(A);
6044   });
6045 
6046   for (Instruction *Inst : OrderedScalars) {
6047     if (!PrevInst) {
6048       PrevInst = Inst;
6049       continue;
6050     }
6051 
6052     // Update LiveValues.
6053     LiveValues.erase(PrevInst);
6054     for (auto &J : PrevInst->operands()) {
6055       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6056         LiveValues.insert(cast<Instruction>(&*J));
6057     }
6058 
6059     LLVM_DEBUG({
6060       dbgs() << "SLP: #LV: " << LiveValues.size();
6061       for (auto *X : LiveValues)
6062         dbgs() << " " << X->getName();
6063       dbgs() << ", Looking at ";
6064       Inst->dump();
6065     });
6066 
6067     // Now find the sequence of instructions between PrevInst and Inst.
6068     unsigned NumCalls = 0;
6069     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6070                                  PrevInstIt =
6071                                      PrevInst->getIterator().getReverse();
6072     while (InstIt != PrevInstIt) {
6073       if (PrevInstIt == PrevInst->getParent()->rend()) {
6074         PrevInstIt = Inst->getParent()->rbegin();
6075         continue;
6076       }
6077 
6078       // Debug information does not impact spill cost.
6079       if ((isa<CallInst>(&*PrevInstIt) &&
6080            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6081           &*PrevInstIt != PrevInst)
6082         NumCalls++;
6083 
6084       ++PrevInstIt;
6085     }
6086 
6087     if (NumCalls) {
6088       SmallVector<Type*, 4> V;
6089       for (auto *II : LiveValues) {
6090         auto *ScalarTy = II->getType();
6091         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6092           ScalarTy = VectorTy->getElementType();
6093         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6094       }
6095       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6096     }
6097 
6098     PrevInst = Inst;
6099   }
6100 
6101   return Cost;
6102 }
6103 
6104 /// Check if two insertelement instructions are from the same buildvector.
6105 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6106                                             InsertElementInst *V) {
6107   // Instructions must be from the same basic blocks.
6108   if (VU->getParent() != V->getParent())
6109     return false;
6110   // Checks if 2 insertelements are from the same buildvector.
6111   if (VU->getType() != V->getType())
6112     return false;
6113   // Multiple used inserts are separate nodes.
6114   if (!VU->hasOneUse() && !V->hasOneUse())
6115     return false;
6116   auto *IE1 = VU;
6117   auto *IE2 = V;
6118   // Go through the vector operand of insertelement instructions trying to find
6119   // either VU as the original vector for IE2 or V as the original vector for
6120   // IE1.
6121   do {
6122     if (IE2 == VU || IE1 == V)
6123       return true;
6124     if (IE1) {
6125       if (IE1 != VU && !IE1->hasOneUse())
6126         IE1 = nullptr;
6127       else
6128         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6129     }
6130     if (IE2) {
6131       if (IE2 != V && !IE2->hasOneUse())
6132         IE2 = nullptr;
6133       else
6134         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6135     }
6136   } while (IE1 || IE2);
6137   return false;
6138 }
6139 
6140 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6141   InstructionCost Cost = 0;
6142   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6143                     << VectorizableTree.size() << ".\n");
6144 
6145   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6146 
6147   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6148     TreeEntry &TE = *VectorizableTree[I];
6149 
6150     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6151     Cost += C;
6152     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6153                       << " for bundle that starts with " << *TE.Scalars[0]
6154                       << ".\n"
6155                       << "SLP: Current total cost = " << Cost << "\n");
6156   }
6157 
6158   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6159   InstructionCost ExtractCost = 0;
6160   SmallVector<unsigned> VF;
6161   SmallVector<SmallVector<int>> ShuffleMask;
6162   SmallVector<Value *> FirstUsers;
6163   SmallVector<APInt> DemandedElts;
6164   for (ExternalUser &EU : ExternalUses) {
6165     // We only add extract cost once for the same scalar.
6166     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6167         !ExtractCostCalculated.insert(EU.Scalar).second)
6168       continue;
6169 
6170     // Uses by ephemeral values are free (because the ephemeral value will be
6171     // removed prior to code generation, and so the extraction will be
6172     // removed as well).
6173     if (EphValues.count(EU.User))
6174       continue;
6175 
6176     // No extract cost for vector "scalar"
6177     if (isa<FixedVectorType>(EU.Scalar->getType()))
6178       continue;
6179 
6180     // Already counted the cost for external uses when tried to adjust the cost
6181     // for extractelements, no need to add it again.
6182     if (isa<ExtractElementInst>(EU.Scalar))
6183       continue;
6184 
6185     // If found user is an insertelement, do not calculate extract cost but try
6186     // to detect it as a final shuffled/identity match.
6187     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6188       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6189         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6190         if (InsertIdx) {
6191           auto *It = find_if(FirstUsers, [VU](Value *V) {
6192             return areTwoInsertFromSameBuildVector(VU,
6193                                                    cast<InsertElementInst>(V));
6194           });
6195           int VecId = -1;
6196           if (It == FirstUsers.end()) {
6197             VF.push_back(FTy->getNumElements());
6198             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6199             // Find the insertvector, vectorized in tree, if any.
6200             Value *Base = VU;
6201             while (isa<InsertElementInst>(Base)) {
6202               // Build the mask for the vectorized insertelement instructions.
6203               if (const TreeEntry *E = getTreeEntry(Base)) {
6204                 VU = cast<InsertElementInst>(Base);
6205                 do {
6206                   int Idx = E->findLaneForValue(Base);
6207                   ShuffleMask.back()[Idx] = Idx;
6208                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6209                 } while (E == getTreeEntry(Base));
6210                 break;
6211               }
6212               Base = cast<InsertElementInst>(Base)->getOperand(0);
6213             }
6214             FirstUsers.push_back(VU);
6215             DemandedElts.push_back(APInt::getZero(VF.back()));
6216             VecId = FirstUsers.size() - 1;
6217           } else {
6218             VecId = std::distance(FirstUsers.begin(), It);
6219           }
6220           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6221           DemandedElts[VecId].setBit(*InsertIdx);
6222           continue;
6223         }
6224       }
6225     }
6226 
6227     // If we plan to rewrite the tree in a smaller type, we will need to sign
6228     // extend the extracted value back to the original type. Here, we account
6229     // for the extract and the added cost of the sign extend if needed.
6230     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6231     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6232     if (MinBWs.count(ScalarRoot)) {
6233       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6234       auto Extend =
6235           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6236       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6237       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6238                                                    VecTy, EU.Lane);
6239     } else {
6240       ExtractCost +=
6241           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6242     }
6243   }
6244 
6245   InstructionCost SpillCost = getSpillCost();
6246   Cost += SpillCost + ExtractCost;
6247   if (FirstUsers.size() == 1) {
6248     int Limit = ShuffleMask.front().size() * 2;
6249     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6250         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6251       InstructionCost C = TTI->getShuffleCost(
6252           TTI::SK_PermuteSingleSrc,
6253           cast<FixedVectorType>(FirstUsers.front()->getType()),
6254           ShuffleMask.front());
6255       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6256                         << " for final shuffle of insertelement external users "
6257                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6258                         << "SLP: Current total cost = " << Cost << "\n");
6259       Cost += C;
6260     }
6261     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6262         cast<FixedVectorType>(FirstUsers.front()->getType()),
6263         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6264     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6265                       << " for insertelements gather.\n"
6266                       << "SLP: Current total cost = " << Cost << "\n");
6267     Cost -= InsertCost;
6268   } else if (FirstUsers.size() >= 2) {
6269     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6270     // Combined masks of the first 2 vectors.
6271     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6272     copy(ShuffleMask.front(), CombinedMask.begin());
6273     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6274     auto *VecTy = FixedVectorType::get(
6275         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6276         MaxVF);
6277     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6278       if (ShuffleMask[1][I] != UndefMaskElem) {
6279         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6280         CombinedDemandedElts.setBit(I);
6281       }
6282     }
6283     InstructionCost C =
6284         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6285     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6286                       << " for final shuffle of vector node and external "
6287                          "insertelement users "
6288                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6289                       << "SLP: Current total cost = " << Cost << "\n");
6290     Cost += C;
6291     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6292         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6293     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6294                       << " for insertelements gather.\n"
6295                       << "SLP: Current total cost = " << Cost << "\n");
6296     Cost -= InsertCost;
6297     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6298       // Other elements - permutation of 2 vectors (the initial one and the
6299       // next Ith incoming vector).
6300       unsigned VF = ShuffleMask[I].size();
6301       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6302         int Mask = ShuffleMask[I][Idx];
6303         if (Mask != UndefMaskElem)
6304           CombinedMask[Idx] = MaxVF + Mask;
6305         else if (CombinedMask[Idx] != UndefMaskElem)
6306           CombinedMask[Idx] = Idx;
6307       }
6308       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6309         if (CombinedMask[Idx] != UndefMaskElem)
6310           CombinedMask[Idx] = Idx;
6311       InstructionCost C =
6312           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6313       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6314                         << " for final shuffle of vector node and external "
6315                            "insertelement users "
6316                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6317                         << "SLP: Current total cost = " << Cost << "\n");
6318       Cost += C;
6319       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6320           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6321           /*Insert*/ true, /*Extract*/ false);
6322       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6323                         << " for insertelements gather.\n"
6324                         << "SLP: Current total cost = " << Cost << "\n");
6325       Cost -= InsertCost;
6326     }
6327   }
6328 
6329 #ifndef NDEBUG
6330   SmallString<256> Str;
6331   {
6332     raw_svector_ostream OS(Str);
6333     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6334        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6335        << "SLP: Total Cost = " << Cost << ".\n";
6336   }
6337   LLVM_DEBUG(dbgs() << Str);
6338   if (ViewSLPTree)
6339     ViewGraph(this, "SLP" + F->getName(), false, Str);
6340 #endif
6341 
6342   return Cost;
6343 }
6344 
6345 Optional<TargetTransformInfo::ShuffleKind>
6346 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6347                                SmallVectorImpl<const TreeEntry *> &Entries) {
6348   // TODO: currently checking only for Scalars in the tree entry, need to count
6349   // reused elements too for better cost estimation.
6350   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6351   Entries.clear();
6352   // Build a lists of values to tree entries.
6353   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6354   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6355     if (EntryPtr.get() == TE)
6356       break;
6357     if (EntryPtr->State != TreeEntry::NeedToGather)
6358       continue;
6359     for (Value *V : EntryPtr->Scalars)
6360       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6361   }
6362   // Find all tree entries used by the gathered values. If no common entries
6363   // found - not a shuffle.
6364   // Here we build a set of tree nodes for each gathered value and trying to
6365   // find the intersection between these sets. If we have at least one common
6366   // tree node for each gathered value - we have just a permutation of the
6367   // single vector. If we have 2 different sets, we're in situation where we
6368   // have a permutation of 2 input vectors.
6369   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6370   DenseMap<Value *, int> UsedValuesEntry;
6371   for (Value *V : TE->Scalars) {
6372     if (isa<UndefValue>(V))
6373       continue;
6374     // Build a list of tree entries where V is used.
6375     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6376     auto It = ValueToTEs.find(V);
6377     if (It != ValueToTEs.end())
6378       VToTEs = It->second;
6379     if (const TreeEntry *VTE = getTreeEntry(V))
6380       VToTEs.insert(VTE);
6381     if (VToTEs.empty())
6382       return None;
6383     if (UsedTEs.empty()) {
6384       // The first iteration, just insert the list of nodes to vector.
6385       UsedTEs.push_back(VToTEs);
6386     } else {
6387       // Need to check if there are any previously used tree nodes which use V.
6388       // If there are no such nodes, consider that we have another one input
6389       // vector.
6390       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6391       unsigned Idx = 0;
6392       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6393         // Do we have a non-empty intersection of previously listed tree entries
6394         // and tree entries using current V?
6395         set_intersect(VToTEs, Set);
6396         if (!VToTEs.empty()) {
6397           // Yes, write the new subset and continue analysis for the next
6398           // scalar.
6399           Set.swap(VToTEs);
6400           break;
6401         }
6402         VToTEs = SavedVToTEs;
6403         ++Idx;
6404       }
6405       // No non-empty intersection found - need to add a second set of possible
6406       // source vectors.
6407       if (Idx == UsedTEs.size()) {
6408         // If the number of input vectors is greater than 2 - not a permutation,
6409         // fallback to the regular gather.
6410         if (UsedTEs.size() == 2)
6411           return None;
6412         UsedTEs.push_back(SavedVToTEs);
6413         Idx = UsedTEs.size() - 1;
6414       }
6415       UsedValuesEntry.try_emplace(V, Idx);
6416     }
6417   }
6418 
6419   unsigned VF = 0;
6420   if (UsedTEs.size() == 1) {
6421     // Try to find the perfect match in another gather node at first.
6422     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6423       return EntryPtr->isSame(TE->Scalars);
6424     });
6425     if (It != UsedTEs.front().end()) {
6426       Entries.push_back(*It);
6427       std::iota(Mask.begin(), Mask.end(), 0);
6428       return TargetTransformInfo::SK_PermuteSingleSrc;
6429     }
6430     // No perfect match, just shuffle, so choose the first tree node.
6431     Entries.push_back(*UsedTEs.front().begin());
6432   } else {
6433     // Try to find nodes with the same vector factor.
6434     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6435     DenseMap<int, const TreeEntry *> VFToTE;
6436     for (const TreeEntry *TE : UsedTEs.front())
6437       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6438     for (const TreeEntry *TE : UsedTEs.back()) {
6439       auto It = VFToTE.find(TE->getVectorFactor());
6440       if (It != VFToTE.end()) {
6441         VF = It->first;
6442         Entries.push_back(It->second);
6443         Entries.push_back(TE);
6444         break;
6445       }
6446     }
6447     // No 2 source vectors with the same vector factor - give up and do regular
6448     // gather.
6449     if (Entries.empty())
6450       return None;
6451   }
6452 
6453   // Build a shuffle mask for better cost estimation and vector emission.
6454   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6455     Value *V = TE->Scalars[I];
6456     if (isa<UndefValue>(V))
6457       continue;
6458     unsigned Idx = UsedValuesEntry.lookup(V);
6459     const TreeEntry *VTE = Entries[Idx];
6460     int FoundLane = VTE->findLaneForValue(V);
6461     Mask[I] = Idx * VF + FoundLane;
6462     // Extra check required by isSingleSourceMaskImpl function (called by
6463     // ShuffleVectorInst::isSingleSourceMask).
6464     if (Mask[I] >= 2 * E)
6465       return None;
6466   }
6467   switch (Entries.size()) {
6468   case 1:
6469     return TargetTransformInfo::SK_PermuteSingleSrc;
6470   case 2:
6471     return TargetTransformInfo::SK_PermuteTwoSrc;
6472   default:
6473     break;
6474   }
6475   return None;
6476 }
6477 
6478 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6479                                        const APInt &ShuffledIndices,
6480                                        bool NeedToShuffle) const {
6481   InstructionCost Cost =
6482       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6483                                     /*Extract*/ false);
6484   if (NeedToShuffle)
6485     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6486   return Cost;
6487 }
6488 
6489 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6490   // Find the type of the operands in VL.
6491   Type *ScalarTy = VL[0]->getType();
6492   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6493     ScalarTy = SI->getValueOperand()->getType();
6494   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6495   bool DuplicateNonConst = false;
6496   // Find the cost of inserting/extracting values from the vector.
6497   // Check if the same elements are inserted several times and count them as
6498   // shuffle candidates.
6499   APInt ShuffledElements = APInt::getZero(VL.size());
6500   DenseSet<Value *> UniqueElements;
6501   // Iterate in reverse order to consider insert elements with the high cost.
6502   for (unsigned I = VL.size(); I > 0; --I) {
6503     unsigned Idx = I - 1;
6504     // No need to shuffle duplicates for constants.
6505     if (isConstant(VL[Idx])) {
6506       ShuffledElements.setBit(Idx);
6507       continue;
6508     }
6509     if (!UniqueElements.insert(VL[Idx]).second) {
6510       DuplicateNonConst = true;
6511       ShuffledElements.setBit(Idx);
6512     }
6513   }
6514   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6515 }
6516 
6517 // Perform operand reordering on the instructions in VL and return the reordered
6518 // operands in Left and Right.
6519 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6520                                              SmallVectorImpl<Value *> &Left,
6521                                              SmallVectorImpl<Value *> &Right,
6522                                              const DataLayout &DL,
6523                                              ScalarEvolution &SE,
6524                                              const BoUpSLP &R) {
6525   if (VL.empty())
6526     return;
6527   VLOperands Ops(VL, DL, SE, R);
6528   // Reorder the operands in place.
6529   Ops.reorder();
6530   Left = Ops.getVL(0);
6531   Right = Ops.getVL(1);
6532 }
6533 
6534 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6535   // Get the basic block this bundle is in. All instructions in the bundle
6536   // should be in this block.
6537   auto *Front = E->getMainOp();
6538   auto *BB = Front->getParent();
6539   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6540     auto *I = cast<Instruction>(V);
6541     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6542   }));
6543 
6544   auto &&FindLastInst = [E, Front]() {
6545     Instruction *LastInst = Front;
6546     for (Value *V : E->Scalars) {
6547       auto *I = dyn_cast<Instruction>(V);
6548       if (!I)
6549         continue;
6550       if (LastInst->comesBefore(I))
6551         LastInst = I;
6552     }
6553     return LastInst;
6554   };
6555 
6556   auto &&FindFirstInst = [E, Front]() {
6557     Instruction *FirstInst = Front;
6558     for (Value *V : E->Scalars) {
6559       auto *I = dyn_cast<Instruction>(V);
6560       if (!I)
6561         continue;
6562       if (I->comesBefore(FirstInst))
6563         FirstInst = I;
6564     }
6565     return FirstInst;
6566   };
6567 
6568   // Set the insert point to the beginning of the basic block if the entry
6569   // should not be scheduled.
6570   if (E->State != TreeEntry::NeedToGather &&
6571       doesNotNeedToSchedule(E->Scalars)) {
6572     BasicBlock::iterator InsertPt;
6573     if (all_of(E->Scalars, isUsedOutsideBlock))
6574       InsertPt = FindLastInst()->getIterator();
6575     else
6576       InsertPt = FindFirstInst()->getIterator();
6577     Builder.SetInsertPoint(BB, InsertPt);
6578     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6579     return;
6580   }
6581 
6582   // The last instruction in the bundle in program order.
6583   Instruction *LastInst = nullptr;
6584 
6585   // Find the last instruction. The common case should be that BB has been
6586   // scheduled, and the last instruction is VL.back(). So we start with
6587   // VL.back() and iterate over schedule data until we reach the end of the
6588   // bundle. The end of the bundle is marked by null ScheduleData.
6589   if (BlocksSchedules.count(BB)) {
6590     Value *V = E->isOneOf(E->Scalars.back());
6591     if (doesNotNeedToBeScheduled(V))
6592       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6593     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6594     if (Bundle && Bundle->isPartOfBundle())
6595       for (; Bundle; Bundle = Bundle->NextInBundle)
6596         if (Bundle->OpValue == Bundle->Inst)
6597           LastInst = Bundle->Inst;
6598   }
6599 
6600   // LastInst can still be null at this point if there's either not an entry
6601   // for BB in BlocksSchedules or there's no ScheduleData available for
6602   // VL.back(). This can be the case if buildTree_rec aborts for various
6603   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6604   // size is reached, etc.). ScheduleData is initialized in the scheduling
6605   // "dry-run".
6606   //
6607   // If this happens, we can still find the last instruction by brute force. We
6608   // iterate forwards from Front (inclusive) until we either see all
6609   // instructions in the bundle or reach the end of the block. If Front is the
6610   // last instruction in program order, LastInst will be set to Front, and we
6611   // will visit all the remaining instructions in the block.
6612   //
6613   // One of the reasons we exit early from buildTree_rec is to place an upper
6614   // bound on compile-time. Thus, taking an additional compile-time hit here is
6615   // not ideal. However, this should be exceedingly rare since it requires that
6616   // we both exit early from buildTree_rec and that the bundle be out-of-order
6617   // (causing us to iterate all the way to the end of the block).
6618   if (!LastInst)
6619     LastInst = FindLastInst();
6620   assert(LastInst && "Failed to find last instruction in bundle");
6621 
6622   // Set the insertion point after the last instruction in the bundle. Set the
6623   // debug location to Front.
6624   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6625   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6626 }
6627 
6628 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6629   // List of instructions/lanes from current block and/or the blocks which are
6630   // part of the current loop. These instructions will be inserted at the end to
6631   // make it possible to optimize loops and hoist invariant instructions out of
6632   // the loops body with better chances for success.
6633   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6634   SmallSet<int, 4> PostponedIndices;
6635   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6636   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6637     SmallPtrSet<BasicBlock *, 4> Visited;
6638     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6639       InsertBB = InsertBB->getSinglePredecessor();
6640     return InsertBB && InsertBB == InstBB;
6641   };
6642   for (int I = 0, E = VL.size(); I < E; ++I) {
6643     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6644       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6645            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6646           PostponedIndices.insert(I).second)
6647         PostponedInsts.emplace_back(Inst, I);
6648   }
6649 
6650   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6651     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6652     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6653     if (!InsElt)
6654       return Vec;
6655     GatherShuffleSeq.insert(InsElt);
6656     CSEBlocks.insert(InsElt->getParent());
6657     // Add to our 'need-to-extract' list.
6658     if (TreeEntry *Entry = getTreeEntry(V)) {
6659       // Find which lane we need to extract.
6660       unsigned FoundLane = Entry->findLaneForValue(V);
6661       ExternalUses.emplace_back(V, InsElt, FoundLane);
6662     }
6663     return Vec;
6664   };
6665   Value *Val0 =
6666       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6667   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6668   Value *Vec = PoisonValue::get(VecTy);
6669   SmallVector<int> NonConsts;
6670   // Insert constant values at first.
6671   for (int I = 0, E = VL.size(); I < E; ++I) {
6672     if (PostponedIndices.contains(I))
6673       continue;
6674     if (!isConstant(VL[I])) {
6675       NonConsts.push_back(I);
6676       continue;
6677     }
6678     Vec = CreateInsertElement(Vec, VL[I], I);
6679   }
6680   // Insert non-constant values.
6681   for (int I : NonConsts)
6682     Vec = CreateInsertElement(Vec, VL[I], I);
6683   // Append instructions, which are/may be part of the loop, in the end to make
6684   // it possible to hoist non-loop-based instructions.
6685   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6686     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6687 
6688   return Vec;
6689 }
6690 
6691 namespace {
6692 /// Merges shuffle masks and emits final shuffle instruction, if required.
6693 class ShuffleInstructionBuilder {
6694   IRBuilderBase &Builder;
6695   const unsigned VF = 0;
6696   bool IsFinalized = false;
6697   SmallVector<int, 4> Mask;
6698   /// Holds all of the instructions that we gathered.
6699   SetVector<Instruction *> &GatherShuffleSeq;
6700   /// A list of blocks that we are going to CSE.
6701   SetVector<BasicBlock *> &CSEBlocks;
6702 
6703 public:
6704   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6705                             SetVector<Instruction *> &GatherShuffleSeq,
6706                             SetVector<BasicBlock *> &CSEBlocks)
6707       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6708         CSEBlocks(CSEBlocks) {}
6709 
6710   /// Adds a mask, inverting it before applying.
6711   void addInversedMask(ArrayRef<unsigned> SubMask) {
6712     if (SubMask.empty())
6713       return;
6714     SmallVector<int, 4> NewMask;
6715     inversePermutation(SubMask, NewMask);
6716     addMask(NewMask);
6717   }
6718 
6719   /// Functions adds masks, merging them into  single one.
6720   void addMask(ArrayRef<unsigned> SubMask) {
6721     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6722     addMask(NewMask);
6723   }
6724 
6725   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6726 
6727   Value *finalize(Value *V) {
6728     IsFinalized = true;
6729     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6730     if (VF == ValueVF && Mask.empty())
6731       return V;
6732     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6733     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6734     addMask(NormalizedMask);
6735 
6736     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6737       return V;
6738     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6739     if (auto *I = dyn_cast<Instruction>(Vec)) {
6740       GatherShuffleSeq.insert(I);
6741       CSEBlocks.insert(I->getParent());
6742     }
6743     return Vec;
6744   }
6745 
6746   ~ShuffleInstructionBuilder() {
6747     assert((IsFinalized || Mask.empty()) &&
6748            "Shuffle construction must be finalized.");
6749   }
6750 };
6751 } // namespace
6752 
6753 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6754   const unsigned VF = VL.size();
6755   InstructionsState S = getSameOpcode(VL);
6756   if (S.getOpcode()) {
6757     if (TreeEntry *E = getTreeEntry(S.OpValue))
6758       if (E->isSame(VL)) {
6759         Value *V = vectorizeTree(E);
6760         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6761           if (!E->ReuseShuffleIndices.empty()) {
6762             // Reshuffle to get only unique values.
6763             // If some of the scalars are duplicated in the vectorization tree
6764             // entry, we do not vectorize them but instead generate a mask for
6765             // the reuses. But if there are several users of the same entry,
6766             // they may have different vectorization factors. This is especially
6767             // important for PHI nodes. In this case, we need to adapt the
6768             // resulting instruction for the user vectorization factor and have
6769             // to reshuffle it again to take only unique elements of the vector.
6770             // Without this code the function incorrectly returns reduced vector
6771             // instruction with the same elements, not with the unique ones.
6772 
6773             // block:
6774             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6775             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6776             // ... (use %2)
6777             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6778             // br %block
6779             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6780             SmallSet<int, 4> UsedIdxs;
6781             int Pos = 0;
6782             int Sz = VL.size();
6783             for (int Idx : E->ReuseShuffleIndices) {
6784               if (Idx != Sz && Idx != UndefMaskElem &&
6785                   UsedIdxs.insert(Idx).second)
6786                 UniqueIdxs[Idx] = Pos;
6787               ++Pos;
6788             }
6789             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6790                                             "less than original vector size.");
6791             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6792             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6793           } else {
6794             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6795                    "Expected vectorization factor less "
6796                    "than original vector size.");
6797             SmallVector<int> UniformMask(VF, 0);
6798             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6799             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6800           }
6801           if (auto *I = dyn_cast<Instruction>(V)) {
6802             GatherShuffleSeq.insert(I);
6803             CSEBlocks.insert(I->getParent());
6804           }
6805         }
6806         return V;
6807       }
6808   }
6809 
6810   // Can't vectorize this, so simply build a new vector with each lane
6811   // corresponding to the requested value.
6812   return createBuildVector(VL);
6813 }
6814 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6815   unsigned VF = VL.size();
6816   // Exploit possible reuse of values across lanes.
6817   SmallVector<int> ReuseShuffleIndicies;
6818   SmallVector<Value *> UniqueValues;
6819   if (VL.size() > 2) {
6820     DenseMap<Value *, unsigned> UniquePositions;
6821     unsigned NumValues =
6822         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6823                                     return !isa<UndefValue>(V);
6824                                   }).base());
6825     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6826     int UniqueVals = 0;
6827     for (Value *V : VL.drop_back(VL.size() - VF)) {
6828       if (isa<UndefValue>(V)) {
6829         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6830         continue;
6831       }
6832       if (isConstant(V)) {
6833         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6834         UniqueValues.emplace_back(V);
6835         continue;
6836       }
6837       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6838       ReuseShuffleIndicies.emplace_back(Res.first->second);
6839       if (Res.second) {
6840         UniqueValues.emplace_back(V);
6841         ++UniqueVals;
6842       }
6843     }
6844     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6845       // Emit pure splat vector.
6846       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6847                                   UndefMaskElem);
6848     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6849       ReuseShuffleIndicies.clear();
6850       UniqueValues.clear();
6851       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6852     }
6853     UniqueValues.append(VF - UniqueValues.size(),
6854                         PoisonValue::get(VL[0]->getType()));
6855     VL = UniqueValues;
6856   }
6857 
6858   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6859                                            CSEBlocks);
6860   Value *Vec = gather(VL);
6861   if (!ReuseShuffleIndicies.empty()) {
6862     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6863     Vec = ShuffleBuilder.finalize(Vec);
6864   }
6865   return Vec;
6866 }
6867 
6868 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6869   IRBuilder<>::InsertPointGuard Guard(Builder);
6870 
6871   if (E->VectorizedValue) {
6872     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6873     return E->VectorizedValue;
6874   }
6875 
6876   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6877   unsigned VF = E->getVectorFactor();
6878   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6879                                            CSEBlocks);
6880   if (E->State == TreeEntry::NeedToGather) {
6881     if (E->getMainOp())
6882       setInsertPointAfterBundle(E);
6883     Value *Vec;
6884     SmallVector<int> Mask;
6885     SmallVector<const TreeEntry *> Entries;
6886     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6887         isGatherShuffledEntry(E, Mask, Entries);
6888     if (Shuffle.hasValue()) {
6889       assert((Entries.size() == 1 || Entries.size() == 2) &&
6890              "Expected shuffle of 1 or 2 entries.");
6891       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6892                                         Entries.back()->VectorizedValue, Mask);
6893       if (auto *I = dyn_cast<Instruction>(Vec)) {
6894         GatherShuffleSeq.insert(I);
6895         CSEBlocks.insert(I->getParent());
6896       }
6897     } else {
6898       Vec = gather(E->Scalars);
6899     }
6900     if (NeedToShuffleReuses) {
6901       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6902       Vec = ShuffleBuilder.finalize(Vec);
6903     }
6904     E->VectorizedValue = Vec;
6905     return Vec;
6906   }
6907 
6908   assert((E->State == TreeEntry::Vectorize ||
6909           E->State == TreeEntry::ScatterVectorize) &&
6910          "Unhandled state");
6911   unsigned ShuffleOrOp =
6912       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6913   Instruction *VL0 = E->getMainOp();
6914   Type *ScalarTy = VL0->getType();
6915   if (auto *Store = dyn_cast<StoreInst>(VL0))
6916     ScalarTy = Store->getValueOperand()->getType();
6917   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6918     ScalarTy = IE->getOperand(1)->getType();
6919   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6920   switch (ShuffleOrOp) {
6921     case Instruction::PHI: {
6922       assert(
6923           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6924           "PHI reordering is free.");
6925       auto *PH = cast<PHINode>(VL0);
6926       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6927       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6928       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6929       Value *V = NewPhi;
6930 
6931       // Adjust insertion point once all PHI's have been generated.
6932       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6933       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6934 
6935       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6936       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6937       V = ShuffleBuilder.finalize(V);
6938 
6939       E->VectorizedValue = V;
6940 
6941       // PHINodes may have multiple entries from the same block. We want to
6942       // visit every block once.
6943       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6944 
6945       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6946         ValueList Operands;
6947         BasicBlock *IBB = PH->getIncomingBlock(i);
6948 
6949         if (!VisitedBBs.insert(IBB).second) {
6950           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6951           continue;
6952         }
6953 
6954         Builder.SetInsertPoint(IBB->getTerminator());
6955         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6956         Value *Vec = vectorizeTree(E->getOperand(i));
6957         NewPhi->addIncoming(Vec, IBB);
6958       }
6959 
6960       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6961              "Invalid number of incoming values");
6962       return V;
6963     }
6964 
6965     case Instruction::ExtractElement: {
6966       Value *V = E->getSingleOperand(0);
6967       Builder.SetInsertPoint(VL0);
6968       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6969       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6970       V = ShuffleBuilder.finalize(V);
6971       E->VectorizedValue = V;
6972       return V;
6973     }
6974     case Instruction::ExtractValue: {
6975       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6976       Builder.SetInsertPoint(LI);
6977       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6978       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6979       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6980       Value *NewV = propagateMetadata(V, E->Scalars);
6981       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6982       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6983       NewV = ShuffleBuilder.finalize(NewV);
6984       E->VectorizedValue = NewV;
6985       return NewV;
6986     }
6987     case Instruction::InsertElement: {
6988       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6989       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6990       Value *V = vectorizeTree(E->getOperand(1));
6991 
6992       // Create InsertVector shuffle if necessary
6993       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6994         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6995       }));
6996       const unsigned NumElts =
6997           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6998       const unsigned NumScalars = E->Scalars.size();
6999 
7000       unsigned Offset = *getInsertIndex(VL0);
7001       assert(Offset < NumElts && "Failed to find vector index offset");
7002 
7003       // Create shuffle to resize vector
7004       SmallVector<int> Mask;
7005       if (!E->ReorderIndices.empty()) {
7006         inversePermutation(E->ReorderIndices, Mask);
7007         Mask.append(NumElts - NumScalars, UndefMaskElem);
7008       } else {
7009         Mask.assign(NumElts, UndefMaskElem);
7010         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
7011       }
7012       // Create InsertVector shuffle if necessary
7013       bool IsIdentity = true;
7014       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
7015       Mask.swap(PrevMask);
7016       for (unsigned I = 0; I < NumScalars; ++I) {
7017         Value *Scalar = E->Scalars[PrevMask[I]];
7018         unsigned InsertIdx = *getInsertIndex(Scalar);
7019         IsIdentity &= InsertIdx - Offset == I;
7020         Mask[InsertIdx - Offset] = I;
7021       }
7022       if (!IsIdentity || NumElts != NumScalars) {
7023         V = Builder.CreateShuffleVector(V, Mask);
7024         if (auto *I = dyn_cast<Instruction>(V)) {
7025           GatherShuffleSeq.insert(I);
7026           CSEBlocks.insert(I->getParent());
7027         }
7028       }
7029 
7030       if ((!IsIdentity || Offset != 0 ||
7031            !isUndefVector(FirstInsert->getOperand(0))) &&
7032           NumElts != NumScalars) {
7033         SmallVector<int> InsertMask(NumElts);
7034         std::iota(InsertMask.begin(), InsertMask.end(), 0);
7035         for (unsigned I = 0; I < NumElts; I++) {
7036           if (Mask[I] != UndefMaskElem)
7037             InsertMask[Offset + I] = NumElts + I;
7038         }
7039 
7040         V = Builder.CreateShuffleVector(
7041             FirstInsert->getOperand(0), V, InsertMask,
7042             cast<Instruction>(E->Scalars.back())->getName());
7043         if (auto *I = dyn_cast<Instruction>(V)) {
7044           GatherShuffleSeq.insert(I);
7045           CSEBlocks.insert(I->getParent());
7046         }
7047       }
7048 
7049       ++NumVectorInstructions;
7050       E->VectorizedValue = V;
7051       return V;
7052     }
7053     case Instruction::ZExt:
7054     case Instruction::SExt:
7055     case Instruction::FPToUI:
7056     case Instruction::FPToSI:
7057     case Instruction::FPExt:
7058     case Instruction::PtrToInt:
7059     case Instruction::IntToPtr:
7060     case Instruction::SIToFP:
7061     case Instruction::UIToFP:
7062     case Instruction::Trunc:
7063     case Instruction::FPTrunc:
7064     case Instruction::BitCast: {
7065       setInsertPointAfterBundle(E);
7066 
7067       Value *InVec = vectorizeTree(E->getOperand(0));
7068 
7069       if (E->VectorizedValue) {
7070         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7071         return E->VectorizedValue;
7072       }
7073 
7074       auto *CI = cast<CastInst>(VL0);
7075       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7076       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7077       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7078       V = ShuffleBuilder.finalize(V);
7079 
7080       E->VectorizedValue = V;
7081       ++NumVectorInstructions;
7082       return V;
7083     }
7084     case Instruction::FCmp:
7085     case Instruction::ICmp: {
7086       setInsertPointAfterBundle(E);
7087 
7088       Value *L = vectorizeTree(E->getOperand(0));
7089       Value *R = vectorizeTree(E->getOperand(1));
7090 
7091       if (E->VectorizedValue) {
7092         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7093         return E->VectorizedValue;
7094       }
7095 
7096       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7097       Value *V = Builder.CreateCmp(P0, L, R);
7098       propagateIRFlags(V, E->Scalars, VL0);
7099       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7100       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7101       V = ShuffleBuilder.finalize(V);
7102 
7103       E->VectorizedValue = V;
7104       ++NumVectorInstructions;
7105       return V;
7106     }
7107     case Instruction::Select: {
7108       setInsertPointAfterBundle(E);
7109 
7110       Value *Cond = vectorizeTree(E->getOperand(0));
7111       Value *True = vectorizeTree(E->getOperand(1));
7112       Value *False = vectorizeTree(E->getOperand(2));
7113 
7114       if (E->VectorizedValue) {
7115         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7116         return E->VectorizedValue;
7117       }
7118 
7119       Value *V = Builder.CreateSelect(Cond, True, False);
7120       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7121       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7122       V = ShuffleBuilder.finalize(V);
7123 
7124       E->VectorizedValue = V;
7125       ++NumVectorInstructions;
7126       return V;
7127     }
7128     case Instruction::FNeg: {
7129       setInsertPointAfterBundle(E);
7130 
7131       Value *Op = vectorizeTree(E->getOperand(0));
7132 
7133       if (E->VectorizedValue) {
7134         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7135         return E->VectorizedValue;
7136       }
7137 
7138       Value *V = Builder.CreateUnOp(
7139           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7140       propagateIRFlags(V, E->Scalars, VL0);
7141       if (auto *I = dyn_cast<Instruction>(V))
7142         V = propagateMetadata(I, E->Scalars);
7143 
7144       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7145       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7146       V = ShuffleBuilder.finalize(V);
7147 
7148       E->VectorizedValue = V;
7149       ++NumVectorInstructions;
7150 
7151       return V;
7152     }
7153     case Instruction::Add:
7154     case Instruction::FAdd:
7155     case Instruction::Sub:
7156     case Instruction::FSub:
7157     case Instruction::Mul:
7158     case Instruction::FMul:
7159     case Instruction::UDiv:
7160     case Instruction::SDiv:
7161     case Instruction::FDiv:
7162     case Instruction::URem:
7163     case Instruction::SRem:
7164     case Instruction::FRem:
7165     case Instruction::Shl:
7166     case Instruction::LShr:
7167     case Instruction::AShr:
7168     case Instruction::And:
7169     case Instruction::Or:
7170     case Instruction::Xor: {
7171       setInsertPointAfterBundle(E);
7172 
7173       Value *LHS = vectorizeTree(E->getOperand(0));
7174       Value *RHS = vectorizeTree(E->getOperand(1));
7175 
7176       if (E->VectorizedValue) {
7177         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7178         return E->VectorizedValue;
7179       }
7180 
7181       Value *V = Builder.CreateBinOp(
7182           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7183           RHS);
7184       propagateIRFlags(V, E->Scalars, VL0);
7185       if (auto *I = dyn_cast<Instruction>(V))
7186         V = propagateMetadata(I, E->Scalars);
7187 
7188       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7189       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7190       V = ShuffleBuilder.finalize(V);
7191 
7192       E->VectorizedValue = V;
7193       ++NumVectorInstructions;
7194 
7195       return V;
7196     }
7197     case Instruction::Load: {
7198       // Loads are inserted at the head of the tree because we don't want to
7199       // sink them all the way down past store instructions.
7200       setInsertPointAfterBundle(E);
7201 
7202       LoadInst *LI = cast<LoadInst>(VL0);
7203       Instruction *NewLI;
7204       unsigned AS = LI->getPointerAddressSpace();
7205       Value *PO = LI->getPointerOperand();
7206       if (E->State == TreeEntry::Vectorize) {
7207         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7208         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7209 
7210         // The pointer operand uses an in-tree scalar so we add the new BitCast
7211         // or LoadInst to ExternalUses list to make sure that an extract will
7212         // be generated in the future.
7213         if (TreeEntry *Entry = getTreeEntry(PO)) {
7214           // Find which lane we need to extract.
7215           unsigned FoundLane = Entry->findLaneForValue(PO);
7216           ExternalUses.emplace_back(
7217               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7218         }
7219       } else {
7220         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7221         Value *VecPtr = vectorizeTree(E->getOperand(0));
7222         // Use the minimum alignment of the gathered loads.
7223         Align CommonAlignment = LI->getAlign();
7224         for (Value *V : E->Scalars)
7225           CommonAlignment =
7226               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7227         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7228       }
7229       Value *V = propagateMetadata(NewLI, E->Scalars);
7230 
7231       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7232       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7233       V = ShuffleBuilder.finalize(V);
7234       E->VectorizedValue = V;
7235       ++NumVectorInstructions;
7236       return V;
7237     }
7238     case Instruction::Store: {
7239       auto *SI = cast<StoreInst>(VL0);
7240       unsigned AS = SI->getPointerAddressSpace();
7241 
7242       setInsertPointAfterBundle(E);
7243 
7244       Value *VecValue = vectorizeTree(E->getOperand(0));
7245       ShuffleBuilder.addMask(E->ReorderIndices);
7246       VecValue = ShuffleBuilder.finalize(VecValue);
7247 
7248       Value *ScalarPtr = SI->getPointerOperand();
7249       Value *VecPtr = Builder.CreateBitCast(
7250           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7251       StoreInst *ST =
7252           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7253 
7254       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7255       // StoreInst to ExternalUses to make sure that an extract will be
7256       // generated in the future.
7257       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7258         // Find which lane we need to extract.
7259         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7260         ExternalUses.push_back(ExternalUser(
7261             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7262             FoundLane));
7263       }
7264 
7265       Value *V = propagateMetadata(ST, E->Scalars);
7266 
7267       E->VectorizedValue = V;
7268       ++NumVectorInstructions;
7269       return V;
7270     }
7271     case Instruction::GetElementPtr: {
7272       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7273       setInsertPointAfterBundle(E);
7274 
7275       Value *Op0 = vectorizeTree(E->getOperand(0));
7276 
7277       SmallVector<Value *> OpVecs;
7278       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7279         Value *OpVec = vectorizeTree(E->getOperand(J));
7280         OpVecs.push_back(OpVec);
7281       }
7282 
7283       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7284       if (Instruction *I = dyn_cast<Instruction>(V))
7285         V = propagateMetadata(I, E->Scalars);
7286 
7287       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7288       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7289       V = ShuffleBuilder.finalize(V);
7290 
7291       E->VectorizedValue = V;
7292       ++NumVectorInstructions;
7293 
7294       return V;
7295     }
7296     case Instruction::Call: {
7297       CallInst *CI = cast<CallInst>(VL0);
7298       setInsertPointAfterBundle(E);
7299 
7300       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7301       if (Function *FI = CI->getCalledFunction())
7302         IID = FI->getIntrinsicID();
7303 
7304       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7305 
7306       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7307       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7308                           VecCallCosts.first <= VecCallCosts.second;
7309 
7310       Value *ScalarArg = nullptr;
7311       std::vector<Value *> OpVecs;
7312       SmallVector<Type *, 2> TysForDecl =
7313           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7314       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7315         ValueList OpVL;
7316         // Some intrinsics have scalar arguments. This argument should not be
7317         // vectorized.
7318         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7319           CallInst *CEI = cast<CallInst>(VL0);
7320           ScalarArg = CEI->getArgOperand(j);
7321           OpVecs.push_back(CEI->getArgOperand(j));
7322           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7323             TysForDecl.push_back(ScalarArg->getType());
7324           continue;
7325         }
7326 
7327         Value *OpVec = vectorizeTree(E->getOperand(j));
7328         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7329         OpVecs.push_back(OpVec);
7330       }
7331 
7332       Function *CF;
7333       if (!UseIntrinsic) {
7334         VFShape Shape =
7335             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7336                                   VecTy->getNumElements())),
7337                          false /*HasGlobalPred*/);
7338         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7339       } else {
7340         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7341       }
7342 
7343       SmallVector<OperandBundleDef, 1> OpBundles;
7344       CI->getOperandBundlesAsDefs(OpBundles);
7345       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7346 
7347       // The scalar argument uses an in-tree scalar so we add the new vectorized
7348       // call to ExternalUses list to make sure that an extract will be
7349       // generated in the future.
7350       if (ScalarArg) {
7351         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7352           // Find which lane we need to extract.
7353           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7354           ExternalUses.push_back(
7355               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7356         }
7357       }
7358 
7359       propagateIRFlags(V, E->Scalars, VL0);
7360       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7361       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7362       V = ShuffleBuilder.finalize(V);
7363 
7364       E->VectorizedValue = V;
7365       ++NumVectorInstructions;
7366       return V;
7367     }
7368     case Instruction::ShuffleVector: {
7369       assert(E->isAltShuffle() &&
7370              ((Instruction::isBinaryOp(E->getOpcode()) &&
7371                Instruction::isBinaryOp(E->getAltOpcode())) ||
7372               (Instruction::isCast(E->getOpcode()) &&
7373                Instruction::isCast(E->getAltOpcode())) ||
7374               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7375              "Invalid Shuffle Vector Operand");
7376 
7377       Value *LHS = nullptr, *RHS = nullptr;
7378       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7379         setInsertPointAfterBundle(E);
7380         LHS = vectorizeTree(E->getOperand(0));
7381         RHS = vectorizeTree(E->getOperand(1));
7382       } else {
7383         setInsertPointAfterBundle(E);
7384         LHS = vectorizeTree(E->getOperand(0));
7385       }
7386 
7387       if (E->VectorizedValue) {
7388         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7389         return E->VectorizedValue;
7390       }
7391 
7392       Value *V0, *V1;
7393       if (Instruction::isBinaryOp(E->getOpcode())) {
7394         V0 = Builder.CreateBinOp(
7395             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7396         V1 = Builder.CreateBinOp(
7397             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7398       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7399         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7400         auto *AltCI = cast<CmpInst>(E->getAltOp());
7401         CmpInst::Predicate AltPred = AltCI->getPredicate();
7402         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7403       } else {
7404         V0 = Builder.CreateCast(
7405             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7406         V1 = Builder.CreateCast(
7407             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7408       }
7409       // Add V0 and V1 to later analysis to try to find and remove matching
7410       // instruction, if any.
7411       for (Value *V : {V0, V1}) {
7412         if (auto *I = dyn_cast<Instruction>(V)) {
7413           GatherShuffleSeq.insert(I);
7414           CSEBlocks.insert(I->getParent());
7415         }
7416       }
7417 
7418       // Create shuffle to take alternate operations from the vector.
7419       // Also, gather up main and alt scalar ops to propagate IR flags to
7420       // each vector operation.
7421       ValueList OpScalars, AltScalars;
7422       SmallVector<int> Mask;
7423       buildShuffleEntryMask(
7424           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7425           [E](Instruction *I) {
7426             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7427             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7428           },
7429           Mask, &OpScalars, &AltScalars);
7430 
7431       propagateIRFlags(V0, OpScalars);
7432       propagateIRFlags(V1, AltScalars);
7433 
7434       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7435       if (auto *I = dyn_cast<Instruction>(V)) {
7436         V = propagateMetadata(I, E->Scalars);
7437         GatherShuffleSeq.insert(I);
7438         CSEBlocks.insert(I->getParent());
7439       }
7440       V = ShuffleBuilder.finalize(V);
7441 
7442       E->VectorizedValue = V;
7443       ++NumVectorInstructions;
7444 
7445       return V;
7446     }
7447     default:
7448     llvm_unreachable("unknown inst");
7449   }
7450   return nullptr;
7451 }
7452 
7453 Value *BoUpSLP::vectorizeTree() {
7454   ExtraValueToDebugLocsMap ExternallyUsedValues;
7455   return vectorizeTree(ExternallyUsedValues);
7456 }
7457 
7458 Value *
7459 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7460   // All blocks must be scheduled before any instructions are inserted.
7461   for (auto &BSIter : BlocksSchedules) {
7462     scheduleBlock(BSIter.second.get());
7463   }
7464 
7465   Builder.SetInsertPoint(&F->getEntryBlock().front());
7466   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7467 
7468   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7469   // vectorized root. InstCombine will then rewrite the entire expression. We
7470   // sign extend the extracted values below.
7471   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7472   if (MinBWs.count(ScalarRoot)) {
7473     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7474       // If current instr is a phi and not the last phi, insert it after the
7475       // last phi node.
7476       if (isa<PHINode>(I))
7477         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7478       else
7479         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7480     }
7481     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7482     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7483     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7484     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7485     VectorizableTree[0]->VectorizedValue = Trunc;
7486   }
7487 
7488   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7489                     << " values .\n");
7490 
7491   // Extract all of the elements with the external uses.
7492   for (const auto &ExternalUse : ExternalUses) {
7493     Value *Scalar = ExternalUse.Scalar;
7494     llvm::User *User = ExternalUse.User;
7495 
7496     // Skip users that we already RAUW. This happens when one instruction
7497     // has multiple uses of the same value.
7498     if (User && !is_contained(Scalar->users(), User))
7499       continue;
7500     TreeEntry *E = getTreeEntry(Scalar);
7501     assert(E && "Invalid scalar");
7502     assert(E->State != TreeEntry::NeedToGather &&
7503            "Extracting from a gather list");
7504 
7505     Value *Vec = E->VectorizedValue;
7506     assert(Vec && "Can't find vectorizable value");
7507 
7508     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7509     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7510       if (Scalar->getType() != Vec->getType()) {
7511         Value *Ex;
7512         // "Reuse" the existing extract to improve final codegen.
7513         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7514           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7515                                             ES->getOperand(1));
7516         } else {
7517           Ex = Builder.CreateExtractElement(Vec, Lane);
7518         }
7519         // If necessary, sign-extend or zero-extend ScalarRoot
7520         // to the larger type.
7521         if (!MinBWs.count(ScalarRoot))
7522           return Ex;
7523         if (MinBWs[ScalarRoot].second)
7524           return Builder.CreateSExt(Ex, Scalar->getType());
7525         return Builder.CreateZExt(Ex, Scalar->getType());
7526       }
7527       assert(isa<FixedVectorType>(Scalar->getType()) &&
7528              isa<InsertElementInst>(Scalar) &&
7529              "In-tree scalar of vector type is not insertelement?");
7530       return Vec;
7531     };
7532     // If User == nullptr, the Scalar is used as extra arg. Generate
7533     // ExtractElement instruction and update the record for this scalar in
7534     // ExternallyUsedValues.
7535     if (!User) {
7536       assert(ExternallyUsedValues.count(Scalar) &&
7537              "Scalar with nullptr as an external user must be registered in "
7538              "ExternallyUsedValues map");
7539       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7540         Builder.SetInsertPoint(VecI->getParent(),
7541                                std::next(VecI->getIterator()));
7542       } else {
7543         Builder.SetInsertPoint(&F->getEntryBlock().front());
7544       }
7545       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7546       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7547       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7548       auto It = ExternallyUsedValues.find(Scalar);
7549       assert(It != ExternallyUsedValues.end() &&
7550              "Externally used scalar is not found in ExternallyUsedValues");
7551       NewInstLocs.append(It->second);
7552       ExternallyUsedValues.erase(Scalar);
7553       // Required to update internally referenced instructions.
7554       Scalar->replaceAllUsesWith(NewInst);
7555       continue;
7556     }
7557 
7558     // Generate extracts for out-of-tree users.
7559     // Find the insertion point for the extractelement lane.
7560     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7561       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7562         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7563           if (PH->getIncomingValue(i) == Scalar) {
7564             Instruction *IncomingTerminator =
7565                 PH->getIncomingBlock(i)->getTerminator();
7566             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7567               Builder.SetInsertPoint(VecI->getParent(),
7568                                      std::next(VecI->getIterator()));
7569             } else {
7570               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7571             }
7572             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7573             CSEBlocks.insert(PH->getIncomingBlock(i));
7574             PH->setOperand(i, NewInst);
7575           }
7576         }
7577       } else {
7578         Builder.SetInsertPoint(cast<Instruction>(User));
7579         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7580         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7581         User->replaceUsesOfWith(Scalar, NewInst);
7582       }
7583     } else {
7584       Builder.SetInsertPoint(&F->getEntryBlock().front());
7585       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7586       CSEBlocks.insert(&F->getEntryBlock());
7587       User->replaceUsesOfWith(Scalar, NewInst);
7588     }
7589 
7590     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7591   }
7592 
7593   // For each vectorized value:
7594   for (auto &TEPtr : VectorizableTree) {
7595     TreeEntry *Entry = TEPtr.get();
7596 
7597     // No need to handle users of gathered values.
7598     if (Entry->State == TreeEntry::NeedToGather)
7599       continue;
7600 
7601     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7602 
7603     // For each lane:
7604     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7605       Value *Scalar = Entry->Scalars[Lane];
7606 
7607 #ifndef NDEBUG
7608       Type *Ty = Scalar->getType();
7609       if (!Ty->isVoidTy()) {
7610         for (User *U : Scalar->users()) {
7611           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7612 
7613           // It is legal to delete users in the ignorelist.
7614           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7615                   (isa_and_nonnull<Instruction>(U) &&
7616                    isDeleted(cast<Instruction>(U)))) &&
7617                  "Deleting out-of-tree value");
7618         }
7619       }
7620 #endif
7621       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7622       eraseInstruction(cast<Instruction>(Scalar));
7623     }
7624   }
7625 
7626   Builder.ClearInsertionPoint();
7627   InstrElementSize.clear();
7628 
7629   return VectorizableTree[0]->VectorizedValue;
7630 }
7631 
7632 void BoUpSLP::optimizeGatherSequence() {
7633   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7634                     << " gather sequences instructions.\n");
7635   // LICM InsertElementInst sequences.
7636   for (Instruction *I : GatherShuffleSeq) {
7637     if (isDeleted(I))
7638       continue;
7639 
7640     // Check if this block is inside a loop.
7641     Loop *L = LI->getLoopFor(I->getParent());
7642     if (!L)
7643       continue;
7644 
7645     // Check if it has a preheader.
7646     BasicBlock *PreHeader = L->getLoopPreheader();
7647     if (!PreHeader)
7648       continue;
7649 
7650     // If the vector or the element that we insert into it are
7651     // instructions that are defined in this basic block then we can't
7652     // hoist this instruction.
7653     if (any_of(I->operands(), [L](Value *V) {
7654           auto *OpI = dyn_cast<Instruction>(V);
7655           return OpI && L->contains(OpI);
7656         }))
7657       continue;
7658 
7659     // We can hoist this instruction. Move it to the pre-header.
7660     I->moveBefore(PreHeader->getTerminator());
7661   }
7662 
7663   // Make a list of all reachable blocks in our CSE queue.
7664   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7665   CSEWorkList.reserve(CSEBlocks.size());
7666   for (BasicBlock *BB : CSEBlocks)
7667     if (DomTreeNode *N = DT->getNode(BB)) {
7668       assert(DT->isReachableFromEntry(N));
7669       CSEWorkList.push_back(N);
7670     }
7671 
7672   // Sort blocks by domination. This ensures we visit a block after all blocks
7673   // dominating it are visited.
7674   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7675     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7676            "Different nodes should have different DFS numbers");
7677     return A->getDFSNumIn() < B->getDFSNumIn();
7678   });
7679 
7680   // Less defined shuffles can be replaced by the more defined copies.
7681   // Between two shuffles one is less defined if it has the same vector operands
7682   // and its mask indeces are the same as in the first one or undefs. E.g.
7683   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7684   // poison, <0, 0, 0, 0>.
7685   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7686                                            SmallVectorImpl<int> &NewMask) {
7687     if (I1->getType() != I2->getType())
7688       return false;
7689     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7690     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7691     if (!SI1 || !SI2)
7692       return I1->isIdenticalTo(I2);
7693     if (SI1->isIdenticalTo(SI2))
7694       return true;
7695     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7696       if (SI1->getOperand(I) != SI2->getOperand(I))
7697         return false;
7698     // Check if the second instruction is more defined than the first one.
7699     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7700     ArrayRef<int> SM1 = SI1->getShuffleMask();
7701     // Count trailing undefs in the mask to check the final number of used
7702     // registers.
7703     unsigned LastUndefsCnt = 0;
7704     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7705       if (SM1[I] == UndefMaskElem)
7706         ++LastUndefsCnt;
7707       else
7708         LastUndefsCnt = 0;
7709       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7710           NewMask[I] != SM1[I])
7711         return false;
7712       if (NewMask[I] == UndefMaskElem)
7713         NewMask[I] = SM1[I];
7714     }
7715     // Check if the last undefs actually change the final number of used vector
7716     // registers.
7717     return SM1.size() - LastUndefsCnt > 1 &&
7718            TTI->getNumberOfParts(SI1->getType()) ==
7719                TTI->getNumberOfParts(
7720                    FixedVectorType::get(SI1->getType()->getElementType(),
7721                                         SM1.size() - LastUndefsCnt));
7722   };
7723   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7724   // instructions. TODO: We can further optimize this scan if we split the
7725   // instructions into different buckets based on the insert lane.
7726   SmallVector<Instruction *, 16> Visited;
7727   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7728     assert(*I &&
7729            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7730            "Worklist not sorted properly!");
7731     BasicBlock *BB = (*I)->getBlock();
7732     // For all instructions in blocks containing gather sequences:
7733     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7734       if (isDeleted(&In))
7735         continue;
7736       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7737           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7738         continue;
7739 
7740       // Check if we can replace this instruction with any of the
7741       // visited instructions.
7742       bool Replaced = false;
7743       for (Instruction *&V : Visited) {
7744         SmallVector<int> NewMask;
7745         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7746             DT->dominates(V->getParent(), In.getParent())) {
7747           In.replaceAllUsesWith(V);
7748           eraseInstruction(&In);
7749           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7750             if (!NewMask.empty())
7751               SI->setShuffleMask(NewMask);
7752           Replaced = true;
7753           break;
7754         }
7755         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7756             GatherShuffleSeq.contains(V) &&
7757             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7758             DT->dominates(In.getParent(), V->getParent())) {
7759           In.moveAfter(V);
7760           V->replaceAllUsesWith(&In);
7761           eraseInstruction(V);
7762           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7763             if (!NewMask.empty())
7764               SI->setShuffleMask(NewMask);
7765           V = &In;
7766           Replaced = true;
7767           break;
7768         }
7769       }
7770       if (!Replaced) {
7771         assert(!is_contained(Visited, &In));
7772         Visited.push_back(&In);
7773       }
7774     }
7775   }
7776   CSEBlocks.clear();
7777   GatherShuffleSeq.clear();
7778 }
7779 
7780 BoUpSLP::ScheduleData *
7781 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7782   ScheduleData *Bundle = nullptr;
7783   ScheduleData *PrevInBundle = nullptr;
7784   for (Value *V : VL) {
7785     if (doesNotNeedToBeScheduled(V))
7786       continue;
7787     ScheduleData *BundleMember = getScheduleData(V);
7788     assert(BundleMember &&
7789            "no ScheduleData for bundle member "
7790            "(maybe not in same basic block)");
7791     assert(BundleMember->isSchedulingEntity() &&
7792            "bundle member already part of other bundle");
7793     if (PrevInBundle) {
7794       PrevInBundle->NextInBundle = BundleMember;
7795     } else {
7796       Bundle = BundleMember;
7797     }
7798 
7799     // Group the instructions to a bundle.
7800     BundleMember->FirstInBundle = Bundle;
7801     PrevInBundle = BundleMember;
7802   }
7803   assert(Bundle && "Failed to find schedule bundle");
7804   return Bundle;
7805 }
7806 
7807 // Groups the instructions to a bundle (which is then a single scheduling entity)
7808 // and schedules instructions until the bundle gets ready.
7809 Optional<BoUpSLP::ScheduleData *>
7810 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7811                                             const InstructionsState &S) {
7812   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7813   // instructions.
7814   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7815       doesNotNeedToSchedule(VL))
7816     return nullptr;
7817 
7818   // Initialize the instruction bundle.
7819   Instruction *OldScheduleEnd = ScheduleEnd;
7820   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7821 
7822   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7823                                                          ScheduleData *Bundle) {
7824     // The scheduling region got new instructions at the lower end (or it is a
7825     // new region for the first bundle). This makes it necessary to
7826     // recalculate all dependencies.
7827     // It is seldom that this needs to be done a second time after adding the
7828     // initial bundle to the region.
7829     if (ScheduleEnd != OldScheduleEnd) {
7830       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7831         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7832       ReSchedule = true;
7833     }
7834     if (Bundle) {
7835       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7836                         << " in block " << BB->getName() << "\n");
7837       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7838     }
7839 
7840     if (ReSchedule) {
7841       resetSchedule();
7842       initialFillReadyList(ReadyInsts);
7843     }
7844 
7845     // Now try to schedule the new bundle or (if no bundle) just calculate
7846     // dependencies. As soon as the bundle is "ready" it means that there are no
7847     // cyclic dependencies and we can schedule it. Note that's important that we
7848     // don't "schedule" the bundle yet (see cancelScheduling).
7849     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7850            !ReadyInsts.empty()) {
7851       ScheduleData *Picked = ReadyInsts.pop_back_val();
7852       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7853              "must be ready to schedule");
7854       schedule(Picked, ReadyInsts);
7855     }
7856   };
7857 
7858   // Make sure that the scheduling region contains all
7859   // instructions of the bundle.
7860   for (Value *V : VL) {
7861     if (doesNotNeedToBeScheduled(V))
7862       continue;
7863     if (!extendSchedulingRegion(V, S)) {
7864       // If the scheduling region got new instructions at the lower end (or it
7865       // is a new region for the first bundle). This makes it necessary to
7866       // recalculate all dependencies.
7867       // Otherwise the compiler may crash trying to incorrectly calculate
7868       // dependencies and emit instruction in the wrong order at the actual
7869       // scheduling.
7870       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7871       return None;
7872     }
7873   }
7874 
7875   bool ReSchedule = false;
7876   for (Value *V : VL) {
7877     if (doesNotNeedToBeScheduled(V))
7878       continue;
7879     ScheduleData *BundleMember = getScheduleData(V);
7880     assert(BundleMember &&
7881            "no ScheduleData for bundle member (maybe not in same basic block)");
7882 
7883     // Make sure we don't leave the pieces of the bundle in the ready list when
7884     // whole bundle might not be ready.
7885     ReadyInsts.remove(BundleMember);
7886 
7887     if (!BundleMember->IsScheduled)
7888       continue;
7889     // A bundle member was scheduled as single instruction before and now
7890     // needs to be scheduled as part of the bundle. We just get rid of the
7891     // existing schedule.
7892     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7893                       << " was already scheduled\n");
7894     ReSchedule = true;
7895   }
7896 
7897   auto *Bundle = buildBundle(VL);
7898   TryScheduleBundleImpl(ReSchedule, Bundle);
7899   if (!Bundle->isReady()) {
7900     cancelScheduling(VL, S.OpValue);
7901     return None;
7902   }
7903   return Bundle;
7904 }
7905 
7906 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7907                                                 Value *OpValue) {
7908   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7909       doesNotNeedToSchedule(VL))
7910     return;
7911 
7912   if (doesNotNeedToBeScheduled(OpValue))
7913     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7914   ScheduleData *Bundle = getScheduleData(OpValue);
7915   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7916   assert(!Bundle->IsScheduled &&
7917          "Can't cancel bundle which is already scheduled");
7918   assert(Bundle->isSchedulingEntity() &&
7919          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7920          "tried to unbundle something which is not a bundle");
7921 
7922   // Remove the bundle from the ready list.
7923   if (Bundle->isReady())
7924     ReadyInsts.remove(Bundle);
7925 
7926   // Un-bundle: make single instructions out of the bundle.
7927   ScheduleData *BundleMember = Bundle;
7928   while (BundleMember) {
7929     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7930     BundleMember->FirstInBundle = BundleMember;
7931     ScheduleData *Next = BundleMember->NextInBundle;
7932     BundleMember->NextInBundle = nullptr;
7933     BundleMember->TE = nullptr;
7934     if (BundleMember->unscheduledDepsInBundle() == 0) {
7935       ReadyInsts.insert(BundleMember);
7936     }
7937     BundleMember = Next;
7938   }
7939 }
7940 
7941 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7942   // Allocate a new ScheduleData for the instruction.
7943   if (ChunkPos >= ChunkSize) {
7944     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7945     ChunkPos = 0;
7946   }
7947   return &(ScheduleDataChunks.back()[ChunkPos++]);
7948 }
7949 
7950 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7951                                                       const InstructionsState &S) {
7952   if (getScheduleData(V, isOneOf(S, V)))
7953     return true;
7954   Instruction *I = dyn_cast<Instruction>(V);
7955   assert(I && "bundle member must be an instruction");
7956   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7957          !doesNotNeedToBeScheduled(I) &&
7958          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7959          "be scheduled");
7960   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7961     ScheduleData *ISD = getScheduleData(I);
7962     if (!ISD)
7963       return false;
7964     assert(isInSchedulingRegion(ISD) &&
7965            "ScheduleData not in scheduling region");
7966     ScheduleData *SD = allocateScheduleDataChunks();
7967     SD->Inst = I;
7968     SD->init(SchedulingRegionID, S.OpValue);
7969     ExtraScheduleDataMap[I][S.OpValue] = SD;
7970     return true;
7971   };
7972   if (CheckScheduleForI(I))
7973     return true;
7974   if (!ScheduleStart) {
7975     // It's the first instruction in the new region.
7976     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7977     ScheduleStart = I;
7978     ScheduleEnd = I->getNextNode();
7979     if (isOneOf(S, I) != I)
7980       CheckScheduleForI(I);
7981     assert(ScheduleEnd && "tried to vectorize a terminator?");
7982     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7983     return true;
7984   }
7985   // Search up and down at the same time, because we don't know if the new
7986   // instruction is above or below the existing scheduling region.
7987   BasicBlock::reverse_iterator UpIter =
7988       ++ScheduleStart->getIterator().getReverse();
7989   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7990   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7991   BasicBlock::iterator LowerEnd = BB->end();
7992   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7993          &*DownIter != I) {
7994     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7995       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7996       return false;
7997     }
7998 
7999     ++UpIter;
8000     ++DownIter;
8001   }
8002   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
8003     assert(I->getParent() == ScheduleStart->getParent() &&
8004            "Instruction is in wrong basic block.");
8005     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
8006     ScheduleStart = I;
8007     if (isOneOf(S, I) != I)
8008       CheckScheduleForI(I);
8009     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
8010                       << "\n");
8011     return true;
8012   }
8013   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
8014          "Expected to reach top of the basic block or instruction down the "
8015          "lower end.");
8016   assert(I->getParent() == ScheduleEnd->getParent() &&
8017          "Instruction is in wrong basic block.");
8018   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
8019                    nullptr);
8020   ScheduleEnd = I->getNextNode();
8021   if (isOneOf(S, I) != I)
8022     CheckScheduleForI(I);
8023   assert(ScheduleEnd && "tried to vectorize a terminator?");
8024   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
8025   return true;
8026 }
8027 
8028 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
8029                                                 Instruction *ToI,
8030                                                 ScheduleData *PrevLoadStore,
8031                                                 ScheduleData *NextLoadStore) {
8032   ScheduleData *CurrentLoadStore = PrevLoadStore;
8033   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
8034     // No need to allocate data for non-schedulable instructions.
8035     if (doesNotNeedToBeScheduled(I))
8036       continue;
8037     ScheduleData *SD = ScheduleDataMap.lookup(I);
8038     if (!SD) {
8039       SD = allocateScheduleDataChunks();
8040       ScheduleDataMap[I] = SD;
8041       SD->Inst = I;
8042     }
8043     assert(!isInSchedulingRegion(SD) &&
8044            "new ScheduleData already in scheduling region");
8045     SD->init(SchedulingRegionID, I);
8046 
8047     if (I->mayReadOrWriteMemory() &&
8048         (!isa<IntrinsicInst>(I) ||
8049          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8050           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8051               Intrinsic::pseudoprobe))) {
8052       // Update the linked list of memory accessing instructions.
8053       if (CurrentLoadStore) {
8054         CurrentLoadStore->NextLoadStore = SD;
8055       } else {
8056         FirstLoadStoreInRegion = SD;
8057       }
8058       CurrentLoadStore = SD;
8059     }
8060 
8061     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8062         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8063       RegionHasStackSave = true;
8064   }
8065   if (NextLoadStore) {
8066     if (CurrentLoadStore)
8067       CurrentLoadStore->NextLoadStore = NextLoadStore;
8068   } else {
8069     LastLoadStoreInRegion = CurrentLoadStore;
8070   }
8071 }
8072 
8073 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8074                                                      bool InsertInReadyList,
8075                                                      BoUpSLP *SLP) {
8076   assert(SD->isSchedulingEntity());
8077 
8078   SmallVector<ScheduleData *, 10> WorkList;
8079   WorkList.push_back(SD);
8080 
8081   while (!WorkList.empty()) {
8082     ScheduleData *SD = WorkList.pop_back_val();
8083     for (ScheduleData *BundleMember = SD; BundleMember;
8084          BundleMember = BundleMember->NextInBundle) {
8085       assert(isInSchedulingRegion(BundleMember));
8086       if (BundleMember->hasValidDependencies())
8087         continue;
8088 
8089       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8090                  << "\n");
8091       BundleMember->Dependencies = 0;
8092       BundleMember->resetUnscheduledDeps();
8093 
8094       // Handle def-use chain dependencies.
8095       if (BundleMember->OpValue != BundleMember->Inst) {
8096         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8097           BundleMember->Dependencies++;
8098           ScheduleData *DestBundle = UseSD->FirstInBundle;
8099           if (!DestBundle->IsScheduled)
8100             BundleMember->incrementUnscheduledDeps(1);
8101           if (!DestBundle->hasValidDependencies())
8102             WorkList.push_back(DestBundle);
8103         }
8104       } else {
8105         for (User *U : BundleMember->Inst->users()) {
8106           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8107             BundleMember->Dependencies++;
8108             ScheduleData *DestBundle = UseSD->FirstInBundle;
8109             if (!DestBundle->IsScheduled)
8110               BundleMember->incrementUnscheduledDeps(1);
8111             if (!DestBundle->hasValidDependencies())
8112               WorkList.push_back(DestBundle);
8113           }
8114         }
8115       }
8116 
8117       auto makeControlDependent = [&](Instruction *I) {
8118         auto *DepDest = getScheduleData(I);
8119         assert(DepDest && "must be in schedule window");
8120         DepDest->ControlDependencies.push_back(BundleMember);
8121         BundleMember->Dependencies++;
8122         ScheduleData *DestBundle = DepDest->FirstInBundle;
8123         if (!DestBundle->IsScheduled)
8124           BundleMember->incrementUnscheduledDeps(1);
8125         if (!DestBundle->hasValidDependencies())
8126           WorkList.push_back(DestBundle);
8127       };
8128 
8129       // Any instruction which isn't safe to speculate at the begining of the
8130       // block is control dependend on any early exit or non-willreturn call
8131       // which proceeds it.
8132       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8133         for (Instruction *I = BundleMember->Inst->getNextNode();
8134              I != ScheduleEnd; I = I->getNextNode()) {
8135           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8136             continue;
8137 
8138           // Add the dependency
8139           makeControlDependent(I);
8140 
8141           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8142             // Everything past here must be control dependent on I.
8143             break;
8144         }
8145       }
8146 
8147       if (RegionHasStackSave) {
8148         // If we have an inalloc alloca instruction, it needs to be scheduled
8149         // after any preceeding stacksave.  We also need to prevent any alloca
8150         // from reordering above a preceeding stackrestore.
8151         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8152             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8153           for (Instruction *I = BundleMember->Inst->getNextNode();
8154                I != ScheduleEnd; I = I->getNextNode()) {
8155             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8156                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8157               // Any allocas past here must be control dependent on I, and I
8158               // must be memory dependend on BundleMember->Inst.
8159               break;
8160 
8161             if (!isa<AllocaInst>(I))
8162               continue;
8163 
8164             // Add the dependency
8165             makeControlDependent(I);
8166           }
8167         }
8168 
8169         // In addition to the cases handle just above, we need to prevent
8170         // allocas from moving below a stacksave.  The stackrestore case
8171         // is currently thought to be conservatism.
8172         if (isa<AllocaInst>(BundleMember->Inst)) {
8173           for (Instruction *I = BundleMember->Inst->getNextNode();
8174                I != ScheduleEnd; I = I->getNextNode()) {
8175             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8176                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8177               continue;
8178 
8179             // Add the dependency
8180             makeControlDependent(I);
8181             break;
8182           }
8183         }
8184       }
8185 
8186       // Handle the memory dependencies (if any).
8187       ScheduleData *DepDest = BundleMember->NextLoadStore;
8188       if (!DepDest)
8189         continue;
8190       Instruction *SrcInst = BundleMember->Inst;
8191       assert(SrcInst->mayReadOrWriteMemory() &&
8192              "NextLoadStore list for non memory effecting bundle?");
8193       MemoryLocation SrcLoc = getLocation(SrcInst);
8194       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8195       unsigned numAliased = 0;
8196       unsigned DistToSrc = 1;
8197 
8198       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8199         assert(isInSchedulingRegion(DepDest));
8200 
8201         // We have two limits to reduce the complexity:
8202         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8203         //    SLP->isAliased (which is the expensive part in this loop).
8204         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8205         //    the whole loop (even if the loop is fast, it's quadratic).
8206         //    It's important for the loop break condition (see below) to
8207         //    check this limit even between two read-only instructions.
8208         if (DistToSrc >= MaxMemDepDistance ||
8209             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8210              (numAliased >= AliasedCheckLimit ||
8211               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8212 
8213           // We increment the counter only if the locations are aliased
8214           // (instead of counting all alias checks). This gives a better
8215           // balance between reduced runtime and accurate dependencies.
8216           numAliased++;
8217 
8218           DepDest->MemoryDependencies.push_back(BundleMember);
8219           BundleMember->Dependencies++;
8220           ScheduleData *DestBundle = DepDest->FirstInBundle;
8221           if (!DestBundle->IsScheduled) {
8222             BundleMember->incrementUnscheduledDeps(1);
8223           }
8224           if (!DestBundle->hasValidDependencies()) {
8225             WorkList.push_back(DestBundle);
8226           }
8227         }
8228 
8229         // Example, explaining the loop break condition: Let's assume our
8230         // starting instruction is i0 and MaxMemDepDistance = 3.
8231         //
8232         //                      +--------v--v--v
8233         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8234         //             +--------^--^--^
8235         //
8236         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8237         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8238         // Previously we already added dependencies from i3 to i6,i7,i8
8239         // (because of MaxMemDepDistance). As we added a dependency from
8240         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8241         // and we can abort this loop at i6.
8242         if (DistToSrc >= 2 * MaxMemDepDistance)
8243           break;
8244         DistToSrc++;
8245       }
8246     }
8247     if (InsertInReadyList && SD->isReady()) {
8248       ReadyInsts.insert(SD);
8249       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8250                         << "\n");
8251     }
8252   }
8253 }
8254 
8255 void BoUpSLP::BlockScheduling::resetSchedule() {
8256   assert(ScheduleStart &&
8257          "tried to reset schedule on block which has not been scheduled");
8258   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8259     doForAllOpcodes(I, [&](ScheduleData *SD) {
8260       assert(isInSchedulingRegion(SD) &&
8261              "ScheduleData not in scheduling region");
8262       SD->IsScheduled = false;
8263       SD->resetUnscheduledDeps();
8264     });
8265   }
8266   ReadyInsts.clear();
8267 }
8268 
8269 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8270   if (!BS->ScheduleStart)
8271     return;
8272 
8273   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8274 
8275   // A key point - if we got here, pre-scheduling was able to find a valid
8276   // scheduling of the sub-graph of the scheduling window which consists
8277   // of all vector bundles and their transitive users.  As such, we do not
8278   // need to reschedule anything *outside of* that subgraph.
8279 
8280   BS->resetSchedule();
8281 
8282   // For the real scheduling we use a more sophisticated ready-list: it is
8283   // sorted by the original instruction location. This lets the final schedule
8284   // be as  close as possible to the original instruction order.
8285   // WARNING: If changing this order causes a correctness issue, that means
8286   // there is some missing dependence edge in the schedule data graph.
8287   struct ScheduleDataCompare {
8288     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8289       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8290     }
8291   };
8292   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8293 
8294   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8295   // and fill the ready-list with initial instructions.
8296   int Idx = 0;
8297   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8298        I = I->getNextNode()) {
8299     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8300       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8301       (void)SDTE;
8302       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8303               SD->isPartOfBundle() ==
8304                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8305              "scheduler and vectorizer bundle mismatch");
8306       SD->FirstInBundle->SchedulingPriority = Idx++;
8307 
8308       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8309         BS->calculateDependencies(SD, false, this);
8310     });
8311   }
8312   BS->initialFillReadyList(ReadyInsts);
8313 
8314   Instruction *LastScheduledInst = BS->ScheduleEnd;
8315 
8316   // Do the "real" scheduling.
8317   while (!ReadyInsts.empty()) {
8318     ScheduleData *picked = *ReadyInsts.begin();
8319     ReadyInsts.erase(ReadyInsts.begin());
8320 
8321     // Move the scheduled instruction(s) to their dedicated places, if not
8322     // there yet.
8323     for (ScheduleData *BundleMember = picked; BundleMember;
8324          BundleMember = BundleMember->NextInBundle) {
8325       Instruction *pickedInst = BundleMember->Inst;
8326       if (pickedInst->getNextNode() != LastScheduledInst)
8327         pickedInst->moveBefore(LastScheduledInst);
8328       LastScheduledInst = pickedInst;
8329     }
8330 
8331     BS->schedule(picked, ReadyInsts);
8332   }
8333 
8334   // Check that we didn't break any of our invariants.
8335 #ifdef EXPENSIVE_CHECKS
8336   BS->verify();
8337 #endif
8338 
8339 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8340   // Check that all schedulable entities got scheduled
8341   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8342     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8343       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8344         assert(SD->IsScheduled && "must be scheduled at this point");
8345       }
8346     });
8347   }
8348 #endif
8349 
8350   // Avoid duplicate scheduling of the block.
8351   BS->ScheduleStart = nullptr;
8352 }
8353 
8354 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8355   // If V is a store, just return the width of the stored value (or value
8356   // truncated just before storing) without traversing the expression tree.
8357   // This is the common case.
8358   if (auto *Store = dyn_cast<StoreInst>(V)) {
8359     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8360       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8361     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8362   }
8363 
8364   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8365     return getVectorElementSize(IEI->getOperand(1));
8366 
8367   auto E = InstrElementSize.find(V);
8368   if (E != InstrElementSize.end())
8369     return E->second;
8370 
8371   // If V is not a store, we can traverse the expression tree to find loads
8372   // that feed it. The type of the loaded value may indicate a more suitable
8373   // width than V's type. We want to base the vector element size on the width
8374   // of memory operations where possible.
8375   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8376   SmallPtrSet<Instruction *, 16> Visited;
8377   if (auto *I = dyn_cast<Instruction>(V)) {
8378     Worklist.emplace_back(I, I->getParent());
8379     Visited.insert(I);
8380   }
8381 
8382   // Traverse the expression tree in bottom-up order looking for loads. If we
8383   // encounter an instruction we don't yet handle, we give up.
8384   auto Width = 0u;
8385   while (!Worklist.empty()) {
8386     Instruction *I;
8387     BasicBlock *Parent;
8388     std::tie(I, Parent) = Worklist.pop_back_val();
8389 
8390     // We should only be looking at scalar instructions here. If the current
8391     // instruction has a vector type, skip.
8392     auto *Ty = I->getType();
8393     if (isa<VectorType>(Ty))
8394       continue;
8395 
8396     // If the current instruction is a load, update MaxWidth to reflect the
8397     // width of the loaded value.
8398     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8399         isa<ExtractValueInst>(I))
8400       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8401 
8402     // Otherwise, we need to visit the operands of the instruction. We only
8403     // handle the interesting cases from buildTree here. If an operand is an
8404     // instruction we haven't yet visited and from the same basic block as the
8405     // user or the use is a PHI node, we add it to the worklist.
8406     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8407              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8408              isa<UnaryOperator>(I)) {
8409       for (Use &U : I->operands())
8410         if (auto *J = dyn_cast<Instruction>(U.get()))
8411           if (Visited.insert(J).second &&
8412               (isa<PHINode>(I) || J->getParent() == Parent))
8413             Worklist.emplace_back(J, J->getParent());
8414     } else {
8415       break;
8416     }
8417   }
8418 
8419   // If we didn't encounter a memory access in the expression tree, or if we
8420   // gave up for some reason, just return the width of V. Otherwise, return the
8421   // maximum width we found.
8422   if (!Width) {
8423     if (auto *CI = dyn_cast<CmpInst>(V))
8424       V = CI->getOperand(0);
8425     Width = DL->getTypeSizeInBits(V->getType());
8426   }
8427 
8428   for (Instruction *I : Visited)
8429     InstrElementSize[I] = Width;
8430 
8431   return Width;
8432 }
8433 
8434 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8435 // smaller type with a truncation. We collect the values that will be demoted
8436 // in ToDemote and additional roots that require investigating in Roots.
8437 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8438                                   SmallVectorImpl<Value *> &ToDemote,
8439                                   SmallVectorImpl<Value *> &Roots) {
8440   // We can always demote constants.
8441   if (isa<Constant>(V)) {
8442     ToDemote.push_back(V);
8443     return true;
8444   }
8445 
8446   // If the value is not an instruction in the expression with only one use, it
8447   // cannot be demoted.
8448   auto *I = dyn_cast<Instruction>(V);
8449   if (!I || !I->hasOneUse() || !Expr.count(I))
8450     return false;
8451 
8452   switch (I->getOpcode()) {
8453 
8454   // We can always demote truncations and extensions. Since truncations can
8455   // seed additional demotion, we save the truncated value.
8456   case Instruction::Trunc:
8457     Roots.push_back(I->getOperand(0));
8458     break;
8459   case Instruction::ZExt:
8460   case Instruction::SExt:
8461     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8462         isa<InsertElementInst>(I->getOperand(0)))
8463       return false;
8464     break;
8465 
8466   // We can demote certain binary operations if we can demote both of their
8467   // operands.
8468   case Instruction::Add:
8469   case Instruction::Sub:
8470   case Instruction::Mul:
8471   case Instruction::And:
8472   case Instruction::Or:
8473   case Instruction::Xor:
8474     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8475         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8476       return false;
8477     break;
8478 
8479   // We can demote selects if we can demote their true and false values.
8480   case Instruction::Select: {
8481     SelectInst *SI = cast<SelectInst>(I);
8482     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8483         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8484       return false;
8485     break;
8486   }
8487 
8488   // We can demote phis if we can demote all their incoming operands. Note that
8489   // we don't need to worry about cycles since we ensure single use above.
8490   case Instruction::PHI: {
8491     PHINode *PN = cast<PHINode>(I);
8492     for (Value *IncValue : PN->incoming_values())
8493       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8494         return false;
8495     break;
8496   }
8497 
8498   // Otherwise, conservatively give up.
8499   default:
8500     return false;
8501   }
8502 
8503   // Record the value that we can demote.
8504   ToDemote.push_back(V);
8505   return true;
8506 }
8507 
8508 void BoUpSLP::computeMinimumValueSizes() {
8509   // If there are no external uses, the expression tree must be rooted by a
8510   // store. We can't demote in-memory values, so there is nothing to do here.
8511   if (ExternalUses.empty())
8512     return;
8513 
8514   // We only attempt to truncate integer expressions.
8515   auto &TreeRoot = VectorizableTree[0]->Scalars;
8516   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8517   if (!TreeRootIT)
8518     return;
8519 
8520   // If the expression is not rooted by a store, these roots should have
8521   // external uses. We will rely on InstCombine to rewrite the expression in
8522   // the narrower type. However, InstCombine only rewrites single-use values.
8523   // This means that if a tree entry other than a root is used externally, it
8524   // must have multiple uses and InstCombine will not rewrite it. The code
8525   // below ensures that only the roots are used externally.
8526   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8527   for (auto &EU : ExternalUses)
8528     if (!Expr.erase(EU.Scalar))
8529       return;
8530   if (!Expr.empty())
8531     return;
8532 
8533   // Collect the scalar values of the vectorizable expression. We will use this
8534   // context to determine which values can be demoted. If we see a truncation,
8535   // we mark it as seeding another demotion.
8536   for (auto &EntryPtr : VectorizableTree)
8537     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8538 
8539   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8540   // have a single external user that is not in the vectorizable tree.
8541   for (auto *Root : TreeRoot)
8542     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8543       return;
8544 
8545   // Conservatively determine if we can actually truncate the roots of the
8546   // expression. Collect the values that can be demoted in ToDemote and
8547   // additional roots that require investigating in Roots.
8548   SmallVector<Value *, 32> ToDemote;
8549   SmallVector<Value *, 4> Roots;
8550   for (auto *Root : TreeRoot)
8551     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8552       return;
8553 
8554   // The maximum bit width required to represent all the values that can be
8555   // demoted without loss of precision. It would be safe to truncate the roots
8556   // of the expression to this width.
8557   auto MaxBitWidth = 8u;
8558 
8559   // We first check if all the bits of the roots are demanded. If they're not,
8560   // we can truncate the roots to this narrower type.
8561   for (auto *Root : TreeRoot) {
8562     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8563     MaxBitWidth = std::max<unsigned>(
8564         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8565   }
8566 
8567   // True if the roots can be zero-extended back to their original type, rather
8568   // than sign-extended. We know that if the leading bits are not demanded, we
8569   // can safely zero-extend. So we initialize IsKnownPositive to True.
8570   bool IsKnownPositive = true;
8571 
8572   // If all the bits of the roots are demanded, we can try a little harder to
8573   // compute a narrower type. This can happen, for example, if the roots are
8574   // getelementptr indices. InstCombine promotes these indices to the pointer
8575   // width. Thus, all their bits are technically demanded even though the
8576   // address computation might be vectorized in a smaller type.
8577   //
8578   // We start by looking at each entry that can be demoted. We compute the
8579   // maximum bit width required to store the scalar by using ValueTracking to
8580   // compute the number of high-order bits we can truncate.
8581   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8582       llvm::all_of(TreeRoot, [](Value *R) {
8583         assert(R->hasOneUse() && "Root should have only one use!");
8584         return isa<GetElementPtrInst>(R->user_back());
8585       })) {
8586     MaxBitWidth = 8u;
8587 
8588     // Determine if the sign bit of all the roots is known to be zero. If not,
8589     // IsKnownPositive is set to False.
8590     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8591       KnownBits Known = computeKnownBits(R, *DL);
8592       return Known.isNonNegative();
8593     });
8594 
8595     // Determine the maximum number of bits required to store the scalar
8596     // values.
8597     for (auto *Scalar : ToDemote) {
8598       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8599       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8600       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8601     }
8602 
8603     // If we can't prove that the sign bit is zero, we must add one to the
8604     // maximum bit width to account for the unknown sign bit. This preserves
8605     // the existing sign bit so we can safely sign-extend the root back to the
8606     // original type. Otherwise, if we know the sign bit is zero, we will
8607     // zero-extend the root instead.
8608     //
8609     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8610     //        one to the maximum bit width will yield a larger-than-necessary
8611     //        type. In general, we need to add an extra bit only if we can't
8612     //        prove that the upper bit of the original type is equal to the
8613     //        upper bit of the proposed smaller type. If these two bits are the
8614     //        same (either zero or one) we know that sign-extending from the
8615     //        smaller type will result in the same value. Here, since we can't
8616     //        yet prove this, we are just making the proposed smaller type
8617     //        larger to ensure correctness.
8618     if (!IsKnownPositive)
8619       ++MaxBitWidth;
8620   }
8621 
8622   // Round MaxBitWidth up to the next power-of-two.
8623   if (!isPowerOf2_64(MaxBitWidth))
8624     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8625 
8626   // If the maximum bit width we compute is less than the with of the roots'
8627   // type, we can proceed with the narrowing. Otherwise, do nothing.
8628   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8629     return;
8630 
8631   // If we can truncate the root, we must collect additional values that might
8632   // be demoted as a result. That is, those seeded by truncations we will
8633   // modify.
8634   while (!Roots.empty())
8635     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8636 
8637   // Finally, map the values we can demote to the maximum bit with we computed.
8638   for (auto *Scalar : ToDemote)
8639     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8640 }
8641 
8642 namespace {
8643 
8644 /// The SLPVectorizer Pass.
8645 struct SLPVectorizer : public FunctionPass {
8646   SLPVectorizerPass Impl;
8647 
8648   /// Pass identification, replacement for typeid
8649   static char ID;
8650 
8651   explicit SLPVectorizer() : FunctionPass(ID) {
8652     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8653   }
8654 
8655   bool doInitialization(Module &M) override { return false; }
8656 
8657   bool runOnFunction(Function &F) override {
8658     if (skipFunction(F))
8659       return false;
8660 
8661     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8662     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8663     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8664     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8665     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8666     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8667     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8668     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8669     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8670     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8671 
8672     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8673   }
8674 
8675   void getAnalysisUsage(AnalysisUsage &AU) const override {
8676     FunctionPass::getAnalysisUsage(AU);
8677     AU.addRequired<AssumptionCacheTracker>();
8678     AU.addRequired<ScalarEvolutionWrapperPass>();
8679     AU.addRequired<AAResultsWrapperPass>();
8680     AU.addRequired<TargetTransformInfoWrapperPass>();
8681     AU.addRequired<LoopInfoWrapperPass>();
8682     AU.addRequired<DominatorTreeWrapperPass>();
8683     AU.addRequired<DemandedBitsWrapperPass>();
8684     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8685     AU.addRequired<InjectTLIMappingsLegacy>();
8686     AU.addPreserved<LoopInfoWrapperPass>();
8687     AU.addPreserved<DominatorTreeWrapperPass>();
8688     AU.addPreserved<AAResultsWrapperPass>();
8689     AU.addPreserved<GlobalsAAWrapperPass>();
8690     AU.setPreservesCFG();
8691   }
8692 };
8693 
8694 } // end anonymous namespace
8695 
8696 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8697   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8698   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8699   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8700   auto *AA = &AM.getResult<AAManager>(F);
8701   auto *LI = &AM.getResult<LoopAnalysis>(F);
8702   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8703   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8704   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8705   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8706 
8707   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8708   if (!Changed)
8709     return PreservedAnalyses::all();
8710 
8711   PreservedAnalyses PA;
8712   PA.preserveSet<CFGAnalyses>();
8713   return PA;
8714 }
8715 
8716 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8717                                 TargetTransformInfo *TTI_,
8718                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8719                                 LoopInfo *LI_, DominatorTree *DT_,
8720                                 AssumptionCache *AC_, DemandedBits *DB_,
8721                                 OptimizationRemarkEmitter *ORE_) {
8722   if (!RunSLPVectorization)
8723     return false;
8724   SE = SE_;
8725   TTI = TTI_;
8726   TLI = TLI_;
8727   AA = AA_;
8728   LI = LI_;
8729   DT = DT_;
8730   AC = AC_;
8731   DB = DB_;
8732   DL = &F.getParent()->getDataLayout();
8733 
8734   Stores.clear();
8735   GEPs.clear();
8736   bool Changed = false;
8737 
8738   // If the target claims to have no vector registers don't attempt
8739   // vectorization.
8740   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8741     LLVM_DEBUG(
8742         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8743     return false;
8744   }
8745 
8746   // Don't vectorize when the attribute NoImplicitFloat is used.
8747   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8748     return false;
8749 
8750   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8751 
8752   // Use the bottom up slp vectorizer to construct chains that start with
8753   // store instructions.
8754   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8755 
8756   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8757   // delete instructions.
8758 
8759   // Update DFS numbers now so that we can use them for ordering.
8760   DT->updateDFSNumbers();
8761 
8762   // Scan the blocks in the function in post order.
8763   for (auto BB : post_order(&F.getEntryBlock())) {
8764     collectSeedInstructions(BB);
8765 
8766     // Vectorize trees that end at stores.
8767     if (!Stores.empty()) {
8768       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8769                         << " underlying objects.\n");
8770       Changed |= vectorizeStoreChains(R);
8771     }
8772 
8773     // Vectorize trees that end at reductions.
8774     Changed |= vectorizeChainsInBlock(BB, R);
8775 
8776     // Vectorize the index computations of getelementptr instructions. This
8777     // is primarily intended to catch gather-like idioms ending at
8778     // non-consecutive loads.
8779     if (!GEPs.empty()) {
8780       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8781                         << " underlying objects.\n");
8782       Changed |= vectorizeGEPIndices(BB, R);
8783     }
8784   }
8785 
8786   if (Changed) {
8787     R.optimizeGatherSequence();
8788     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8789   }
8790   return Changed;
8791 }
8792 
8793 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8794                                             unsigned Idx) {
8795   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8796                     << "\n");
8797   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8798   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8799   unsigned VF = Chain.size();
8800 
8801   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8802     return false;
8803 
8804   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8805                     << "\n");
8806 
8807   R.buildTree(Chain);
8808   if (R.isTreeTinyAndNotFullyVectorizable())
8809     return false;
8810   if (R.isLoadCombineCandidate())
8811     return false;
8812   R.reorderTopToBottom();
8813   R.reorderBottomToTop();
8814   R.buildExternalUses();
8815 
8816   R.computeMinimumValueSizes();
8817 
8818   InstructionCost Cost = R.getTreeCost();
8819 
8820   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8821   if (Cost < -SLPCostThreshold) {
8822     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8823 
8824     using namespace ore;
8825 
8826     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8827                                         cast<StoreInst>(Chain[0]))
8828                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8829                      << " and with tree size "
8830                      << NV("TreeSize", R.getTreeSize()));
8831 
8832     R.vectorizeTree();
8833     return true;
8834   }
8835 
8836   return false;
8837 }
8838 
8839 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8840                                         BoUpSLP &R) {
8841   // We may run into multiple chains that merge into a single chain. We mark the
8842   // stores that we vectorized so that we don't visit the same store twice.
8843   BoUpSLP::ValueSet VectorizedStores;
8844   bool Changed = false;
8845 
8846   int E = Stores.size();
8847   SmallBitVector Tails(E, false);
8848   int MaxIter = MaxStoreLookup.getValue();
8849   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8850       E, std::make_pair(E, INT_MAX));
8851   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8852   int IterCnt;
8853   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8854                                   &CheckedPairs,
8855                                   &ConsecutiveChain](int K, int Idx) {
8856     if (IterCnt >= MaxIter)
8857       return true;
8858     if (CheckedPairs[Idx].test(K))
8859       return ConsecutiveChain[K].second == 1 &&
8860              ConsecutiveChain[K].first == Idx;
8861     ++IterCnt;
8862     CheckedPairs[Idx].set(K);
8863     CheckedPairs[K].set(Idx);
8864     Optional<int> Diff = getPointersDiff(
8865         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8866         Stores[Idx]->getValueOperand()->getType(),
8867         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8868     if (!Diff || *Diff == 0)
8869       return false;
8870     int Val = *Diff;
8871     if (Val < 0) {
8872       if (ConsecutiveChain[Idx].second > -Val) {
8873         Tails.set(K);
8874         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8875       }
8876       return false;
8877     }
8878     if (ConsecutiveChain[K].second <= Val)
8879       return false;
8880 
8881     Tails.set(Idx);
8882     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8883     return Val == 1;
8884   };
8885   // Do a quadratic search on all of the given stores in reverse order and find
8886   // all of the pairs of stores that follow each other.
8887   for (int Idx = E - 1; Idx >= 0; --Idx) {
8888     // If a store has multiple consecutive store candidates, search according
8889     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8890     // This is because usually pairing with immediate succeeding or preceding
8891     // candidate create the best chance to find slp vectorization opportunity.
8892     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8893     IterCnt = 0;
8894     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8895       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8896           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8897         break;
8898   }
8899 
8900   // Tracks if we tried to vectorize stores starting from the given tail
8901   // already.
8902   SmallBitVector TriedTails(E, false);
8903   // For stores that start but don't end a link in the chain:
8904   for (int Cnt = E; Cnt > 0; --Cnt) {
8905     int I = Cnt - 1;
8906     if (ConsecutiveChain[I].first == E || Tails.test(I))
8907       continue;
8908     // We found a store instr that starts a chain. Now follow the chain and try
8909     // to vectorize it.
8910     BoUpSLP::ValueList Operands;
8911     // Collect the chain into a list.
8912     while (I != E && !VectorizedStores.count(Stores[I])) {
8913       Operands.push_back(Stores[I]);
8914       Tails.set(I);
8915       if (ConsecutiveChain[I].second != 1) {
8916         // Mark the new end in the chain and go back, if required. It might be
8917         // required if the original stores come in reversed order, for example.
8918         if (ConsecutiveChain[I].first != E &&
8919             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8920             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8921           TriedTails.set(I);
8922           Tails.reset(ConsecutiveChain[I].first);
8923           if (Cnt < ConsecutiveChain[I].first + 2)
8924             Cnt = ConsecutiveChain[I].first + 2;
8925         }
8926         break;
8927       }
8928       // Move to the next value in the chain.
8929       I = ConsecutiveChain[I].first;
8930     }
8931     assert(!Operands.empty() && "Expected non-empty list of stores.");
8932 
8933     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8934     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8935     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8936 
8937     unsigned MinVF = R.getMinVF(EltSize);
8938     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8939                               MaxElts);
8940 
8941     // FIXME: Is division-by-2 the correct step? Should we assert that the
8942     // register size is a power-of-2?
8943     unsigned StartIdx = 0;
8944     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8945       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8946         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8947         if (!VectorizedStores.count(Slice.front()) &&
8948             !VectorizedStores.count(Slice.back()) &&
8949             vectorizeStoreChain(Slice, R, Cnt)) {
8950           // Mark the vectorized stores so that we don't vectorize them again.
8951           VectorizedStores.insert(Slice.begin(), Slice.end());
8952           Changed = true;
8953           // If we vectorized initial block, no need to try to vectorize it
8954           // again.
8955           if (Cnt == StartIdx)
8956             StartIdx += Size;
8957           Cnt += Size;
8958           continue;
8959         }
8960         ++Cnt;
8961       }
8962       // Check if the whole array was vectorized already - exit.
8963       if (StartIdx >= Operands.size())
8964         break;
8965     }
8966   }
8967 
8968   return Changed;
8969 }
8970 
8971 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8972   // Initialize the collections. We will make a single pass over the block.
8973   Stores.clear();
8974   GEPs.clear();
8975 
8976   // Visit the store and getelementptr instructions in BB and organize them in
8977   // Stores and GEPs according to the underlying objects of their pointer
8978   // operands.
8979   for (Instruction &I : *BB) {
8980     // Ignore store instructions that are volatile or have a pointer operand
8981     // that doesn't point to a scalar type.
8982     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8983       if (!SI->isSimple())
8984         continue;
8985       if (!isValidElementType(SI->getValueOperand()->getType()))
8986         continue;
8987       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8988     }
8989 
8990     // Ignore getelementptr instructions that have more than one index, a
8991     // constant index, or a pointer operand that doesn't point to a scalar
8992     // type.
8993     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8994       auto Idx = GEP->idx_begin()->get();
8995       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8996         continue;
8997       if (!isValidElementType(Idx->getType()))
8998         continue;
8999       if (GEP->getType()->isVectorTy())
9000         continue;
9001       GEPs[GEP->getPointerOperand()].push_back(GEP);
9002     }
9003   }
9004 }
9005 
9006 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
9007   if (!A || !B)
9008     return false;
9009   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
9010     return false;
9011   Value *VL[] = {A, B};
9012   return tryToVectorizeList(VL, R);
9013 }
9014 
9015 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
9016                                            bool LimitForRegisterSize) {
9017   if (VL.size() < 2)
9018     return false;
9019 
9020   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
9021                     << VL.size() << ".\n");
9022 
9023   // Check that all of the parts are instructions of the same type,
9024   // we permit an alternate opcode via InstructionsState.
9025   InstructionsState S = getSameOpcode(VL);
9026   if (!S.getOpcode())
9027     return false;
9028 
9029   Instruction *I0 = cast<Instruction>(S.OpValue);
9030   // Make sure invalid types (including vector type) are rejected before
9031   // determining vectorization factor for scalar instructions.
9032   for (Value *V : VL) {
9033     Type *Ty = V->getType();
9034     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
9035       // NOTE: the following will give user internal llvm type name, which may
9036       // not be useful.
9037       R.getORE()->emit([&]() {
9038         std::string type_str;
9039         llvm::raw_string_ostream rso(type_str);
9040         Ty->print(rso);
9041         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
9042                << "Cannot SLP vectorize list: type "
9043                << rso.str() + " is unsupported by vectorizer";
9044       });
9045       return false;
9046     }
9047   }
9048 
9049   unsigned Sz = R.getVectorElementSize(I0);
9050   unsigned MinVF = R.getMinVF(Sz);
9051   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9052   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9053   if (MaxVF < 2) {
9054     R.getORE()->emit([&]() {
9055       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9056              << "Cannot SLP vectorize list: vectorization factor "
9057              << "less than 2 is not supported";
9058     });
9059     return false;
9060   }
9061 
9062   bool Changed = false;
9063   bool CandidateFound = false;
9064   InstructionCost MinCost = SLPCostThreshold.getValue();
9065   Type *ScalarTy = VL[0]->getType();
9066   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9067     ScalarTy = IE->getOperand(1)->getType();
9068 
9069   unsigned NextInst = 0, MaxInst = VL.size();
9070   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9071     // No actual vectorization should happen, if number of parts is the same as
9072     // provided vectorization factor (i.e. the scalar type is used for vector
9073     // code during codegen).
9074     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9075     if (TTI->getNumberOfParts(VecTy) == VF)
9076       continue;
9077     for (unsigned I = NextInst; I < MaxInst; ++I) {
9078       unsigned OpsWidth = 0;
9079 
9080       if (I + VF > MaxInst)
9081         OpsWidth = MaxInst - I;
9082       else
9083         OpsWidth = VF;
9084 
9085       if (!isPowerOf2_32(OpsWidth))
9086         continue;
9087 
9088       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9089           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9090         break;
9091 
9092       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9093       // Check that a previous iteration of this loop did not delete the Value.
9094       if (llvm::any_of(Ops, [&R](Value *V) {
9095             auto *I = dyn_cast<Instruction>(V);
9096             return I && R.isDeleted(I);
9097           }))
9098         continue;
9099 
9100       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9101                         << "\n");
9102 
9103       R.buildTree(Ops);
9104       if (R.isTreeTinyAndNotFullyVectorizable())
9105         continue;
9106       R.reorderTopToBottom();
9107       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9108       R.buildExternalUses();
9109 
9110       R.computeMinimumValueSizes();
9111       InstructionCost Cost = R.getTreeCost();
9112       CandidateFound = true;
9113       MinCost = std::min(MinCost, Cost);
9114 
9115       if (Cost < -SLPCostThreshold) {
9116         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9117         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9118                                                     cast<Instruction>(Ops[0]))
9119                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9120                                  << " and with tree size "
9121                                  << ore::NV("TreeSize", R.getTreeSize()));
9122 
9123         R.vectorizeTree();
9124         // Move to the next bundle.
9125         I += VF - 1;
9126         NextInst = I + 1;
9127         Changed = true;
9128       }
9129     }
9130   }
9131 
9132   if (!Changed && CandidateFound) {
9133     R.getORE()->emit([&]() {
9134       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9135              << "List vectorization was possible but not beneficial with cost "
9136              << ore::NV("Cost", MinCost) << " >= "
9137              << ore::NV("Treshold", -SLPCostThreshold);
9138     });
9139   } else if (!Changed) {
9140     R.getORE()->emit([&]() {
9141       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9142              << "Cannot SLP vectorize list: vectorization was impossible"
9143              << " with available vectorization factors";
9144     });
9145   }
9146   return Changed;
9147 }
9148 
9149 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9150   if (!I)
9151     return false;
9152 
9153   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9154     return false;
9155 
9156   Value *P = I->getParent();
9157 
9158   // Vectorize in current basic block only.
9159   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9160   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9161   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9162     return false;
9163 
9164   // Try to vectorize V.
9165   if (tryToVectorizePair(Op0, Op1, R))
9166     return true;
9167 
9168   auto *A = dyn_cast<BinaryOperator>(Op0);
9169   auto *B = dyn_cast<BinaryOperator>(Op1);
9170   // Try to skip B.
9171   if (B && B->hasOneUse()) {
9172     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9173     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9174     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9175       return true;
9176     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9177       return true;
9178   }
9179 
9180   // Try to skip A.
9181   if (A && A->hasOneUse()) {
9182     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9183     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9184     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9185       return true;
9186     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9187       return true;
9188   }
9189   return false;
9190 }
9191 
9192 namespace {
9193 
9194 /// Model horizontal reductions.
9195 ///
9196 /// A horizontal reduction is a tree of reduction instructions that has values
9197 /// that can be put into a vector as its leaves. For example:
9198 ///
9199 /// mul mul mul mul
9200 ///  \  /    \  /
9201 ///   +       +
9202 ///    \     /
9203 ///       +
9204 /// This tree has "mul" as its leaf values and "+" as its reduction
9205 /// instructions. A reduction can feed into a store or a binary operation
9206 /// feeding a phi.
9207 ///    ...
9208 ///    \  /
9209 ///     +
9210 ///     |
9211 ///  phi +=
9212 ///
9213 ///  Or:
9214 ///    ...
9215 ///    \  /
9216 ///     +
9217 ///     |
9218 ///   *p =
9219 ///
9220 class HorizontalReduction {
9221   using ReductionOpsType = SmallVector<Value *, 16>;
9222   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9223   ReductionOpsListType ReductionOps;
9224   SmallVector<Value *, 32> ReducedVals;
9225   // Use map vector to make stable output.
9226   MapVector<Instruction *, Value *> ExtraArgs;
9227   WeakTrackingVH ReductionRoot;
9228   /// The type of reduction operation.
9229   RecurKind RdxKind;
9230 
9231   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9232 
9233   static bool isCmpSelMinMax(Instruction *I) {
9234     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9235            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9236   }
9237 
9238   // And/or are potentially poison-safe logical patterns like:
9239   // select x, y, false
9240   // select x, true, y
9241   static bool isBoolLogicOp(Instruction *I) {
9242     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9243            match(I, m_LogicalOr(m_Value(), m_Value()));
9244   }
9245 
9246   /// Checks if instruction is associative and can be vectorized.
9247   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9248     if (Kind == RecurKind::None)
9249       return false;
9250 
9251     // Integer ops that map to select instructions or intrinsics are fine.
9252     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9253         isBoolLogicOp(I))
9254       return true;
9255 
9256     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9257       // FP min/max are associative except for NaN and -0.0. We do not
9258       // have to rule out -0.0 here because the intrinsic semantics do not
9259       // specify a fixed result for it.
9260       return I->getFastMathFlags().noNaNs();
9261     }
9262 
9263     return I->isAssociative();
9264   }
9265 
9266   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9267     // Poison-safe 'or' takes the form: select X, true, Y
9268     // To make that work with the normal operand processing, we skip the
9269     // true value operand.
9270     // TODO: Change the code and data structures to handle this without a hack.
9271     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9272       return I->getOperand(2);
9273     return I->getOperand(Index);
9274   }
9275 
9276   /// Checks if the ParentStackElem.first should be marked as a reduction
9277   /// operation with an extra argument or as extra argument itself.
9278   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9279                     Value *ExtraArg) {
9280     if (ExtraArgs.count(ParentStackElem.first)) {
9281       ExtraArgs[ParentStackElem.first] = nullptr;
9282       // We ran into something like:
9283       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9284       // The whole ParentStackElem.first should be considered as an extra value
9285       // in this case.
9286       // Do not perform analysis of remaining operands of ParentStackElem.first
9287       // instruction, this whole instruction is an extra argument.
9288       ParentStackElem.second = INVALID_OPERAND_INDEX;
9289     } else {
9290       // We ran into something like:
9291       // ParentStackElem.first += ... + ExtraArg + ...
9292       ExtraArgs[ParentStackElem.first] = ExtraArg;
9293     }
9294   }
9295 
9296   /// Creates reduction operation with the current opcode.
9297   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9298                          Value *RHS, const Twine &Name, bool UseSelect) {
9299     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9300     switch (Kind) {
9301     case RecurKind::Or:
9302       if (UseSelect &&
9303           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9304         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9305       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9306                                  Name);
9307     case RecurKind::And:
9308       if (UseSelect &&
9309           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9310         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9311       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9312                                  Name);
9313     case RecurKind::Add:
9314     case RecurKind::Mul:
9315     case RecurKind::Xor:
9316     case RecurKind::FAdd:
9317     case RecurKind::FMul:
9318       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9319                                  Name);
9320     case RecurKind::FMax:
9321       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9322     case RecurKind::FMin:
9323       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9324     case RecurKind::SMax:
9325       if (UseSelect) {
9326         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9327         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9328       }
9329       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9330     case RecurKind::SMin:
9331       if (UseSelect) {
9332         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9333         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9334       }
9335       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9336     case RecurKind::UMax:
9337       if (UseSelect) {
9338         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9339         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9340       }
9341       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9342     case RecurKind::UMin:
9343       if (UseSelect) {
9344         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9345         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9346       }
9347       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9348     default:
9349       llvm_unreachable("Unknown reduction operation.");
9350     }
9351   }
9352 
9353   /// Creates reduction operation with the current opcode with the IR flags
9354   /// from \p ReductionOps.
9355   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9356                          Value *RHS, const Twine &Name,
9357                          const ReductionOpsListType &ReductionOps) {
9358     bool UseSelect = ReductionOps.size() == 2 ||
9359                      // Logical or/and.
9360                      (ReductionOps.size() == 1 &&
9361                       isa<SelectInst>(ReductionOps.front().front()));
9362     assert((!UseSelect || ReductionOps.size() != 2 ||
9363             isa<SelectInst>(ReductionOps[1][0])) &&
9364            "Expected cmp + select pairs for reduction");
9365     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9366     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9367       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9368         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9369         propagateIRFlags(Op, ReductionOps[1]);
9370         return Op;
9371       }
9372     }
9373     propagateIRFlags(Op, ReductionOps[0]);
9374     return Op;
9375   }
9376 
9377   /// Creates reduction operation with the current opcode with the IR flags
9378   /// from \p I.
9379   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9380                          Value *RHS, const Twine &Name, Instruction *I) {
9381     auto *SelI = dyn_cast<SelectInst>(I);
9382     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9383     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9384       if (auto *Sel = dyn_cast<SelectInst>(Op))
9385         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9386     }
9387     propagateIRFlags(Op, I);
9388     return Op;
9389   }
9390 
9391   static RecurKind getRdxKind(Instruction *I) {
9392     assert(I && "Expected instruction for reduction matching");
9393     if (match(I, m_Add(m_Value(), m_Value())))
9394       return RecurKind::Add;
9395     if (match(I, m_Mul(m_Value(), m_Value())))
9396       return RecurKind::Mul;
9397     if (match(I, m_And(m_Value(), m_Value())) ||
9398         match(I, m_LogicalAnd(m_Value(), m_Value())))
9399       return RecurKind::And;
9400     if (match(I, m_Or(m_Value(), m_Value())) ||
9401         match(I, m_LogicalOr(m_Value(), m_Value())))
9402       return RecurKind::Or;
9403     if (match(I, m_Xor(m_Value(), m_Value())))
9404       return RecurKind::Xor;
9405     if (match(I, m_FAdd(m_Value(), m_Value())))
9406       return RecurKind::FAdd;
9407     if (match(I, m_FMul(m_Value(), m_Value())))
9408       return RecurKind::FMul;
9409 
9410     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9411       return RecurKind::FMax;
9412     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9413       return RecurKind::FMin;
9414 
9415     // This matches either cmp+select or intrinsics. SLP is expected to handle
9416     // either form.
9417     // TODO: If we are canonicalizing to intrinsics, we can remove several
9418     //       special-case paths that deal with selects.
9419     if (match(I, m_SMax(m_Value(), m_Value())))
9420       return RecurKind::SMax;
9421     if (match(I, m_SMin(m_Value(), m_Value())))
9422       return RecurKind::SMin;
9423     if (match(I, m_UMax(m_Value(), m_Value())))
9424       return RecurKind::UMax;
9425     if (match(I, m_UMin(m_Value(), m_Value())))
9426       return RecurKind::UMin;
9427 
9428     if (auto *Select = dyn_cast<SelectInst>(I)) {
9429       // Try harder: look for min/max pattern based on instructions producing
9430       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9431       // During the intermediate stages of SLP, it's very common to have
9432       // pattern like this (since optimizeGatherSequence is run only once
9433       // at the end):
9434       // %1 = extractelement <2 x i32> %a, i32 0
9435       // %2 = extractelement <2 x i32> %a, i32 1
9436       // %cond = icmp sgt i32 %1, %2
9437       // %3 = extractelement <2 x i32> %a, i32 0
9438       // %4 = extractelement <2 x i32> %a, i32 1
9439       // %select = select i1 %cond, i32 %3, i32 %4
9440       CmpInst::Predicate Pred;
9441       Instruction *L1;
9442       Instruction *L2;
9443 
9444       Value *LHS = Select->getTrueValue();
9445       Value *RHS = Select->getFalseValue();
9446       Value *Cond = Select->getCondition();
9447 
9448       // TODO: Support inverse predicates.
9449       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9450         if (!isa<ExtractElementInst>(RHS) ||
9451             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9452           return RecurKind::None;
9453       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9454         if (!isa<ExtractElementInst>(LHS) ||
9455             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9456           return RecurKind::None;
9457       } else {
9458         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9459           return RecurKind::None;
9460         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9461             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9462             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9463           return RecurKind::None;
9464       }
9465 
9466       switch (Pred) {
9467       default:
9468         return RecurKind::None;
9469       case CmpInst::ICMP_SGT:
9470       case CmpInst::ICMP_SGE:
9471         return RecurKind::SMax;
9472       case CmpInst::ICMP_SLT:
9473       case CmpInst::ICMP_SLE:
9474         return RecurKind::SMin;
9475       case CmpInst::ICMP_UGT:
9476       case CmpInst::ICMP_UGE:
9477         return RecurKind::UMax;
9478       case CmpInst::ICMP_ULT:
9479       case CmpInst::ICMP_ULE:
9480         return RecurKind::UMin;
9481       }
9482     }
9483     return RecurKind::None;
9484   }
9485 
9486   /// Get the index of the first operand.
9487   static unsigned getFirstOperandIndex(Instruction *I) {
9488     return isCmpSelMinMax(I) ? 1 : 0;
9489   }
9490 
9491   /// Total number of operands in the reduction operation.
9492   static unsigned getNumberOfOperands(Instruction *I) {
9493     return isCmpSelMinMax(I) ? 3 : 2;
9494   }
9495 
9496   /// Checks if the instruction is in basic block \p BB.
9497   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9498   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9499     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9500       auto *Sel = cast<SelectInst>(I);
9501       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9502       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9503     }
9504     return I->getParent() == BB;
9505   }
9506 
9507   /// Expected number of uses for reduction operations/reduced values.
9508   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9509     if (IsCmpSelMinMax) {
9510       // SelectInst must be used twice while the condition op must have single
9511       // use only.
9512       if (auto *Sel = dyn_cast<SelectInst>(I))
9513         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9514       return I->hasNUses(2);
9515     }
9516 
9517     // Arithmetic reduction operation must be used once only.
9518     return I->hasOneUse();
9519   }
9520 
9521   /// Initializes the list of reduction operations.
9522   void initReductionOps(Instruction *I) {
9523     if (isCmpSelMinMax(I))
9524       ReductionOps.assign(2, ReductionOpsType());
9525     else
9526       ReductionOps.assign(1, ReductionOpsType());
9527   }
9528 
9529   /// Add all reduction operations for the reduction instruction \p I.
9530   void addReductionOps(Instruction *I) {
9531     if (isCmpSelMinMax(I)) {
9532       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9533       ReductionOps[1].emplace_back(I);
9534     } else {
9535       ReductionOps[0].emplace_back(I);
9536     }
9537   }
9538 
9539   static Value *getLHS(RecurKind Kind, Instruction *I) {
9540     if (Kind == RecurKind::None)
9541       return nullptr;
9542     return I->getOperand(getFirstOperandIndex(I));
9543   }
9544   static Value *getRHS(RecurKind Kind, Instruction *I) {
9545     if (Kind == RecurKind::None)
9546       return nullptr;
9547     return I->getOperand(getFirstOperandIndex(I) + 1);
9548   }
9549 
9550 public:
9551   HorizontalReduction() = default;
9552 
9553   /// Try to find a reduction tree.
9554   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9555     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9556            "Phi needs to use the binary operator");
9557     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9558             isa<IntrinsicInst>(Inst)) &&
9559            "Expected binop, select, or intrinsic for reduction matching");
9560     RdxKind = getRdxKind(Inst);
9561 
9562     // We could have a initial reductions that is not an add.
9563     //  r *= v1 + v2 + v3 + v4
9564     // In such a case start looking for a tree rooted in the first '+'.
9565     if (Phi) {
9566       if (getLHS(RdxKind, Inst) == Phi) {
9567         Phi = nullptr;
9568         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9569         if (!Inst)
9570           return false;
9571         RdxKind = getRdxKind(Inst);
9572       } else if (getRHS(RdxKind, Inst) == Phi) {
9573         Phi = nullptr;
9574         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9575         if (!Inst)
9576           return false;
9577         RdxKind = getRdxKind(Inst);
9578       }
9579     }
9580 
9581     if (!isVectorizable(RdxKind, Inst))
9582       return false;
9583 
9584     // Analyze "regular" integer/FP types for reductions - no target-specific
9585     // types or pointers.
9586     Type *Ty = Inst->getType();
9587     if (!isValidElementType(Ty) || Ty->isPointerTy())
9588       return false;
9589 
9590     // Though the ultimate reduction may have multiple uses, its condition must
9591     // have only single use.
9592     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9593       if (!Sel->getCondition()->hasOneUse())
9594         return false;
9595 
9596     ReductionRoot = Inst;
9597 
9598     // The opcode for leaf values that we perform a reduction on.
9599     // For example: load(x) + load(y) + load(z) + fptoui(w)
9600     // The leaf opcode for 'w' does not match, so we don't include it as a
9601     // potential candidate for the reduction.
9602     unsigned LeafOpcode = 0;
9603 
9604     // Post-order traverse the reduction tree starting at Inst. We only handle
9605     // true trees containing binary operators or selects.
9606     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9607     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9608     initReductionOps(Inst);
9609     while (!Stack.empty()) {
9610       Instruction *TreeN = Stack.back().first;
9611       unsigned EdgeToVisit = Stack.back().second++;
9612       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9613       bool IsReducedValue = TreeRdxKind != RdxKind;
9614 
9615       // Postorder visit.
9616       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9617         if (IsReducedValue)
9618           ReducedVals.push_back(TreeN);
9619         else {
9620           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9621           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9622             // Check if TreeN is an extra argument of its parent operation.
9623             if (Stack.size() <= 1) {
9624               // TreeN can't be an extra argument as it is a root reduction
9625               // operation.
9626               return false;
9627             }
9628             // Yes, TreeN is an extra argument, do not add it to a list of
9629             // reduction operations.
9630             // Stack[Stack.size() - 2] always points to the parent operation.
9631             markExtraArg(Stack[Stack.size() - 2], TreeN);
9632             ExtraArgs.erase(TreeN);
9633           } else
9634             addReductionOps(TreeN);
9635         }
9636         // Retract.
9637         Stack.pop_back();
9638         continue;
9639       }
9640 
9641       // Visit operands.
9642       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9643       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9644       if (!EdgeInst) {
9645         // Edge value is not a reduction instruction or a leaf instruction.
9646         // (It may be a constant, function argument, or something else.)
9647         markExtraArg(Stack.back(), EdgeVal);
9648         continue;
9649       }
9650       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9651       // Continue analysis if the next operand is a reduction operation or
9652       // (possibly) a leaf value. If the leaf value opcode is not set,
9653       // the first met operation != reduction operation is considered as the
9654       // leaf opcode.
9655       // Only handle trees in the current basic block.
9656       // Each tree node needs to have minimal number of users except for the
9657       // ultimate reduction.
9658       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9659       if (EdgeInst != Phi && EdgeInst != Inst &&
9660           hasSameParent(EdgeInst, Inst->getParent()) &&
9661           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9662           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9663         if (IsRdxInst) {
9664           // We need to be able to reassociate the reduction operations.
9665           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9666             // I is an extra argument for TreeN (its parent operation).
9667             markExtraArg(Stack.back(), EdgeInst);
9668             continue;
9669           }
9670         } else if (!LeafOpcode) {
9671           LeafOpcode = EdgeInst->getOpcode();
9672         }
9673         Stack.push_back(
9674             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9675         continue;
9676       }
9677       // I is an extra argument for TreeN (its parent operation).
9678       markExtraArg(Stack.back(), EdgeInst);
9679     }
9680     return true;
9681   }
9682 
9683   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9684   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9685     // If there are a sufficient number of reduction values, reduce
9686     // to a nearby power-of-2. We can safely generate oversized
9687     // vectors and rely on the backend to split them to legal sizes.
9688     unsigned NumReducedVals = ReducedVals.size();
9689     if (NumReducedVals < 4)
9690       return nullptr;
9691 
9692     // Intersect the fast-math-flags from all reduction operations.
9693     FastMathFlags RdxFMF;
9694     RdxFMF.set();
9695     for (ReductionOpsType &RdxOp : ReductionOps) {
9696       for (Value *RdxVal : RdxOp) {
9697         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9698           RdxFMF &= FPMO->getFastMathFlags();
9699       }
9700     }
9701 
9702     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9703     Builder.setFastMathFlags(RdxFMF);
9704 
9705     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9706     // The same extra argument may be used several times, so log each attempt
9707     // to use it.
9708     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9709       assert(Pair.first && "DebugLoc must be set.");
9710       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9711     }
9712 
9713     // The compare instruction of a min/max is the insertion point for new
9714     // instructions and may be replaced with a new compare instruction.
9715     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9716       assert(isa<SelectInst>(RdxRootInst) &&
9717              "Expected min/max reduction to have select root instruction");
9718       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9719       assert(isa<Instruction>(ScalarCond) &&
9720              "Expected min/max reduction to have compare condition");
9721       return cast<Instruction>(ScalarCond);
9722     };
9723 
9724     // The reduction root is used as the insertion point for new instructions,
9725     // so set it as externally used to prevent it from being deleted.
9726     ExternallyUsedValues[ReductionRoot];
9727     SmallVector<Value *, 16> IgnoreList;
9728     for (ReductionOpsType &RdxOp : ReductionOps)
9729       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9730 
9731     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9732     if (NumReducedVals > ReduxWidth) {
9733       // In the loop below, we are building a tree based on a window of
9734       // 'ReduxWidth' values.
9735       // If the operands of those values have common traits (compare predicate,
9736       // constant operand, etc), then we want to group those together to
9737       // minimize the cost of the reduction.
9738 
9739       // TODO: This should be extended to count common operands for
9740       //       compares and binops.
9741 
9742       // Step 1: Count the number of times each compare predicate occurs.
9743       SmallDenseMap<unsigned, unsigned> PredCountMap;
9744       for (Value *RdxVal : ReducedVals) {
9745         CmpInst::Predicate Pred;
9746         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9747           ++PredCountMap[Pred];
9748       }
9749       // Step 2: Sort the values so the most common predicates come first.
9750       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9751         CmpInst::Predicate PredA, PredB;
9752         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9753             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9754           return PredCountMap[PredA] > PredCountMap[PredB];
9755         }
9756         return false;
9757       });
9758     }
9759 
9760     Value *VectorizedTree = nullptr;
9761     unsigned i = 0;
9762     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9763       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9764       V.buildTree(VL, IgnoreList);
9765       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9766         break;
9767       if (V.isLoadCombineReductionCandidate(RdxKind))
9768         break;
9769       V.reorderTopToBottom();
9770       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9771       V.buildExternalUses(ExternallyUsedValues);
9772 
9773       // For a poison-safe boolean logic reduction, do not replace select
9774       // instructions with logic ops. All reduced values will be frozen (see
9775       // below) to prevent leaking poison.
9776       if (isa<SelectInst>(ReductionRoot) &&
9777           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9778           NumReducedVals != ReduxWidth)
9779         break;
9780 
9781       V.computeMinimumValueSizes();
9782 
9783       // Estimate cost.
9784       InstructionCost TreeCost =
9785           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9786       InstructionCost ReductionCost =
9787           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9788       InstructionCost Cost = TreeCost + ReductionCost;
9789       if (!Cost.isValid()) {
9790         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9791         return nullptr;
9792       }
9793       if (Cost >= -SLPCostThreshold) {
9794         V.getORE()->emit([&]() {
9795           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9796                                           cast<Instruction>(VL[0]))
9797                  << "Vectorizing horizontal reduction is possible"
9798                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9799                  << " and threshold "
9800                  << ore::NV("Threshold", -SLPCostThreshold);
9801         });
9802         break;
9803       }
9804 
9805       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9806                         << Cost << ". (HorRdx)\n");
9807       V.getORE()->emit([&]() {
9808         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9809                                   cast<Instruction>(VL[0]))
9810                << "Vectorized horizontal reduction with cost "
9811                << ore::NV("Cost", Cost) << " and with tree size "
9812                << ore::NV("TreeSize", V.getTreeSize());
9813       });
9814 
9815       // Vectorize a tree.
9816       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9817       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9818 
9819       // Emit a reduction. If the root is a select (min/max idiom), the insert
9820       // point is the compare condition of that select.
9821       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9822       if (isCmpSelMinMax(RdxRootInst))
9823         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9824       else
9825         Builder.SetInsertPoint(RdxRootInst);
9826 
9827       // To prevent poison from leaking across what used to be sequential, safe,
9828       // scalar boolean logic operations, the reduction operand must be frozen.
9829       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9830         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9831 
9832       Value *ReducedSubTree =
9833           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9834 
9835       if (!VectorizedTree) {
9836         // Initialize the final value in the reduction.
9837         VectorizedTree = ReducedSubTree;
9838       } else {
9839         // Update the final value in the reduction.
9840         Builder.SetCurrentDebugLocation(Loc);
9841         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9842                                   ReducedSubTree, "op.rdx", ReductionOps);
9843       }
9844       i += ReduxWidth;
9845       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9846     }
9847 
9848     if (VectorizedTree) {
9849       // Finish the reduction.
9850       for (; i < NumReducedVals; ++i) {
9851         auto *I = cast<Instruction>(ReducedVals[i]);
9852         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9853         VectorizedTree =
9854             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9855       }
9856       for (auto &Pair : ExternallyUsedValues) {
9857         // Add each externally used value to the final reduction.
9858         for (auto *I : Pair.second) {
9859           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9860           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9861                                     Pair.first, "op.extra", I);
9862         }
9863       }
9864 
9865       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9866 
9867       // The original scalar reduction is expected to have no remaining
9868       // uses outside the reduction tree itself.  Assert that we got this
9869       // correct, replace internal uses with undef, and mark for eventual
9870       // deletion.
9871 #ifndef NDEBUG
9872       SmallSet<Value *, 4> IgnoreSet;
9873       IgnoreSet.insert(IgnoreList.begin(), IgnoreList.end());
9874 #endif
9875       for (auto *Ignore : IgnoreList) {
9876 #ifndef NDEBUG
9877         for (auto *U : Ignore->users()) {
9878           assert(IgnoreSet.count(U));
9879         }
9880 #endif
9881         if (!Ignore->use_empty()) {
9882           Value *Undef = UndefValue::get(Ignore->getType());
9883           Ignore->replaceAllUsesWith(Undef);
9884         }
9885         V.eraseInstruction(cast<Instruction>(Ignore));
9886       }
9887     }
9888     return VectorizedTree;
9889   }
9890 
9891   unsigned numReductionValues() const { return ReducedVals.size(); }
9892 
9893 private:
9894   /// Calculate the cost of a reduction.
9895   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9896                                    Value *FirstReducedVal, unsigned ReduxWidth,
9897                                    FastMathFlags FMF) {
9898     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9899     Type *ScalarTy = FirstReducedVal->getType();
9900     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9901     InstructionCost VectorCost, ScalarCost;
9902     switch (RdxKind) {
9903     case RecurKind::Add:
9904     case RecurKind::Mul:
9905     case RecurKind::Or:
9906     case RecurKind::And:
9907     case RecurKind::Xor:
9908     case RecurKind::FAdd:
9909     case RecurKind::FMul: {
9910       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9911       VectorCost =
9912           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9913       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9914       break;
9915     }
9916     case RecurKind::FMax:
9917     case RecurKind::FMin: {
9918       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9919       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9920       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9921                                                /*IsUnsigned=*/false, CostKind);
9922       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9923       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9924                                            SclCondTy, RdxPred, CostKind) +
9925                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9926                                            SclCondTy, RdxPred, CostKind);
9927       break;
9928     }
9929     case RecurKind::SMax:
9930     case RecurKind::SMin:
9931     case RecurKind::UMax:
9932     case RecurKind::UMin: {
9933       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9934       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9935       bool IsUnsigned =
9936           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9937       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9938                                                CostKind);
9939       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9940       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9941                                            SclCondTy, RdxPred, CostKind) +
9942                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9943                                            SclCondTy, RdxPred, CostKind);
9944       break;
9945     }
9946     default:
9947       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9948     }
9949 
9950     // Scalar cost is repeated for N-1 elements.
9951     ScalarCost *= (ReduxWidth - 1);
9952     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9953                       << " for reduction that starts with " << *FirstReducedVal
9954                       << " (It is a splitting reduction)\n");
9955     return VectorCost - ScalarCost;
9956   }
9957 
9958   /// Emit a horizontal reduction of the vectorized value.
9959   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9960                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9961     assert(VectorizedValue && "Need to have a vectorized tree node");
9962     assert(isPowerOf2_32(ReduxWidth) &&
9963            "We only handle power-of-two reductions for now");
9964     assert(RdxKind != RecurKind::FMulAdd &&
9965            "A call to the llvm.fmuladd intrinsic is not handled yet");
9966 
9967     ++NumVectorInstructions;
9968     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9969   }
9970 };
9971 
9972 } // end anonymous namespace
9973 
9974 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9975   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9976     return cast<FixedVectorType>(IE->getType())->getNumElements();
9977 
9978   unsigned AggregateSize = 1;
9979   auto *IV = cast<InsertValueInst>(InsertInst);
9980   Type *CurrentType = IV->getType();
9981   do {
9982     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9983       for (auto *Elt : ST->elements())
9984         if (Elt != ST->getElementType(0)) // check homogeneity
9985           return None;
9986       AggregateSize *= ST->getNumElements();
9987       CurrentType = ST->getElementType(0);
9988     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9989       AggregateSize *= AT->getNumElements();
9990       CurrentType = AT->getElementType();
9991     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9992       AggregateSize *= VT->getNumElements();
9993       return AggregateSize;
9994     } else if (CurrentType->isSingleValueType()) {
9995       return AggregateSize;
9996     } else {
9997       return None;
9998     }
9999   } while (true);
10000 }
10001 
10002 static void findBuildAggregate_rec(Instruction *LastInsertInst,
10003                                    TargetTransformInfo *TTI,
10004                                    SmallVectorImpl<Value *> &BuildVectorOpds,
10005                                    SmallVectorImpl<Value *> &InsertElts,
10006                                    unsigned OperandOffset) {
10007   do {
10008     Value *InsertedOperand = LastInsertInst->getOperand(1);
10009     Optional<unsigned> OperandIndex =
10010         getInsertIndex(LastInsertInst, OperandOffset);
10011     if (!OperandIndex)
10012       return;
10013     if (isa<InsertElementInst>(InsertedOperand) ||
10014         isa<InsertValueInst>(InsertedOperand)) {
10015       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
10016                              BuildVectorOpds, InsertElts, *OperandIndex);
10017 
10018     } else {
10019       BuildVectorOpds[*OperandIndex] = InsertedOperand;
10020       InsertElts[*OperandIndex] = LastInsertInst;
10021     }
10022     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
10023   } while (LastInsertInst != nullptr &&
10024            (isa<InsertValueInst>(LastInsertInst) ||
10025             isa<InsertElementInst>(LastInsertInst)) &&
10026            LastInsertInst->hasOneUse());
10027 }
10028 
10029 /// Recognize construction of vectors like
10030 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
10031 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
10032 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
10033 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
10034 ///  starting from the last insertelement or insertvalue instruction.
10035 ///
10036 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
10037 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
10038 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
10039 ///
10040 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
10041 ///
10042 /// \return true if it matches.
10043 static bool findBuildAggregate(Instruction *LastInsertInst,
10044                                TargetTransformInfo *TTI,
10045                                SmallVectorImpl<Value *> &BuildVectorOpds,
10046                                SmallVectorImpl<Value *> &InsertElts) {
10047 
10048   assert((isa<InsertElementInst>(LastInsertInst) ||
10049           isa<InsertValueInst>(LastInsertInst)) &&
10050          "Expected insertelement or insertvalue instruction!");
10051 
10052   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10053          "Expected empty result vectors!");
10054 
10055   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10056   if (!AggregateSize)
10057     return false;
10058   BuildVectorOpds.resize(*AggregateSize);
10059   InsertElts.resize(*AggregateSize);
10060 
10061   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10062   llvm::erase_value(BuildVectorOpds, nullptr);
10063   llvm::erase_value(InsertElts, nullptr);
10064   if (BuildVectorOpds.size() >= 2)
10065     return true;
10066 
10067   return false;
10068 }
10069 
10070 /// Try and get a reduction value from a phi node.
10071 ///
10072 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10073 /// if they come from either \p ParentBB or a containing loop latch.
10074 ///
10075 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10076 /// if not possible.
10077 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10078                                 BasicBlock *ParentBB, LoopInfo *LI) {
10079   // There are situations where the reduction value is not dominated by the
10080   // reduction phi. Vectorizing such cases has been reported to cause
10081   // miscompiles. See PR25787.
10082   auto DominatedReduxValue = [&](Value *R) {
10083     return isa<Instruction>(R) &&
10084            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10085   };
10086 
10087   Value *Rdx = nullptr;
10088 
10089   // Return the incoming value if it comes from the same BB as the phi node.
10090   if (P->getIncomingBlock(0) == ParentBB) {
10091     Rdx = P->getIncomingValue(0);
10092   } else if (P->getIncomingBlock(1) == ParentBB) {
10093     Rdx = P->getIncomingValue(1);
10094   }
10095 
10096   if (Rdx && DominatedReduxValue(Rdx))
10097     return Rdx;
10098 
10099   // Otherwise, check whether we have a loop latch to look at.
10100   Loop *BBL = LI->getLoopFor(ParentBB);
10101   if (!BBL)
10102     return nullptr;
10103   BasicBlock *BBLatch = BBL->getLoopLatch();
10104   if (!BBLatch)
10105     return nullptr;
10106 
10107   // There is a loop latch, return the incoming value if it comes from
10108   // that. This reduction pattern occasionally turns up.
10109   if (P->getIncomingBlock(0) == BBLatch) {
10110     Rdx = P->getIncomingValue(0);
10111   } else if (P->getIncomingBlock(1) == BBLatch) {
10112     Rdx = P->getIncomingValue(1);
10113   }
10114 
10115   if (Rdx && DominatedReduxValue(Rdx))
10116     return Rdx;
10117 
10118   return nullptr;
10119 }
10120 
10121 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10122   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10123     return true;
10124   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10125     return true;
10126   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10127     return true;
10128   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10129     return true;
10130   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10131     return true;
10132   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10133     return true;
10134   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10135     return true;
10136   return false;
10137 }
10138 
10139 /// Attempt to reduce a horizontal reduction.
10140 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10141 /// with reduction operators \a Root (or one of its operands) in a basic block
10142 /// \a BB, then check if it can be done. If horizontal reduction is not found
10143 /// and root instruction is a binary operation, vectorization of the operands is
10144 /// attempted.
10145 /// \returns true if a horizontal reduction was matched and reduced or operands
10146 /// of one of the binary instruction were vectorized.
10147 /// \returns false if a horizontal reduction was not matched (or not possible)
10148 /// or no vectorization of any binary operation feeding \a Root instruction was
10149 /// performed.
10150 static bool tryToVectorizeHorReductionOrInstOperands(
10151     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10152     TargetTransformInfo *TTI,
10153     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10154   if (!ShouldVectorizeHor)
10155     return false;
10156 
10157   if (!Root)
10158     return false;
10159 
10160   if (Root->getParent() != BB || isa<PHINode>(Root))
10161     return false;
10162   // Start analysis starting from Root instruction. If horizontal reduction is
10163   // found, try to vectorize it. If it is not a horizontal reduction or
10164   // vectorization is not possible or not effective, and currently analyzed
10165   // instruction is a binary operation, try to vectorize the operands, using
10166   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10167   // the same procedure considering each operand as a possible root of the
10168   // horizontal reduction.
10169   // Interrupt the process if the Root instruction itself was vectorized or all
10170   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10171   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10172   // CmpInsts so we can skip extra attempts in
10173   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10174   std::queue<std::pair<Instruction *, unsigned>> Stack;
10175   Stack.emplace(Root, 0);
10176   SmallPtrSet<Value *, 8> VisitedInstrs;
10177   SmallVector<WeakTrackingVH> PostponedInsts;
10178   bool Res = false;
10179   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
10180                                      Value *&B1) -> Value * {
10181     bool IsBinop = matchRdxBop(Inst, B0, B1);
10182     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10183     if (IsBinop || IsSelect) {
10184       HorizontalReduction HorRdx;
10185       if (HorRdx.matchAssociativeReduction(P, Inst))
10186         return HorRdx.tryToReduce(R, TTI);
10187     }
10188     return nullptr;
10189   };
10190   while (!Stack.empty()) {
10191     Instruction *Inst;
10192     unsigned Level;
10193     std::tie(Inst, Level) = Stack.front();
10194     Stack.pop();
10195     // Do not try to analyze instruction that has already been vectorized.
10196     // This may happen when we vectorize instruction operands on a previous
10197     // iteration while stack was populated before that happened.
10198     if (R.isDeleted(Inst))
10199       continue;
10200     Value *B0 = nullptr, *B1 = nullptr;
10201     if (Value *V = TryToReduce(Inst, B0, B1)) {
10202       Res = true;
10203       // Set P to nullptr to avoid re-analysis of phi node in
10204       // matchAssociativeReduction function unless this is the root node.
10205       P = nullptr;
10206       if (auto *I = dyn_cast<Instruction>(V)) {
10207         // Try to find another reduction.
10208         Stack.emplace(I, Level);
10209         continue;
10210       }
10211     } else {
10212       bool IsBinop = B0 && B1;
10213       if (P && IsBinop) {
10214         Inst = dyn_cast<Instruction>(B0);
10215         if (Inst == P)
10216           Inst = dyn_cast<Instruction>(B1);
10217         if (!Inst) {
10218           // Set P to nullptr to avoid re-analysis of phi node in
10219           // matchAssociativeReduction function unless this is the root node.
10220           P = nullptr;
10221           continue;
10222         }
10223       }
10224       // Set P to nullptr to avoid re-analysis of phi node in
10225       // matchAssociativeReduction function unless this is the root node.
10226       P = nullptr;
10227       // Do not try to vectorize CmpInst operands, this is done separately.
10228       // Final attempt for binop args vectorization should happen after the loop
10229       // to try to find reductions.
10230       if (!isa<CmpInst>(Inst))
10231         PostponedInsts.push_back(Inst);
10232     }
10233 
10234     // Try to vectorize operands.
10235     // Continue analysis for the instruction from the same basic block only to
10236     // save compile time.
10237     if (++Level < RecursionMaxDepth)
10238       for (auto *Op : Inst->operand_values())
10239         if (VisitedInstrs.insert(Op).second)
10240           if (auto *I = dyn_cast<Instruction>(Op))
10241             // Do not try to vectorize CmpInst operands,  this is done
10242             // separately.
10243             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10244                 I->getParent() == BB)
10245               Stack.emplace(I, Level);
10246   }
10247   // Try to vectorized binops where reductions were not found.
10248   for (Value *V : PostponedInsts)
10249     if (auto *Inst = dyn_cast<Instruction>(V))
10250       if (!R.isDeleted(Inst))
10251         Res |= Vectorize(Inst, R);
10252   return Res;
10253 }
10254 
10255 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10256                                                  BasicBlock *BB, BoUpSLP &R,
10257                                                  TargetTransformInfo *TTI) {
10258   auto *I = dyn_cast_or_null<Instruction>(V);
10259   if (!I)
10260     return false;
10261 
10262   if (!isa<BinaryOperator>(I))
10263     P = nullptr;
10264   // Try to match and vectorize a horizontal reduction.
10265   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10266     return tryToVectorize(I, R);
10267   };
10268   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10269                                                   ExtraVectorization);
10270 }
10271 
10272 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10273                                                  BasicBlock *BB, BoUpSLP &R) {
10274   const DataLayout &DL = BB->getModule()->getDataLayout();
10275   if (!R.canMapToVector(IVI->getType(), DL))
10276     return false;
10277 
10278   SmallVector<Value *, 16> BuildVectorOpds;
10279   SmallVector<Value *, 16> BuildVectorInsts;
10280   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10281     return false;
10282 
10283   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10284   // Aggregate value is unlikely to be processed in vector register.
10285   return tryToVectorizeList(BuildVectorOpds, R);
10286 }
10287 
10288 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10289                                                    BasicBlock *BB, BoUpSLP &R) {
10290   SmallVector<Value *, 16> BuildVectorInsts;
10291   SmallVector<Value *, 16> BuildVectorOpds;
10292   SmallVector<int> Mask;
10293   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10294       (llvm::all_of(
10295            BuildVectorOpds,
10296            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10297        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10298     return false;
10299 
10300   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10301   return tryToVectorizeList(BuildVectorInsts, R);
10302 }
10303 
10304 template <typename T>
10305 static bool
10306 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10307                        function_ref<unsigned(T *)> Limit,
10308                        function_ref<bool(T *, T *)> Comparator,
10309                        function_ref<bool(T *, T *)> AreCompatible,
10310                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10311                        bool LimitForRegisterSize) {
10312   bool Changed = false;
10313   // Sort by type, parent, operands.
10314   stable_sort(Incoming, Comparator);
10315 
10316   // Try to vectorize elements base on their type.
10317   SmallVector<T *> Candidates;
10318   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10319     // Look for the next elements with the same type, parent and operand
10320     // kinds.
10321     auto *SameTypeIt = IncIt;
10322     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10323       ++SameTypeIt;
10324 
10325     // Try to vectorize them.
10326     unsigned NumElts = (SameTypeIt - IncIt);
10327     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10328                       << NumElts << ")\n");
10329     // The vectorization is a 3-state attempt:
10330     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10331     // size of maximal register at first.
10332     // 2. Try to vectorize remaining instructions with the same type, if
10333     // possible. This may result in the better vectorization results rather than
10334     // if we try just to vectorize instructions with the same/alternate opcodes.
10335     // 3. Final attempt to try to vectorize all instructions with the
10336     // same/alternate ops only, this may result in some extra final
10337     // vectorization.
10338     if (NumElts > 1 &&
10339         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10340       // Success start over because instructions might have been changed.
10341       Changed = true;
10342     } else if (NumElts < Limit(*IncIt) &&
10343                (Candidates.empty() ||
10344                 Candidates.front()->getType() == (*IncIt)->getType())) {
10345       Candidates.append(IncIt, std::next(IncIt, NumElts));
10346     }
10347     // Final attempt to vectorize instructions with the same types.
10348     if (Candidates.size() > 1 &&
10349         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10350       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10351         // Success start over because instructions might have been changed.
10352         Changed = true;
10353       } else if (LimitForRegisterSize) {
10354         // Try to vectorize using small vectors.
10355         for (auto *It = Candidates.begin(), *End = Candidates.end();
10356              It != End;) {
10357           auto *SameTypeIt = It;
10358           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10359             ++SameTypeIt;
10360           unsigned NumElts = (SameTypeIt - It);
10361           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10362                                             /*LimitForRegisterSize=*/false))
10363             Changed = true;
10364           It = SameTypeIt;
10365         }
10366       }
10367       Candidates.clear();
10368     }
10369 
10370     // Start over at the next instruction of a different type (or the end).
10371     IncIt = SameTypeIt;
10372   }
10373   return Changed;
10374 }
10375 
10376 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10377 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10378 /// operands. If IsCompatibility is false, function implements strict weak
10379 /// ordering relation between two cmp instructions, returning true if the first
10380 /// instruction is "less" than the second, i.e. its predicate is less than the
10381 /// predicate of the second or the operands IDs are less than the operands IDs
10382 /// of the second cmp instruction.
10383 template <bool IsCompatibility>
10384 static bool compareCmp(Value *V, Value *V2,
10385                        function_ref<bool(Instruction *)> IsDeleted) {
10386   auto *CI1 = cast<CmpInst>(V);
10387   auto *CI2 = cast<CmpInst>(V2);
10388   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10389     return false;
10390   if (CI1->getOperand(0)->getType()->getTypeID() <
10391       CI2->getOperand(0)->getType()->getTypeID())
10392     return !IsCompatibility;
10393   if (CI1->getOperand(0)->getType()->getTypeID() >
10394       CI2->getOperand(0)->getType()->getTypeID())
10395     return false;
10396   CmpInst::Predicate Pred1 = CI1->getPredicate();
10397   CmpInst::Predicate Pred2 = CI2->getPredicate();
10398   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10399   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10400   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10401   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10402   if (BasePred1 < BasePred2)
10403     return !IsCompatibility;
10404   if (BasePred1 > BasePred2)
10405     return false;
10406   // Compare operands.
10407   bool LEPreds = Pred1 <= Pred2;
10408   bool GEPreds = Pred1 >= Pred2;
10409   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10410     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10411     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10412     if (Op1->getValueID() < Op2->getValueID())
10413       return !IsCompatibility;
10414     if (Op1->getValueID() > Op2->getValueID())
10415       return false;
10416     if (auto *I1 = dyn_cast<Instruction>(Op1))
10417       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10418         if (I1->getParent() != I2->getParent())
10419           return false;
10420         InstructionsState S = getSameOpcode({I1, I2});
10421         if (S.getOpcode())
10422           continue;
10423         return false;
10424       }
10425   }
10426   return IsCompatibility;
10427 }
10428 
10429 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10430     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10431     bool AtTerminator) {
10432   bool OpsChanged = false;
10433   SmallVector<Instruction *, 4> PostponedCmps;
10434   for (auto *I : reverse(Instructions)) {
10435     if (R.isDeleted(I))
10436       continue;
10437     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10438       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10439     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10440       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10441     else if (isa<CmpInst>(I))
10442       PostponedCmps.push_back(I);
10443   }
10444   if (AtTerminator) {
10445     // Try to find reductions first.
10446     for (Instruction *I : PostponedCmps) {
10447       if (R.isDeleted(I))
10448         continue;
10449       for (Value *Op : I->operands())
10450         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10451     }
10452     // Try to vectorize operands as vector bundles.
10453     for (Instruction *I : PostponedCmps) {
10454       if (R.isDeleted(I))
10455         continue;
10456       OpsChanged |= tryToVectorize(I, R);
10457     }
10458     // Try to vectorize list of compares.
10459     // Sort by type, compare predicate, etc.
10460     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10461       return compareCmp<false>(V, V2,
10462                                [&R](Instruction *I) { return R.isDeleted(I); });
10463     };
10464 
10465     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10466       if (V1 == V2)
10467         return true;
10468       return compareCmp<true>(V1, V2,
10469                               [&R](Instruction *I) { return R.isDeleted(I); });
10470     };
10471     auto Limit = [&R](Value *V) {
10472       unsigned EltSize = R.getVectorElementSize(V);
10473       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10474     };
10475 
10476     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10477     OpsChanged |= tryToVectorizeSequence<Value>(
10478         Vals, Limit, CompareSorter, AreCompatibleCompares,
10479         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10480           // Exclude possible reductions from other blocks.
10481           bool ArePossiblyReducedInOtherBlock =
10482               any_of(Candidates, [](Value *V) {
10483                 return any_of(V->users(), [V](User *U) {
10484                   return isa<SelectInst>(U) &&
10485                          cast<SelectInst>(U)->getParent() !=
10486                              cast<Instruction>(V)->getParent();
10487                 });
10488               });
10489           if (ArePossiblyReducedInOtherBlock)
10490             return false;
10491           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10492         },
10493         /*LimitForRegisterSize=*/true);
10494     Instructions.clear();
10495   } else {
10496     // Insert in reverse order since the PostponedCmps vector was filled in
10497     // reverse order.
10498     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10499   }
10500   return OpsChanged;
10501 }
10502 
10503 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10504   bool Changed = false;
10505   SmallVector<Value *, 4> Incoming;
10506   SmallPtrSet<Value *, 16> VisitedInstrs;
10507   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10508   // node. Allows better to identify the chains that can be vectorized in the
10509   // better way.
10510   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10511   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10512     assert(isValidElementType(V1->getType()) &&
10513            isValidElementType(V2->getType()) &&
10514            "Expected vectorizable types only.");
10515     // It is fine to compare type IDs here, since we expect only vectorizable
10516     // types, like ints, floats and pointers, we don't care about other type.
10517     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10518       return true;
10519     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10520       return false;
10521     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10522     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10523     if (Opcodes1.size() < Opcodes2.size())
10524       return true;
10525     if (Opcodes1.size() > Opcodes2.size())
10526       return false;
10527     Optional<bool> ConstOrder;
10528     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10529       // Undefs are compatible with any other value.
10530       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10531         if (!ConstOrder)
10532           ConstOrder =
10533               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10534         continue;
10535       }
10536       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10537         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10538           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10539           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10540           if (!NodeI1)
10541             return NodeI2 != nullptr;
10542           if (!NodeI2)
10543             return false;
10544           assert((NodeI1 == NodeI2) ==
10545                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10546                  "Different nodes should have different DFS numbers");
10547           if (NodeI1 != NodeI2)
10548             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10549           InstructionsState S = getSameOpcode({I1, I2});
10550           if (S.getOpcode())
10551             continue;
10552           return I1->getOpcode() < I2->getOpcode();
10553         }
10554       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10555         if (!ConstOrder)
10556           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10557         continue;
10558       }
10559       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10560         return true;
10561       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10562         return false;
10563     }
10564     return ConstOrder && *ConstOrder;
10565   };
10566   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10567     if (V1 == V2)
10568       return true;
10569     if (V1->getType() != V2->getType())
10570       return false;
10571     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10572     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10573     if (Opcodes1.size() != Opcodes2.size())
10574       return false;
10575     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10576       // Undefs are compatible with any other value.
10577       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10578         continue;
10579       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10580         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10581           if (I1->getParent() != I2->getParent())
10582             return false;
10583           InstructionsState S = getSameOpcode({I1, I2});
10584           if (S.getOpcode())
10585             continue;
10586           return false;
10587         }
10588       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10589         continue;
10590       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10591         return false;
10592     }
10593     return true;
10594   };
10595   auto Limit = [&R](Value *V) {
10596     unsigned EltSize = R.getVectorElementSize(V);
10597     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10598   };
10599 
10600   bool HaveVectorizedPhiNodes = false;
10601   do {
10602     // Collect the incoming values from the PHIs.
10603     Incoming.clear();
10604     for (Instruction &I : *BB) {
10605       PHINode *P = dyn_cast<PHINode>(&I);
10606       if (!P)
10607         break;
10608 
10609       // No need to analyze deleted, vectorized and non-vectorizable
10610       // instructions.
10611       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10612           isValidElementType(P->getType()))
10613         Incoming.push_back(P);
10614     }
10615 
10616     // Find the corresponding non-phi nodes for better matching when trying to
10617     // build the tree.
10618     for (Value *V : Incoming) {
10619       SmallVectorImpl<Value *> &Opcodes =
10620           PHIToOpcodes.try_emplace(V).first->getSecond();
10621       if (!Opcodes.empty())
10622         continue;
10623       SmallVector<Value *, 4> Nodes(1, V);
10624       SmallPtrSet<Value *, 4> Visited;
10625       while (!Nodes.empty()) {
10626         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10627         if (!Visited.insert(PHI).second)
10628           continue;
10629         for (Value *V : PHI->incoming_values()) {
10630           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10631             Nodes.push_back(PHI1);
10632             continue;
10633           }
10634           Opcodes.emplace_back(V);
10635         }
10636       }
10637     }
10638 
10639     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10640         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10641         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10642           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10643         },
10644         /*LimitForRegisterSize=*/true);
10645     Changed |= HaveVectorizedPhiNodes;
10646     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10647   } while (HaveVectorizedPhiNodes);
10648 
10649   VisitedInstrs.clear();
10650 
10651   SmallVector<Instruction *, 8> PostProcessInstructions;
10652   SmallDenseSet<Instruction *, 4> KeyNodes;
10653   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10654     // Skip instructions with scalable type. The num of elements is unknown at
10655     // compile-time for scalable type.
10656     if (isa<ScalableVectorType>(it->getType()))
10657       continue;
10658 
10659     // Skip instructions marked for the deletion.
10660     if (R.isDeleted(&*it))
10661       continue;
10662     // We may go through BB multiple times so skip the one we have checked.
10663     if (!VisitedInstrs.insert(&*it).second) {
10664       if (it->use_empty() && KeyNodes.contains(&*it) &&
10665           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10666                                       it->isTerminator())) {
10667         // We would like to start over since some instructions are deleted
10668         // and the iterator may become invalid value.
10669         Changed = true;
10670         it = BB->begin();
10671         e = BB->end();
10672       }
10673       continue;
10674     }
10675 
10676     if (isa<DbgInfoIntrinsic>(it))
10677       continue;
10678 
10679     // Try to vectorize reductions that use PHINodes.
10680     if (PHINode *P = dyn_cast<PHINode>(it)) {
10681       // Check that the PHI is a reduction PHI.
10682       if (P->getNumIncomingValues() == 2) {
10683         // Try to match and vectorize a horizontal reduction.
10684         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10685                                      TTI)) {
10686           Changed = true;
10687           it = BB->begin();
10688           e = BB->end();
10689           continue;
10690         }
10691       }
10692       // Try to vectorize the incoming values of the PHI, to catch reductions
10693       // that feed into PHIs.
10694       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10695         // Skip if the incoming block is the current BB for now. Also, bypass
10696         // unreachable IR for efficiency and to avoid crashing.
10697         // TODO: Collect the skipped incoming values and try to vectorize them
10698         // after processing BB.
10699         if (BB == P->getIncomingBlock(I) ||
10700             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10701           continue;
10702 
10703         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10704                                             P->getIncomingBlock(I), R, TTI);
10705       }
10706       continue;
10707     }
10708 
10709     // Ran into an instruction without users, like terminator, or function call
10710     // with ignored return value, store. Ignore unused instructions (basing on
10711     // instruction type, except for CallInst and InvokeInst).
10712     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10713                             isa<InvokeInst>(it))) {
10714       KeyNodes.insert(&*it);
10715       bool OpsChanged = false;
10716       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10717         for (auto *V : it->operand_values()) {
10718           // Try to match and vectorize a horizontal reduction.
10719           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10720         }
10721       }
10722       // Start vectorization of post-process list of instructions from the
10723       // top-tree instructions to try to vectorize as many instructions as
10724       // possible.
10725       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10726                                                 it->isTerminator());
10727       if (OpsChanged) {
10728         // We would like to start over since some instructions are deleted
10729         // and the iterator may become invalid value.
10730         Changed = true;
10731         it = BB->begin();
10732         e = BB->end();
10733         continue;
10734       }
10735     }
10736 
10737     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10738         isa<InsertValueInst>(it))
10739       PostProcessInstructions.push_back(&*it);
10740   }
10741 
10742   return Changed;
10743 }
10744 
10745 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10746   auto Changed = false;
10747   for (auto &Entry : GEPs) {
10748     // If the getelementptr list has fewer than two elements, there's nothing
10749     // to do.
10750     if (Entry.second.size() < 2)
10751       continue;
10752 
10753     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10754                       << Entry.second.size() << ".\n");
10755 
10756     // Process the GEP list in chunks suitable for the target's supported
10757     // vector size. If a vector register can't hold 1 element, we are done. We
10758     // are trying to vectorize the index computations, so the maximum number of
10759     // elements is based on the size of the index expression, rather than the
10760     // size of the GEP itself (the target's pointer size).
10761     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10762     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10763     if (MaxVecRegSize < EltSize)
10764       continue;
10765 
10766     unsigned MaxElts = MaxVecRegSize / EltSize;
10767     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10768       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10769       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10770 
10771       // Initialize a set a candidate getelementptrs. Note that we use a
10772       // SetVector here to preserve program order. If the index computations
10773       // are vectorizable and begin with loads, we want to minimize the chance
10774       // of having to reorder them later.
10775       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10776 
10777       // Some of the candidates may have already been vectorized after we
10778       // initially collected them. If so, they are marked as deleted, so remove
10779       // them from the set of candidates.
10780       Candidates.remove_if(
10781           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10782 
10783       // Remove from the set of candidates all pairs of getelementptrs with
10784       // constant differences. Such getelementptrs are likely not good
10785       // candidates for vectorization in a bottom-up phase since one can be
10786       // computed from the other. We also ensure all candidate getelementptr
10787       // indices are unique.
10788       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10789         auto *GEPI = GEPList[I];
10790         if (!Candidates.count(GEPI))
10791           continue;
10792         auto *SCEVI = SE->getSCEV(GEPList[I]);
10793         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10794           auto *GEPJ = GEPList[J];
10795           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10796           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10797             Candidates.remove(GEPI);
10798             Candidates.remove(GEPJ);
10799           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10800             Candidates.remove(GEPJ);
10801           }
10802         }
10803       }
10804 
10805       // We break out of the above computation as soon as we know there are
10806       // fewer than two candidates remaining.
10807       if (Candidates.size() < 2)
10808         continue;
10809 
10810       // Add the single, non-constant index of each candidate to the bundle. We
10811       // ensured the indices met these constraints when we originally collected
10812       // the getelementptrs.
10813       SmallVector<Value *, 16> Bundle(Candidates.size());
10814       auto BundleIndex = 0u;
10815       for (auto *V : Candidates) {
10816         auto *GEP = cast<GetElementPtrInst>(V);
10817         auto *GEPIdx = GEP->idx_begin()->get();
10818         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10819         Bundle[BundleIndex++] = GEPIdx;
10820       }
10821 
10822       // Try and vectorize the indices. We are currently only interested in
10823       // gather-like cases of the form:
10824       //
10825       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10826       //
10827       // where the loads of "a", the loads of "b", and the subtractions can be
10828       // performed in parallel. It's likely that detecting this pattern in a
10829       // bottom-up phase will be simpler and less costly than building a
10830       // full-blown top-down phase beginning at the consecutive loads.
10831       Changed |= tryToVectorizeList(Bundle, R);
10832     }
10833   }
10834   return Changed;
10835 }
10836 
10837 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10838   bool Changed = false;
10839   // Sort by type, base pointers and values operand. Value operands must be
10840   // compatible (have the same opcode, same parent), otherwise it is
10841   // definitely not profitable to try to vectorize them.
10842   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10843     if (V->getPointerOperandType()->getTypeID() <
10844         V2->getPointerOperandType()->getTypeID())
10845       return true;
10846     if (V->getPointerOperandType()->getTypeID() >
10847         V2->getPointerOperandType()->getTypeID())
10848       return false;
10849     // UndefValues are compatible with all other values.
10850     if (isa<UndefValue>(V->getValueOperand()) ||
10851         isa<UndefValue>(V2->getValueOperand()))
10852       return false;
10853     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10854       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10855         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10856             DT->getNode(I1->getParent());
10857         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10858             DT->getNode(I2->getParent());
10859         assert(NodeI1 && "Should only process reachable instructions");
10860         assert(NodeI1 && "Should only process reachable instructions");
10861         assert((NodeI1 == NodeI2) ==
10862                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10863                "Different nodes should have different DFS numbers");
10864         if (NodeI1 != NodeI2)
10865           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10866         InstructionsState S = getSameOpcode({I1, I2});
10867         if (S.getOpcode())
10868           return false;
10869         return I1->getOpcode() < I2->getOpcode();
10870       }
10871     if (isa<Constant>(V->getValueOperand()) &&
10872         isa<Constant>(V2->getValueOperand()))
10873       return false;
10874     return V->getValueOperand()->getValueID() <
10875            V2->getValueOperand()->getValueID();
10876   };
10877 
10878   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10879     if (V1 == V2)
10880       return true;
10881     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10882       return false;
10883     // Undefs are compatible with any other value.
10884     if (isa<UndefValue>(V1->getValueOperand()) ||
10885         isa<UndefValue>(V2->getValueOperand()))
10886       return true;
10887     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10888       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10889         if (I1->getParent() != I2->getParent())
10890           return false;
10891         InstructionsState S = getSameOpcode({I1, I2});
10892         return S.getOpcode() > 0;
10893       }
10894     if (isa<Constant>(V1->getValueOperand()) &&
10895         isa<Constant>(V2->getValueOperand()))
10896       return true;
10897     return V1->getValueOperand()->getValueID() ==
10898            V2->getValueOperand()->getValueID();
10899   };
10900   auto Limit = [&R, this](StoreInst *SI) {
10901     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10902     return R.getMinVF(EltSize);
10903   };
10904 
10905   // Attempt to sort and vectorize each of the store-groups.
10906   for (auto &Pair : Stores) {
10907     if (Pair.second.size() < 2)
10908       continue;
10909 
10910     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10911                       << Pair.second.size() << ".\n");
10912 
10913     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10914       continue;
10915 
10916     Changed |= tryToVectorizeSequence<StoreInst>(
10917         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10918         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10919           return vectorizeStores(Candidates, R);
10920         },
10921         /*LimitForRegisterSize=*/false);
10922   }
10923   return Changed;
10924 }
10925 
10926 char SLPVectorizer::ID = 0;
10927 
10928 static const char lv_name[] = "SLP Vectorizer";
10929 
10930 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10931 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10932 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10933 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10934 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10935 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10936 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10937 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10938 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10939 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10940 
10941 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10942