1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/Operator.h"
68 #include "llvm/IR/PatternMatch.h"
69 #include "llvm/IR/Type.h"
70 #include "llvm/IR/Use.h"
71 #include "llvm/IR/User.h"
72 #include "llvm/IR/Value.h"
73 #include "llvm/IR/ValueHandle.h"
74 #ifdef EXPENSIVE_CHECKS
75 #include "llvm/IR/Verifier.h"
76 #endif
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 // Limit the number of alias checks. The limit is chosen so that
172 // it has no negative effect on the llvm benchmarks.
173 static const unsigned AliasedCheckLimit = 10;
174 
175 // Another limit for the alias checks: The maximum distance between load/store
176 // instructions where alias checks are done.
177 // This limit is useful for very large basic blocks.
178 static const unsigned MaxMemDepDistance = 160;
179 
180 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
181 /// regions to be handled.
182 static const int MinScheduleRegionSize = 16;
183 
184 /// Predicate for the element types that the SLP vectorizer supports.
185 ///
186 /// The most important thing to filter here are types which are invalid in LLVM
187 /// vectors. We also filter target specific types which have absolutely no
188 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
189 /// avoids spending time checking the cost model and realizing that they will
190 /// be inevitably scalarized.
191 static bool isValidElementType(Type *Ty) {
192   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
193          !Ty->isPPC_FP128Ty();
194 }
195 
196 /// \returns True if the value is a constant (but not globals/constant
197 /// expressions).
198 static bool isConstant(Value *V) {
199   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
200 }
201 
202 /// Checks if \p V is one of vector-like instructions, i.e. undef,
203 /// insertelement/extractelement with constant indices for fixed vector type or
204 /// extractvalue instruction.
205 static bool isVectorLikeInstWithConstOps(Value *V) {
206   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
207       !isa<ExtractValueInst, UndefValue>(V))
208     return false;
209   auto *I = dyn_cast<Instruction>(V);
210   if (!I || isa<ExtractValueInst>(I))
211     return true;
212   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
213     return false;
214   if (isa<ExtractElementInst>(I))
215     return isConstant(I->getOperand(1));
216   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
217   return isConstant(I->getOperand(2));
218 }
219 
220 /// \returns true if all of the instructions in \p VL are in the same block or
221 /// false otherwise.
222 static bool allSameBlock(ArrayRef<Value *> VL) {
223   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
224   if (!I0)
225     return false;
226   if (all_of(VL, isVectorLikeInstWithConstOps))
227     return true;
228 
229   BasicBlock *BB = I0->getParent();
230   for (int I = 1, E = VL.size(); I < E; I++) {
231     auto *II = dyn_cast<Instruction>(VL[I]);
232     if (!II)
233       return false;
234 
235     if (BB != II->getParent())
236       return false;
237   }
238   return true;
239 }
240 
241 /// \returns True if all of the values in \p VL are constants (but not
242 /// globals/constant expressions).
243 static bool allConstant(ArrayRef<Value *> VL) {
244   // Constant expressions and globals can't be vectorized like normal integer/FP
245   // constants.
246   return all_of(VL, isConstant);
247 }
248 
249 /// \returns True if all of the values in \p VL are identical or some of them
250 /// are UndefValue.
251 static bool isSplat(ArrayRef<Value *> VL) {
252   Value *FirstNonUndef = nullptr;
253   for (Value *V : VL) {
254     if (isa<UndefValue>(V))
255       continue;
256     if (!FirstNonUndef) {
257       FirstNonUndef = V;
258       continue;
259     }
260     if (V != FirstNonUndef)
261       return false;
262   }
263   return FirstNonUndef != nullptr;
264 }
265 
266 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
267 static bool isCommutative(Instruction *I) {
268   if (auto *Cmp = dyn_cast<CmpInst>(I))
269     return Cmp->isCommutative();
270   if (auto *BO = dyn_cast<BinaryOperator>(I))
271     return BO->isCommutative();
272   // TODO: This should check for generic Instruction::isCommutative(), but
273   //       we need to confirm that the caller code correctly handles Intrinsics
274   //       for example (does not have 2 operands).
275   return false;
276 }
277 
278 /// Checks if the given value is actually an undefined constant vector.
279 static bool isUndefVector(const Value *V) {
280   if (isa<UndefValue>(V))
281     return true;
282   auto *C = dyn_cast<Constant>(V);
283   if (!C)
284     return false;
285   if (!C->containsUndefOrPoisonElement())
286     return false;
287   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
288   if (!VecTy)
289     return false;
290   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
291     if (Constant *Elem = C->getAggregateElement(I))
292       if (!isa<UndefValue>(Elem))
293         return false;
294   }
295   return true;
296 }
297 
298 /// Checks if the vector of instructions can be represented as a shuffle, like:
299 /// %x0 = extractelement <4 x i8> %x, i32 0
300 /// %x3 = extractelement <4 x i8> %x, i32 3
301 /// %y1 = extractelement <4 x i8> %y, i32 1
302 /// %y2 = extractelement <4 x i8> %y, i32 2
303 /// %x0x0 = mul i8 %x0, %x0
304 /// %x3x3 = mul i8 %x3, %x3
305 /// %y1y1 = mul i8 %y1, %y1
306 /// %y2y2 = mul i8 %y2, %y2
307 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
308 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
309 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
310 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
311 /// ret <4 x i8> %ins4
312 /// can be transformed into:
313 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
314 ///                                                         i32 6>
315 /// %2 = mul <4 x i8> %1, %1
316 /// ret <4 x i8> %2
317 /// We convert this initially to something like:
318 /// %x0 = extractelement <4 x i8> %x, i32 0
319 /// %x3 = extractelement <4 x i8> %x, i32 3
320 /// %y1 = extractelement <4 x i8> %y, i32 1
321 /// %y2 = extractelement <4 x i8> %y, i32 2
322 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
323 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
324 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
325 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
326 /// %5 = mul <4 x i8> %4, %4
327 /// %6 = extractelement <4 x i8> %5, i32 0
328 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
329 /// %7 = extractelement <4 x i8> %5, i32 1
330 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
331 /// %8 = extractelement <4 x i8> %5, i32 2
332 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
333 /// %9 = extractelement <4 x i8> %5, i32 3
334 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
335 /// ret <4 x i8> %ins4
336 /// InstCombiner transforms this into a shuffle and vector mul
337 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
338 /// TODO: Can we split off and reuse the shuffle mask detection from
339 /// TargetTransformInfo::getInstructionThroughput?
340 static Optional<TargetTransformInfo::ShuffleKind>
341 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
342   const auto *It =
343       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
344   if (It == VL.end())
345     return None;
346   auto *EI0 = cast<ExtractElementInst>(*It);
347   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
348     return None;
349   unsigned Size =
350       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
351   Value *Vec1 = nullptr;
352   Value *Vec2 = nullptr;
353   enum ShuffleMode { Unknown, Select, Permute };
354   ShuffleMode CommonShuffleMode = Unknown;
355   Mask.assign(VL.size(), UndefMaskElem);
356   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
357     // Undef can be represented as an undef element in a vector.
358     if (isa<UndefValue>(VL[I]))
359       continue;
360     auto *EI = cast<ExtractElementInst>(VL[I]);
361     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
362       return None;
363     auto *Vec = EI->getVectorOperand();
364     // We can extractelement from undef or poison vector.
365     if (isUndefVector(Vec))
366       continue;
367     // All vector operands must have the same number of vector elements.
368     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
369       return None;
370     if (isa<UndefValue>(EI->getIndexOperand()))
371       continue;
372     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
373     if (!Idx)
374       return None;
375     // Undefined behavior if Idx is negative or >= Size.
376     if (Idx->getValue().uge(Size))
377       continue;
378     unsigned IntIdx = Idx->getValue().getZExtValue();
379     Mask[I] = IntIdx;
380     // For correct shuffling we have to have at most 2 different vector operands
381     // in all extractelement instructions.
382     if (!Vec1 || Vec1 == Vec) {
383       Vec1 = Vec;
384     } else if (!Vec2 || Vec2 == Vec) {
385       Vec2 = Vec;
386       Mask[I] += Size;
387     } else {
388       return None;
389     }
390     if (CommonShuffleMode == Permute)
391       continue;
392     // If the extract index is not the same as the operation number, it is a
393     // permutation.
394     if (IntIdx != I) {
395       CommonShuffleMode = Permute;
396       continue;
397     }
398     CommonShuffleMode = Select;
399   }
400   // If we're not crossing lanes in different vectors, consider it as blending.
401   if (CommonShuffleMode == Select && Vec2)
402     return TargetTransformInfo::SK_Select;
403   // If Vec2 was never used, we have a permutation of a single vector, otherwise
404   // we have permutation of 2 vectors.
405   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
406               : TargetTransformInfo::SK_PermuteSingleSrc;
407 }
408 
409 namespace {
410 
411 /// Main data required for vectorization of instructions.
412 struct InstructionsState {
413   /// The very first instruction in the list with the main opcode.
414   Value *OpValue = nullptr;
415 
416   /// The main/alternate instruction.
417   Instruction *MainOp = nullptr;
418   Instruction *AltOp = nullptr;
419 
420   /// The main/alternate opcodes for the list of instructions.
421   unsigned getOpcode() const {
422     return MainOp ? MainOp->getOpcode() : 0;
423   }
424 
425   unsigned getAltOpcode() const {
426     return AltOp ? AltOp->getOpcode() : 0;
427   }
428 
429   /// Some of the instructions in the list have alternate opcodes.
430   bool isAltShuffle() const { return AltOp != MainOp; }
431 
432   bool isOpcodeOrAlt(Instruction *I) const {
433     unsigned CheckedOpcode = I->getOpcode();
434     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
435   }
436 
437   InstructionsState() = delete;
438   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
439       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
440 };
441 
442 } // end anonymous namespace
443 
444 /// Chooses the correct key for scheduling data. If \p Op has the same (or
445 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
446 /// OpValue.
447 static Value *isOneOf(const InstructionsState &S, Value *Op) {
448   auto *I = dyn_cast<Instruction>(Op);
449   if (I && S.isOpcodeOrAlt(I))
450     return Op;
451   return S.OpValue;
452 }
453 
454 /// \returns true if \p Opcode is allowed as part of of the main/alternate
455 /// instruction for SLP vectorization.
456 ///
457 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
458 /// "shuffled out" lane would result in division by zero.
459 static bool isValidForAlternation(unsigned Opcode) {
460   if (Instruction::isIntDivRem(Opcode))
461     return false;
462 
463   return true;
464 }
465 
466 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
467                                        unsigned BaseIndex = 0);
468 
469 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
470 /// compatible instructions or constants, or just some other regular values.
471 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
472                                 Value *Op1) {
473   return (isConstant(BaseOp0) && isConstant(Op0)) ||
474          (isConstant(BaseOp1) && isConstant(Op1)) ||
475          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
476           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
477          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
478          getSameOpcode({BaseOp1, Op1}).getOpcode();
479 }
480 
481 /// \returns analysis of the Instructions in \p VL described in
482 /// InstructionsState, the Opcode that we suppose the whole list
483 /// could be vectorized even if its structure is diverse.
484 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
485                                        unsigned BaseIndex) {
486   // Make sure these are all Instructions.
487   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
488     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
489 
490   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
491   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
492   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
493   CmpInst::Predicate BasePred =
494       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
495               : CmpInst::BAD_ICMP_PREDICATE;
496   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
497   unsigned AltOpcode = Opcode;
498   unsigned AltIndex = BaseIndex;
499 
500   // Check for one alternate opcode from another BinaryOperator.
501   // TODO - generalize to support all operators (types, calls etc.).
502   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
503     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
504     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
505       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
506         continue;
507       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
508           isValidForAlternation(Opcode)) {
509         AltOpcode = InstOpcode;
510         AltIndex = Cnt;
511         continue;
512       }
513     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
514       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
515       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
516       if (Ty0 == Ty1) {
517         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
518           continue;
519         if (Opcode == AltOpcode) {
520           assert(isValidForAlternation(Opcode) &&
521                  isValidForAlternation(InstOpcode) &&
522                  "Cast isn't safe for alternation, logic needs to be updated!");
523           AltOpcode = InstOpcode;
524           AltIndex = Cnt;
525           continue;
526         }
527       }
528     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
529       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
530       auto *Inst = cast<Instruction>(VL[Cnt]);
531       Type *Ty0 = BaseInst->getOperand(0)->getType();
532       Type *Ty1 = Inst->getOperand(0)->getType();
533       if (Ty0 == Ty1) {
534         Value *BaseOp0 = BaseInst->getOperand(0);
535         Value *BaseOp1 = BaseInst->getOperand(1);
536         Value *Op0 = Inst->getOperand(0);
537         Value *Op1 = Inst->getOperand(1);
538         CmpInst::Predicate CurrentPred =
539             cast<CmpInst>(VL[Cnt])->getPredicate();
540         CmpInst::Predicate SwappedCurrentPred =
541             CmpInst::getSwappedPredicate(CurrentPred);
542         // Check for compatible operands. If the corresponding operands are not
543         // compatible - need to perform alternate vectorization.
544         if (InstOpcode == Opcode) {
545           if (BasePred == CurrentPred &&
546               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
547             continue;
548           if (BasePred == SwappedCurrentPred &&
549               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
550             continue;
551           if (E == 2 &&
552               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
553             continue;
554           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
555           CmpInst::Predicate AltPred = AltInst->getPredicate();
556           Value *AltOp0 = AltInst->getOperand(0);
557           Value *AltOp1 = AltInst->getOperand(1);
558           // Check if operands are compatible with alternate operands.
559           if (AltPred == CurrentPred &&
560               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
561             continue;
562           if (AltPred == SwappedCurrentPred &&
563               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
564             continue;
565         }
566         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
567           assert(isValidForAlternation(Opcode) &&
568                  isValidForAlternation(InstOpcode) &&
569                  "Cast isn't safe for alternation, logic needs to be updated!");
570           AltIndex = Cnt;
571           continue;
572         }
573         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
574         CmpInst::Predicate AltPred = AltInst->getPredicate();
575         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
576             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
577           continue;
578       }
579     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
580       continue;
581     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
582   }
583 
584   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
585                            cast<Instruction>(VL[AltIndex]));
586 }
587 
588 /// \returns true if all of the values in \p VL have the same type or false
589 /// otherwise.
590 static bool allSameType(ArrayRef<Value *> VL) {
591   Type *Ty = VL[0]->getType();
592   for (int i = 1, e = VL.size(); i < e; i++)
593     if (VL[i]->getType() != Ty)
594       return false;
595 
596   return true;
597 }
598 
599 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
600 static Optional<unsigned> getExtractIndex(Instruction *E) {
601   unsigned Opcode = E->getOpcode();
602   assert((Opcode == Instruction::ExtractElement ||
603           Opcode == Instruction::ExtractValue) &&
604          "Expected extractelement or extractvalue instruction.");
605   if (Opcode == Instruction::ExtractElement) {
606     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
607     if (!CI)
608       return None;
609     return CI->getZExtValue();
610   }
611   ExtractValueInst *EI = cast<ExtractValueInst>(E);
612   if (EI->getNumIndices() != 1)
613     return None;
614   return *EI->idx_begin();
615 }
616 
617 /// \returns True if in-tree use also needs extract. This refers to
618 /// possible scalar operand in vectorized instruction.
619 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
620                                     TargetLibraryInfo *TLI) {
621   unsigned Opcode = UserInst->getOpcode();
622   switch (Opcode) {
623   case Instruction::Load: {
624     LoadInst *LI = cast<LoadInst>(UserInst);
625     return (LI->getPointerOperand() == Scalar);
626   }
627   case Instruction::Store: {
628     StoreInst *SI = cast<StoreInst>(UserInst);
629     return (SI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Call: {
632     CallInst *CI = cast<CallInst>(UserInst);
633     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
634     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
635       if (hasVectorInstrinsicScalarOpd(ID, i))
636         return (CI->getArgOperand(i) == Scalar);
637     }
638     LLVM_FALLTHROUGH;
639   }
640   default:
641     return false;
642   }
643 }
644 
645 /// \returns the AA location that is being access by the instruction.
646 static MemoryLocation getLocation(Instruction *I) {
647   if (StoreInst *SI = dyn_cast<StoreInst>(I))
648     return MemoryLocation::get(SI);
649   if (LoadInst *LI = dyn_cast<LoadInst>(I))
650     return MemoryLocation::get(LI);
651   return MemoryLocation();
652 }
653 
654 /// \returns True if the instruction is not a volatile or atomic load/store.
655 static bool isSimple(Instruction *I) {
656   if (LoadInst *LI = dyn_cast<LoadInst>(I))
657     return LI->isSimple();
658   if (StoreInst *SI = dyn_cast<StoreInst>(I))
659     return SI->isSimple();
660   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
661     return !MI->isVolatile();
662   return true;
663 }
664 
665 /// Shuffles \p Mask in accordance with the given \p SubMask.
666 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
667   if (SubMask.empty())
668     return;
669   if (Mask.empty()) {
670     Mask.append(SubMask.begin(), SubMask.end());
671     return;
672   }
673   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
674   int TermValue = std::min(Mask.size(), SubMask.size());
675   for (int I = 0, E = SubMask.size(); I < E; ++I) {
676     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
677         Mask[SubMask[I]] >= TermValue)
678       continue;
679     NewMask[I] = Mask[SubMask[I]];
680   }
681   Mask.swap(NewMask);
682 }
683 
684 /// Order may have elements assigned special value (size) which is out of
685 /// bounds. Such indices only appear on places which correspond to undef values
686 /// (see canReuseExtract for details) and used in order to avoid undef values
687 /// have effect on operands ordering.
688 /// The first loop below simply finds all unused indices and then the next loop
689 /// nest assigns these indices for undef values positions.
690 /// As an example below Order has two undef positions and they have assigned
691 /// values 3 and 7 respectively:
692 /// before:  6 9 5 4 9 2 1 0
693 /// after:   6 3 5 4 7 2 1 0
694 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
695   const unsigned Sz = Order.size();
696   SmallBitVector UnusedIndices(Sz, /*t=*/true);
697   SmallBitVector MaskedIndices(Sz);
698   for (unsigned I = 0; I < Sz; ++I) {
699     if (Order[I] < Sz)
700       UnusedIndices.reset(Order[I]);
701     else
702       MaskedIndices.set(I);
703   }
704   if (MaskedIndices.none())
705     return;
706   assert(UnusedIndices.count() == MaskedIndices.count() &&
707          "Non-synced masked/available indices.");
708   int Idx = UnusedIndices.find_first();
709   int MIdx = MaskedIndices.find_first();
710   while (MIdx >= 0) {
711     assert(Idx >= 0 && "Indices must be synced.");
712     Order[MIdx] = Idx;
713     Idx = UnusedIndices.find_next(Idx);
714     MIdx = MaskedIndices.find_next(MIdx);
715   }
716 }
717 
718 namespace llvm {
719 
720 static void inversePermutation(ArrayRef<unsigned> Indices,
721                                SmallVectorImpl<int> &Mask) {
722   Mask.clear();
723   const unsigned E = Indices.size();
724   Mask.resize(E, UndefMaskElem);
725   for (unsigned I = 0; I < E; ++I)
726     Mask[Indices[I]] = I;
727 }
728 
729 /// \returns inserting index of InsertElement or InsertValue instruction,
730 /// using Offset as base offset for index.
731 static Optional<unsigned> getInsertIndex(Value *InsertInst,
732                                          unsigned Offset = 0) {
733   int Index = Offset;
734   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
735     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
736       auto *VT = cast<FixedVectorType>(IE->getType());
737       if (CI->getValue().uge(VT->getNumElements()))
738         return None;
739       Index *= VT->getNumElements();
740       Index += CI->getZExtValue();
741       return Index;
742     }
743     return None;
744   }
745 
746   auto *IV = cast<InsertValueInst>(InsertInst);
747   Type *CurrentType = IV->getType();
748   for (unsigned I : IV->indices()) {
749     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
750       Index *= ST->getNumElements();
751       CurrentType = ST->getElementType(I);
752     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
753       Index *= AT->getNumElements();
754       CurrentType = AT->getElementType();
755     } else {
756       return None;
757     }
758     Index += I;
759   }
760   return Index;
761 }
762 
763 /// Reorders the list of scalars in accordance with the given \p Mask.
764 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
765                            ArrayRef<int> Mask) {
766   assert(!Mask.empty() && "Expected non-empty mask.");
767   SmallVector<Value *> Prev(Scalars.size(),
768                             UndefValue::get(Scalars.front()->getType()));
769   Prev.swap(Scalars);
770   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
771     if (Mask[I] != UndefMaskElem)
772       Scalars[Mask[I]] = Prev[I];
773 }
774 
775 /// Checks if the provided value does not require scheduling. It does not
776 /// require scheduling if this is not an instruction or it is an instruction
777 /// that does not read/write memory and all operands are either not instructions
778 /// or phi nodes or instructions from different blocks.
779 static bool areAllOperandsNonInsts(Value *V) {
780   auto *I = dyn_cast<Instruction>(V);
781   if (!I)
782     return true;
783   return !mayHaveNonDefUseDependency(*I) &&
784     all_of(I->operands(), [I](Value *V) {
785       auto *IO = dyn_cast<Instruction>(V);
786       if (!IO)
787         return true;
788       return isa<PHINode>(IO) || IO->getParent() != I->getParent();
789     });
790 }
791 
792 /// Checks if the provided value does not require scheduling. It does not
793 /// require scheduling if this is not an instruction or it is an instruction
794 /// that does not read/write memory and all users are phi nodes or instructions
795 /// from the different blocks.
796 static bool isUsedOutsideBlock(Value *V) {
797   auto *I = dyn_cast<Instruction>(V);
798   if (!I)
799     return true;
800   // Limits the number of uses to save compile time.
801   constexpr int UsesLimit = 8;
802   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
803          all_of(I->users(), [I](User *U) {
804            auto *IU = dyn_cast<Instruction>(U);
805            if (!IU)
806              return true;
807            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
808          });
809 }
810 
811 /// Checks if the specified value does not require scheduling. It does not
812 /// require scheduling if all operands and all users do not need to be scheduled
813 /// in the current basic block.
814 static bool doesNotNeedToBeScheduled(Value *V) {
815   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
816 }
817 
818 /// Checks if the specified array of instructions does not require scheduling.
819 /// It is so if all either instructions have operands that do not require
820 /// scheduling or their users do not require scheduling since they are phis or
821 /// in other basic blocks.
822 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
823   return !VL.empty() &&
824          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
825 }
826 
827 namespace slpvectorizer {
828 
829 /// Bottom Up SLP Vectorizer.
830 class BoUpSLP {
831   struct TreeEntry;
832   struct ScheduleData;
833 
834 public:
835   using ValueList = SmallVector<Value *, 8>;
836   using InstrList = SmallVector<Instruction *, 16>;
837   using ValueSet = SmallPtrSet<Value *, 16>;
838   using StoreList = SmallVector<StoreInst *, 8>;
839   using ExtraValueToDebugLocsMap =
840       MapVector<Value *, SmallVector<Instruction *, 2>>;
841   using OrdersType = SmallVector<unsigned, 4>;
842 
843   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
844           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
845           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
846           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
847       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
848         DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
849     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
850     // Use the vector register size specified by the target unless overridden
851     // by a command-line option.
852     // TODO: It would be better to limit the vectorization factor based on
853     //       data type rather than just register size. For example, x86 AVX has
854     //       256-bit registers, but it does not support integer operations
855     //       at that width (that requires AVX2).
856     if (MaxVectorRegSizeOption.getNumOccurrences())
857       MaxVecRegSize = MaxVectorRegSizeOption;
858     else
859       MaxVecRegSize =
860           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
861               .getFixedSize();
862 
863     if (MinVectorRegSizeOption.getNumOccurrences())
864       MinVecRegSize = MinVectorRegSizeOption;
865     else
866       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
867   }
868 
869   /// Vectorize the tree that starts with the elements in \p VL.
870   /// Returns the vectorized root.
871   Value *vectorizeTree();
872 
873   /// Vectorize the tree but with the list of externally used values \p
874   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
875   /// generated extractvalue instructions.
876   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
877 
878   /// \returns the cost incurred by unwanted spills and fills, caused by
879   /// holding live values over call sites.
880   InstructionCost getSpillCost() const;
881 
882   /// \returns the vectorization cost of the subtree that starts at \p VL.
883   /// A negative number means that this is profitable.
884   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
885 
886   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
887   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
888   void buildTree(ArrayRef<Value *> Roots,
889                  ArrayRef<Value *> UserIgnoreLst = None);
890 
891   /// Builds external uses of the vectorized scalars, i.e. the list of
892   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
893   /// ExternallyUsedValues contains additional list of external uses to handle
894   /// vectorization of reductions.
895   void
896   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
897 
898   /// Clear the internal data structures that are created by 'buildTree'.
899   void deleteTree() {
900     VectorizableTree.clear();
901     ScalarToTreeEntry.clear();
902     MustGather.clear();
903     ExternalUses.clear();
904     for (auto &Iter : BlocksSchedules) {
905       BlockScheduling *BS = Iter.second.get();
906       BS->clear();
907     }
908     MinBWs.clear();
909     InstrElementSize.clear();
910   }
911 
912   unsigned getTreeSize() const { return VectorizableTree.size(); }
913 
914   /// Perform LICM and CSE on the newly generated gather sequences.
915   void optimizeGatherSequence();
916 
917   /// Checks if the specified gather tree entry \p TE can be represented as a
918   /// shuffled vector entry + (possibly) permutation with other gathers. It
919   /// implements the checks only for possibly ordered scalars (Loads,
920   /// ExtractElement, ExtractValue), which can be part of the graph.
921   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
922 
923   /// Gets reordering data for the given tree entry. If the entry is vectorized
924   /// - just return ReorderIndices, otherwise check if the scalars can be
925   /// reordered and return the most optimal order.
926   /// \param TopToBottom If true, include the order of vectorized stores and
927   /// insertelement nodes, otherwise skip them.
928   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
929 
930   /// Reorders the current graph to the most profitable order starting from the
931   /// root node to the leaf nodes. The best order is chosen only from the nodes
932   /// of the same size (vectorization factor). Smaller nodes are considered
933   /// parts of subgraph with smaller VF and they are reordered independently. We
934   /// can make it because we still need to extend smaller nodes to the wider VF
935   /// and we can merge reordering shuffles with the widening shuffles.
936   void reorderTopToBottom();
937 
938   /// Reorders the current graph to the most profitable order starting from
939   /// leaves to the root. It allows to rotate small subgraphs and reduce the
940   /// number of reshuffles if the leaf nodes use the same order. In this case we
941   /// can merge the orders and just shuffle user node instead of shuffling its
942   /// operands. Plus, even the leaf nodes have different orders, it allows to
943   /// sink reordering in the graph closer to the root node and merge it later
944   /// during analysis.
945   void reorderBottomToTop(bool IgnoreReorder = false);
946 
947   /// \return The vector element size in bits to use when vectorizing the
948   /// expression tree ending at \p V. If V is a store, the size is the width of
949   /// the stored value. Otherwise, the size is the width of the largest loaded
950   /// value reaching V. This method is used by the vectorizer to calculate
951   /// vectorization factors.
952   unsigned getVectorElementSize(Value *V);
953 
954   /// Compute the minimum type sizes required to represent the entries in a
955   /// vectorizable tree.
956   void computeMinimumValueSizes();
957 
958   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
959   unsigned getMaxVecRegSize() const {
960     return MaxVecRegSize;
961   }
962 
963   // \returns minimum vector register size as set by cl::opt.
964   unsigned getMinVecRegSize() const {
965     return MinVecRegSize;
966   }
967 
968   unsigned getMinVF(unsigned Sz) const {
969     return std::max(2U, getMinVecRegSize() / Sz);
970   }
971 
972   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
973     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
974       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
975     return MaxVF ? MaxVF : UINT_MAX;
976   }
977 
978   /// Check if homogeneous aggregate is isomorphic to some VectorType.
979   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
980   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
981   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
982   ///
983   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
984   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
985 
986   /// \returns True if the VectorizableTree is both tiny and not fully
987   /// vectorizable. We do not vectorize such trees.
988   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
989 
990   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
991   /// can be load combined in the backend. Load combining may not be allowed in
992   /// the IR optimizer, so we do not want to alter the pattern. For example,
993   /// partially transforming a scalar bswap() pattern into vector code is
994   /// effectively impossible for the backend to undo.
995   /// TODO: If load combining is allowed in the IR optimizer, this analysis
996   ///       may not be necessary.
997   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
998 
999   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1000   /// can be load combined in the backend. Load combining may not be allowed in
1001   /// the IR optimizer, so we do not want to alter the pattern. For example,
1002   /// partially transforming a scalar bswap() pattern into vector code is
1003   /// effectively impossible for the backend to undo.
1004   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1005   ///       may not be necessary.
1006   bool isLoadCombineCandidate() const;
1007 
1008   OptimizationRemarkEmitter *getORE() { return ORE; }
1009 
1010   /// This structure holds any data we need about the edges being traversed
1011   /// during buildTree_rec(). We keep track of:
1012   /// (i) the user TreeEntry index, and
1013   /// (ii) the index of the edge.
1014   struct EdgeInfo {
1015     EdgeInfo() = default;
1016     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1017         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1018     /// The user TreeEntry.
1019     TreeEntry *UserTE = nullptr;
1020     /// The operand index of the use.
1021     unsigned EdgeIdx = UINT_MAX;
1022 #ifndef NDEBUG
1023     friend inline raw_ostream &operator<<(raw_ostream &OS,
1024                                           const BoUpSLP::EdgeInfo &EI) {
1025       EI.dump(OS);
1026       return OS;
1027     }
1028     /// Debug print.
1029     void dump(raw_ostream &OS) const {
1030       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1031          << " EdgeIdx:" << EdgeIdx << "}";
1032     }
1033     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1034 #endif
1035   };
1036 
1037   /// A helper data structure to hold the operands of a vector of instructions.
1038   /// This supports a fixed vector length for all operand vectors.
1039   class VLOperands {
1040     /// For each operand we need (i) the value, and (ii) the opcode that it
1041     /// would be attached to if the expression was in a left-linearized form.
1042     /// This is required to avoid illegal operand reordering.
1043     /// For example:
1044     /// \verbatim
1045     ///                         0 Op1
1046     ///                         |/
1047     /// Op1 Op2   Linearized    + Op2
1048     ///   \ /     ---------->   |/
1049     ///    -                    -
1050     ///
1051     /// Op1 - Op2            (0 + Op1) - Op2
1052     /// \endverbatim
1053     ///
1054     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1055     ///
1056     /// Another way to think of this is to track all the operations across the
1057     /// path from the operand all the way to the root of the tree and to
1058     /// calculate the operation that corresponds to this path. For example, the
1059     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1060     /// corresponding operation is a '-' (which matches the one in the
1061     /// linearized tree, as shown above).
1062     ///
1063     /// For lack of a better term, we refer to this operation as Accumulated
1064     /// Path Operation (APO).
1065     struct OperandData {
1066       OperandData() = default;
1067       OperandData(Value *V, bool APO, bool IsUsed)
1068           : V(V), APO(APO), IsUsed(IsUsed) {}
1069       /// The operand value.
1070       Value *V = nullptr;
1071       /// TreeEntries only allow a single opcode, or an alternate sequence of
1072       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1073       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1074       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1075       /// (e.g., Add/Mul)
1076       bool APO = false;
1077       /// Helper data for the reordering function.
1078       bool IsUsed = false;
1079     };
1080 
1081     /// During operand reordering, we are trying to select the operand at lane
1082     /// that matches best with the operand at the neighboring lane. Our
1083     /// selection is based on the type of value we are looking for. For example,
1084     /// if the neighboring lane has a load, we need to look for a load that is
1085     /// accessing a consecutive address. These strategies are summarized in the
1086     /// 'ReorderingMode' enumerator.
1087     enum class ReorderingMode {
1088       Load,     ///< Matching loads to consecutive memory addresses
1089       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1090       Constant, ///< Matching constants
1091       Splat,    ///< Matching the same instruction multiple times (broadcast)
1092       Failed,   ///< We failed to create a vectorizable group
1093     };
1094 
1095     using OperandDataVec = SmallVector<OperandData, 2>;
1096 
1097     /// A vector of operand vectors.
1098     SmallVector<OperandDataVec, 4> OpsVec;
1099 
1100     const DataLayout &DL;
1101     ScalarEvolution &SE;
1102     const BoUpSLP &R;
1103 
1104     /// \returns the operand data at \p OpIdx and \p Lane.
1105     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1106       return OpsVec[OpIdx][Lane];
1107     }
1108 
1109     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1110     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1111       return OpsVec[OpIdx][Lane];
1112     }
1113 
1114     /// Clears the used flag for all entries.
1115     void clearUsed() {
1116       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1117            OpIdx != NumOperands; ++OpIdx)
1118         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1119              ++Lane)
1120           OpsVec[OpIdx][Lane].IsUsed = false;
1121     }
1122 
1123     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1124     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1125       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1126     }
1127 
1128     // The hard-coded scores listed here are not very important, though it shall
1129     // be higher for better matches to improve the resulting cost. When
1130     // computing the scores of matching one sub-tree with another, we are
1131     // basically counting the number of values that are matching. So even if all
1132     // scores are set to 1, we would still get a decent matching result.
1133     // However, sometimes we have to break ties. For example we may have to
1134     // choose between matching loads vs matching opcodes. This is what these
1135     // scores are helping us with: they provide the order of preference. Also,
1136     // this is important if the scalar is externally used or used in another
1137     // tree entry node in the different lane.
1138 
1139     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1140     static const int ScoreConsecutiveLoads = 4;
1141     /// The same load multiple times. This should have a better score than
1142     /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1143     /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1144     /// a vector load and 1.0 for a broadcast.
1145     static const int ScoreSplatLoads = 3;
1146     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1147     static const int ScoreReversedLoads = 3;
1148     /// ExtractElementInst from same vector and consecutive indexes.
1149     static const int ScoreConsecutiveExtracts = 4;
1150     /// ExtractElementInst from same vector and reversed indices.
1151     static const int ScoreReversedExtracts = 3;
1152     /// Constants.
1153     static const int ScoreConstants = 2;
1154     /// Instructions with the same opcode.
1155     static const int ScoreSameOpcode = 2;
1156     /// Instructions with alt opcodes (e.g, add + sub).
1157     static const int ScoreAltOpcodes = 1;
1158     /// Identical instructions (a.k.a. splat or broadcast).
1159     static const int ScoreSplat = 1;
1160     /// Matching with an undef is preferable to failing.
1161     static const int ScoreUndef = 1;
1162     /// Score for failing to find a decent match.
1163     static const int ScoreFail = 0;
1164     /// Score if all users are vectorized.
1165     static const int ScoreAllUserVectorized = 1;
1166 
1167     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1168     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1169     /// MainAltOps.
1170     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1171                                ScalarEvolution &SE, int NumLanes,
1172                                ArrayRef<Value *> MainAltOps,
1173                                const TargetTransformInfo *TTI) {
1174       if (V1 == V2) {
1175         if (isa<LoadInst>(V1)) {
1176           // A broadcast of a load can be cheaper on some targets.
1177           // TODO: For now accept a broadcast load with no other internal uses.
1178           if (TTI->isLegalBroadcastLoad(V1->getType(), NumLanes) &&
1179               (int)V1->getNumUses() == NumLanes)
1180             return VLOperands::ScoreSplatLoads;
1181         }
1182         return VLOperands::ScoreSplat;
1183       }
1184 
1185       auto *LI1 = dyn_cast<LoadInst>(V1);
1186       auto *LI2 = dyn_cast<LoadInst>(V2);
1187       if (LI1 && LI2) {
1188         if (LI1->getParent() != LI2->getParent())
1189           return VLOperands::ScoreFail;
1190 
1191         Optional<int> Dist = getPointersDiff(
1192             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1193             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1194         if (!Dist || *Dist == 0)
1195           return VLOperands::ScoreFail;
1196         // The distance is too large - still may be profitable to use masked
1197         // loads/gathers.
1198         if (std::abs(*Dist) > NumLanes / 2)
1199           return VLOperands::ScoreAltOpcodes;
1200         // This still will detect consecutive loads, but we might have "holes"
1201         // in some cases. It is ok for non-power-2 vectorization and may produce
1202         // better results. It should not affect current vectorization.
1203         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1204                            : VLOperands::ScoreReversedLoads;
1205       }
1206 
1207       auto *C1 = dyn_cast<Constant>(V1);
1208       auto *C2 = dyn_cast<Constant>(V2);
1209       if (C1 && C2)
1210         return VLOperands::ScoreConstants;
1211 
1212       // Extracts from consecutive indexes of the same vector better score as
1213       // the extracts could be optimized away.
1214       Value *EV1;
1215       ConstantInt *Ex1Idx;
1216       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1217         // Undefs are always profitable for extractelements.
1218         if (isa<UndefValue>(V2))
1219           return VLOperands::ScoreConsecutiveExtracts;
1220         Value *EV2 = nullptr;
1221         ConstantInt *Ex2Idx = nullptr;
1222         if (match(V2,
1223                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1224                                                          m_Undef())))) {
1225           // Undefs are always profitable for extractelements.
1226           if (!Ex2Idx)
1227             return VLOperands::ScoreConsecutiveExtracts;
1228           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1229             return VLOperands::ScoreConsecutiveExtracts;
1230           if (EV2 == EV1) {
1231             int Idx1 = Ex1Idx->getZExtValue();
1232             int Idx2 = Ex2Idx->getZExtValue();
1233             int Dist = Idx2 - Idx1;
1234             // The distance is too large - still may be profitable to use
1235             // shuffles.
1236             if (std::abs(Dist) == 0)
1237               return VLOperands::ScoreSplat;
1238             if (std::abs(Dist) > NumLanes / 2)
1239               return VLOperands::ScoreSameOpcode;
1240             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1241                               : VLOperands::ScoreReversedExtracts;
1242           }
1243           return VLOperands::ScoreAltOpcodes;
1244         }
1245         return VLOperands::ScoreFail;
1246       }
1247 
1248       auto *I1 = dyn_cast<Instruction>(V1);
1249       auto *I2 = dyn_cast<Instruction>(V2);
1250       if (I1 && I2) {
1251         if (I1->getParent() != I2->getParent())
1252           return VLOperands::ScoreFail;
1253         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1254         Ops.push_back(I1);
1255         Ops.push_back(I2);
1256         InstructionsState S = getSameOpcode(Ops);
1257         // Note: Only consider instructions with <= 2 operands to avoid
1258         // complexity explosion.
1259         if (S.getOpcode() &&
1260             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1261              !S.isAltShuffle()) &&
1262             all_of(Ops, [&S](Value *V) {
1263               return cast<Instruction>(V)->getNumOperands() ==
1264                      S.MainOp->getNumOperands();
1265             }))
1266           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1267                                   : VLOperands::ScoreSameOpcode;
1268       }
1269 
1270       if (isa<UndefValue>(V2))
1271         return VLOperands::ScoreUndef;
1272 
1273       return VLOperands::ScoreFail;
1274     }
1275 
1276     /// \param Lane lane of the operands under analysis.
1277     /// \param OpIdx operand index in \p Lane lane we're looking the best
1278     /// candidate for.
1279     /// \param Idx operand index of the current candidate value.
1280     /// \returns The additional score due to possible broadcasting of the
1281     /// elements in the lane. It is more profitable to have power-of-2 unique
1282     /// elements in the lane, it will be vectorized with higher probability
1283     /// after removing duplicates. Currently the SLP vectorizer supports only
1284     /// vectorization of the power-of-2 number of unique scalars.
1285     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1286       Value *IdxLaneV = getData(Idx, Lane).V;
1287       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1288         return 0;
1289       SmallPtrSet<Value *, 4> Uniques;
1290       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1291         if (Ln == Lane)
1292           continue;
1293         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1294         if (!isa<Instruction>(OpIdxLnV))
1295           return 0;
1296         Uniques.insert(OpIdxLnV);
1297       }
1298       int UniquesCount = Uniques.size();
1299       int UniquesCntWithIdxLaneV =
1300           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1301       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1302       int UniquesCntWithOpIdxLaneV =
1303           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1304       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1305         return 0;
1306       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1307               UniquesCntWithOpIdxLaneV) -
1308              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1309     }
1310 
1311     /// \param Lane lane of the operands under analysis.
1312     /// \param OpIdx operand index in \p Lane lane we're looking the best
1313     /// candidate for.
1314     /// \param Idx operand index of the current candidate value.
1315     /// \returns The additional score for the scalar which users are all
1316     /// vectorized.
1317     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1318       Value *IdxLaneV = getData(Idx, Lane).V;
1319       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1320       // Do not care about number of uses for vector-like instructions
1321       // (extractelement/extractvalue with constant indices), they are extracts
1322       // themselves and already externally used. Vectorization of such
1323       // instructions does not add extra extractelement instruction, just may
1324       // remove it.
1325       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1326           isVectorLikeInstWithConstOps(OpIdxLaneV))
1327         return VLOperands::ScoreAllUserVectorized;
1328       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1329       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1330         return 0;
1331       return R.areAllUsersVectorized(IdxLaneI, None)
1332                  ? VLOperands::ScoreAllUserVectorized
1333                  : 0;
1334     }
1335 
1336     /// Go through the operands of \p LHS and \p RHS recursively until \p
1337     /// MaxLevel, and return the cummulative score. For example:
1338     /// \verbatim
1339     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1340     ///     \ /         \ /         \ /        \ /
1341     ///      +           +           +          +
1342     ///     G1          G2          G3         G4
1343     /// \endverbatim
1344     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1345     /// each level recursively, accumulating the score. It starts from matching
1346     /// the additions at level 0, then moves on to the loads (level 1). The
1347     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1348     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1349     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1350     /// Please note that the order of the operands does not matter, as we
1351     /// evaluate the score of all profitable combinations of operands. In
1352     /// other words the score of G1 and G4 is the same as G1 and G2. This
1353     /// heuristic is based on ideas described in:
1354     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1355     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1356     ///   Luís F. W. Góes
1357     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1358                            ArrayRef<Value *> MainAltOps) {
1359 
1360       // Get the shallow score of V1 and V2.
1361       int ShallowScoreAtThisLevel =
1362           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps, R.TTI);
1363 
1364       // If reached MaxLevel,
1365       //  or if V1 and V2 are not instructions,
1366       //  or if they are SPLAT,
1367       //  or if they are not consecutive,
1368       //  or if profitable to vectorize loads or extractelements, early return
1369       //  the current cost.
1370       auto *I1 = dyn_cast<Instruction>(LHS);
1371       auto *I2 = dyn_cast<Instruction>(RHS);
1372       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1373           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1374           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1375             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1376             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1377            ShallowScoreAtThisLevel))
1378         return ShallowScoreAtThisLevel;
1379       assert(I1 && I2 && "Should have early exited.");
1380 
1381       // Contains the I2 operand indexes that got matched with I1 operands.
1382       SmallSet<unsigned, 4> Op2Used;
1383 
1384       // Recursion towards the operands of I1 and I2. We are trying all possible
1385       // operand pairs, and keeping track of the best score.
1386       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1387            OpIdx1 != NumOperands1; ++OpIdx1) {
1388         // Try to pair op1I with the best operand of I2.
1389         int MaxTmpScore = 0;
1390         unsigned MaxOpIdx2 = 0;
1391         bool FoundBest = false;
1392         // If I2 is commutative try all combinations.
1393         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1394         unsigned ToIdx = isCommutative(I2)
1395                              ? I2->getNumOperands()
1396                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1397         assert(FromIdx <= ToIdx && "Bad index");
1398         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1399           // Skip operands already paired with OpIdx1.
1400           if (Op2Used.count(OpIdx2))
1401             continue;
1402           // Recursively calculate the cost at each level
1403           int TmpScore =
1404               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1405                                  CurrLevel + 1, MaxLevel, None);
1406           // Look for the best score.
1407           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1408             MaxTmpScore = TmpScore;
1409             MaxOpIdx2 = OpIdx2;
1410             FoundBest = true;
1411           }
1412         }
1413         if (FoundBest) {
1414           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1415           Op2Used.insert(MaxOpIdx2);
1416           ShallowScoreAtThisLevel += MaxTmpScore;
1417         }
1418       }
1419       return ShallowScoreAtThisLevel;
1420     }
1421 
1422     /// Score scaling factor for fully compatible instructions but with
1423     /// different number of external uses. Allows better selection of the
1424     /// instructions with less external uses.
1425     static const int ScoreScaleFactor = 10;
1426 
1427     /// \Returns the look-ahead score, which tells us how much the sub-trees
1428     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1429     /// score. This helps break ties in an informed way when we cannot decide on
1430     /// the order of the operands by just considering the immediate
1431     /// predecessors.
1432     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1433                           int Lane, unsigned OpIdx, unsigned Idx,
1434                           bool &IsUsed) {
1435       int Score =
1436           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1437       if (Score) {
1438         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1439         if (Score <= -SplatScore) {
1440           // Set the minimum score for splat-like sequence to avoid setting
1441           // failed state.
1442           Score = 1;
1443         } else {
1444           Score += SplatScore;
1445           // Scale score to see the difference between different operands
1446           // and similar operands but all vectorized/not all vectorized
1447           // uses. It does not affect actual selection of the best
1448           // compatible operand in general, just allows to select the
1449           // operand with all vectorized uses.
1450           Score *= ScoreScaleFactor;
1451           Score += getExternalUseScore(Lane, OpIdx, Idx);
1452           IsUsed = true;
1453         }
1454       }
1455       return Score;
1456     }
1457 
1458     /// Best defined scores per lanes between the passes. Used to choose the
1459     /// best operand (with the highest score) between the passes.
1460     /// The key - {Operand Index, Lane}.
1461     /// The value - the best score between the passes for the lane and the
1462     /// operand.
1463     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1464         BestScoresPerLanes;
1465 
1466     // Search all operands in Ops[*][Lane] for the one that matches best
1467     // Ops[OpIdx][LastLane] and return its opreand index.
1468     // If no good match can be found, return None.
1469     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1470                                       ArrayRef<ReorderingMode> ReorderingModes,
1471                                       ArrayRef<Value *> MainAltOps) {
1472       unsigned NumOperands = getNumOperands();
1473 
1474       // The operand of the previous lane at OpIdx.
1475       Value *OpLastLane = getData(OpIdx, LastLane).V;
1476 
1477       // Our strategy mode for OpIdx.
1478       ReorderingMode RMode = ReorderingModes[OpIdx];
1479       if (RMode == ReorderingMode::Failed)
1480         return None;
1481 
1482       // The linearized opcode of the operand at OpIdx, Lane.
1483       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1484 
1485       // The best operand index and its score.
1486       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1487       // are using the score to differentiate between the two.
1488       struct BestOpData {
1489         Optional<unsigned> Idx = None;
1490         unsigned Score = 0;
1491       } BestOp;
1492       BestOp.Score =
1493           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1494               .first->second;
1495 
1496       // Track if the operand must be marked as used. If the operand is set to
1497       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1498       // want to reestimate the operands again on the following iterations).
1499       bool IsUsed =
1500           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1501       // Iterate through all unused operands and look for the best.
1502       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1503         // Get the operand at Idx and Lane.
1504         OperandData &OpData = getData(Idx, Lane);
1505         Value *Op = OpData.V;
1506         bool OpAPO = OpData.APO;
1507 
1508         // Skip already selected operands.
1509         if (OpData.IsUsed)
1510           continue;
1511 
1512         // Skip if we are trying to move the operand to a position with a
1513         // different opcode in the linearized tree form. This would break the
1514         // semantics.
1515         if (OpAPO != OpIdxAPO)
1516           continue;
1517 
1518         // Look for an operand that matches the current mode.
1519         switch (RMode) {
1520         case ReorderingMode::Load:
1521         case ReorderingMode::Constant:
1522         case ReorderingMode::Opcode: {
1523           bool LeftToRight = Lane > LastLane;
1524           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1525           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1526           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1527                                         OpIdx, Idx, IsUsed);
1528           if (Score > static_cast<int>(BestOp.Score)) {
1529             BestOp.Idx = Idx;
1530             BestOp.Score = Score;
1531             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1532           }
1533           break;
1534         }
1535         case ReorderingMode::Splat:
1536           if (Op == OpLastLane)
1537             BestOp.Idx = Idx;
1538           break;
1539         case ReorderingMode::Failed:
1540           llvm_unreachable("Not expected Failed reordering mode.");
1541         }
1542       }
1543 
1544       if (BestOp.Idx) {
1545         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1546         return BestOp.Idx;
1547       }
1548       // If we could not find a good match return None.
1549       return None;
1550     }
1551 
1552     /// Helper for reorderOperandVecs.
1553     /// \returns the lane that we should start reordering from. This is the one
1554     /// which has the least number of operands that can freely move about or
1555     /// less profitable because it already has the most optimal set of operands.
1556     unsigned getBestLaneToStartReordering() const {
1557       unsigned Min = UINT_MAX;
1558       unsigned SameOpNumber = 0;
1559       // std::pair<unsigned, unsigned> is used to implement a simple voting
1560       // algorithm and choose the lane with the least number of operands that
1561       // can freely move about or less profitable because it already has the
1562       // most optimal set of operands. The first unsigned is a counter for
1563       // voting, the second unsigned is the counter of lanes with instructions
1564       // with same/alternate opcodes and same parent basic block.
1565       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1566       // Try to be closer to the original results, if we have multiple lanes
1567       // with same cost. If 2 lanes have the same cost, use the one with the
1568       // lowest index.
1569       for (int I = getNumLanes(); I > 0; --I) {
1570         unsigned Lane = I - 1;
1571         OperandsOrderData NumFreeOpsHash =
1572             getMaxNumOperandsThatCanBeReordered(Lane);
1573         // Compare the number of operands that can move and choose the one with
1574         // the least number.
1575         if (NumFreeOpsHash.NumOfAPOs < Min) {
1576           Min = NumFreeOpsHash.NumOfAPOs;
1577           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1578           HashMap.clear();
1579           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1580         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1581                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1582           // Select the most optimal lane in terms of number of operands that
1583           // should be moved around.
1584           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1585           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1586         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1587                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1588           auto It = HashMap.find(NumFreeOpsHash.Hash);
1589           if (It == HashMap.end())
1590             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1591           else
1592             ++It->second.first;
1593         }
1594       }
1595       // Select the lane with the minimum counter.
1596       unsigned BestLane = 0;
1597       unsigned CntMin = UINT_MAX;
1598       for (const auto &Data : reverse(HashMap)) {
1599         if (Data.second.first < CntMin) {
1600           CntMin = Data.second.first;
1601           BestLane = Data.second.second;
1602         }
1603       }
1604       return BestLane;
1605     }
1606 
1607     /// Data structure that helps to reorder operands.
1608     struct OperandsOrderData {
1609       /// The best number of operands with the same APOs, which can be
1610       /// reordered.
1611       unsigned NumOfAPOs = UINT_MAX;
1612       /// Number of operands with the same/alternate instruction opcode and
1613       /// parent.
1614       unsigned NumOpsWithSameOpcodeParent = 0;
1615       /// Hash for the actual operands ordering.
1616       /// Used to count operands, actually their position id and opcode
1617       /// value. It is used in the voting mechanism to find the lane with the
1618       /// least number of operands that can freely move about or less profitable
1619       /// because it already has the most optimal set of operands. Can be
1620       /// replaced with SmallVector<unsigned> instead but hash code is faster
1621       /// and requires less memory.
1622       unsigned Hash = 0;
1623     };
1624     /// \returns the maximum number of operands that are allowed to be reordered
1625     /// for \p Lane and the number of compatible instructions(with the same
1626     /// parent/opcode). This is used as a heuristic for selecting the first lane
1627     /// to start operand reordering.
1628     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1629       unsigned CntTrue = 0;
1630       unsigned NumOperands = getNumOperands();
1631       // Operands with the same APO can be reordered. We therefore need to count
1632       // how many of them we have for each APO, like this: Cnt[APO] = x.
1633       // Since we only have two APOs, namely true and false, we can avoid using
1634       // a map. Instead we can simply count the number of operands that
1635       // correspond to one of them (in this case the 'true' APO), and calculate
1636       // the other by subtracting it from the total number of operands.
1637       // Operands with the same instruction opcode and parent are more
1638       // profitable since we don't need to move them in many cases, with a high
1639       // probability such lane already can be vectorized effectively.
1640       bool AllUndefs = true;
1641       unsigned NumOpsWithSameOpcodeParent = 0;
1642       Instruction *OpcodeI = nullptr;
1643       BasicBlock *Parent = nullptr;
1644       unsigned Hash = 0;
1645       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1646         const OperandData &OpData = getData(OpIdx, Lane);
1647         if (OpData.APO)
1648           ++CntTrue;
1649         // Use Boyer-Moore majority voting for finding the majority opcode and
1650         // the number of times it occurs.
1651         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1652           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1653               I->getParent() != Parent) {
1654             if (NumOpsWithSameOpcodeParent == 0) {
1655               NumOpsWithSameOpcodeParent = 1;
1656               OpcodeI = I;
1657               Parent = I->getParent();
1658             } else {
1659               --NumOpsWithSameOpcodeParent;
1660             }
1661           } else {
1662             ++NumOpsWithSameOpcodeParent;
1663           }
1664         }
1665         Hash = hash_combine(
1666             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1667         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1668       }
1669       if (AllUndefs)
1670         return {};
1671       OperandsOrderData Data;
1672       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1673       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1674       Data.Hash = Hash;
1675       return Data;
1676     }
1677 
1678     /// Go through the instructions in VL and append their operands.
1679     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1680       assert(!VL.empty() && "Bad VL");
1681       assert((empty() || VL.size() == getNumLanes()) &&
1682              "Expected same number of lanes");
1683       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1684       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1685       OpsVec.resize(NumOperands);
1686       unsigned NumLanes = VL.size();
1687       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1688         OpsVec[OpIdx].resize(NumLanes);
1689         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1690           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1691           // Our tree has just 3 nodes: the root and two operands.
1692           // It is therefore trivial to get the APO. We only need to check the
1693           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1694           // RHS operand. The LHS operand of both add and sub is never attached
1695           // to an inversese operation in the linearized form, therefore its APO
1696           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1697 
1698           // Since operand reordering is performed on groups of commutative
1699           // operations or alternating sequences (e.g., +, -), we can safely
1700           // tell the inverse operations by checking commutativity.
1701           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1702           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1703           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1704                                  APO, false};
1705         }
1706       }
1707     }
1708 
1709     /// \returns the number of operands.
1710     unsigned getNumOperands() const { return OpsVec.size(); }
1711 
1712     /// \returns the number of lanes.
1713     unsigned getNumLanes() const { return OpsVec[0].size(); }
1714 
1715     /// \returns the operand value at \p OpIdx and \p Lane.
1716     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1717       return getData(OpIdx, Lane).V;
1718     }
1719 
1720     /// \returns true if the data structure is empty.
1721     bool empty() const { return OpsVec.empty(); }
1722 
1723     /// Clears the data.
1724     void clear() { OpsVec.clear(); }
1725 
1726     /// \Returns true if there are enough operands identical to \p Op to fill
1727     /// the whole vector.
1728     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1729     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1730       bool OpAPO = getData(OpIdx, Lane).APO;
1731       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1732         if (Ln == Lane)
1733           continue;
1734         // This is set to true if we found a candidate for broadcast at Lane.
1735         bool FoundCandidate = false;
1736         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1737           OperandData &Data = getData(OpI, Ln);
1738           if (Data.APO != OpAPO || Data.IsUsed)
1739             continue;
1740           if (Data.V == Op) {
1741             FoundCandidate = true;
1742             Data.IsUsed = true;
1743             break;
1744           }
1745         }
1746         if (!FoundCandidate)
1747           return false;
1748       }
1749       return true;
1750     }
1751 
1752   public:
1753     /// Initialize with all the operands of the instruction vector \p RootVL.
1754     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1755                ScalarEvolution &SE, const BoUpSLP &R)
1756         : DL(DL), SE(SE), R(R) {
1757       // Append all the operands of RootVL.
1758       appendOperandsOfVL(RootVL);
1759     }
1760 
1761     /// \Returns a value vector with the operands across all lanes for the
1762     /// opearnd at \p OpIdx.
1763     ValueList getVL(unsigned OpIdx) const {
1764       ValueList OpVL(OpsVec[OpIdx].size());
1765       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1766              "Expected same num of lanes across all operands");
1767       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1768         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1769       return OpVL;
1770     }
1771 
1772     // Performs operand reordering for 2 or more operands.
1773     // The original operands are in OrigOps[OpIdx][Lane].
1774     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1775     void reorder() {
1776       unsigned NumOperands = getNumOperands();
1777       unsigned NumLanes = getNumLanes();
1778       // Each operand has its own mode. We are using this mode to help us select
1779       // the instructions for each lane, so that they match best with the ones
1780       // we have selected so far.
1781       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1782 
1783       // This is a greedy single-pass algorithm. We are going over each lane
1784       // once and deciding on the best order right away with no back-tracking.
1785       // However, in order to increase its effectiveness, we start with the lane
1786       // that has operands that can move the least. For example, given the
1787       // following lanes:
1788       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1789       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1790       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1791       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1792       // we will start at Lane 1, since the operands of the subtraction cannot
1793       // be reordered. Then we will visit the rest of the lanes in a circular
1794       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1795 
1796       // Find the first lane that we will start our search from.
1797       unsigned FirstLane = getBestLaneToStartReordering();
1798 
1799       // Initialize the modes.
1800       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1801         Value *OpLane0 = getValue(OpIdx, FirstLane);
1802         // Keep track if we have instructions with all the same opcode on one
1803         // side.
1804         if (isa<LoadInst>(OpLane0))
1805           ReorderingModes[OpIdx] = ReorderingMode::Load;
1806         else if (isa<Instruction>(OpLane0)) {
1807           // Check if OpLane0 should be broadcast.
1808           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1809             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1810           else
1811             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1812         }
1813         else if (isa<Constant>(OpLane0))
1814           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1815         else if (isa<Argument>(OpLane0))
1816           // Our best hope is a Splat. It may save some cost in some cases.
1817           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1818         else
1819           // NOTE: This should be unreachable.
1820           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1821       }
1822 
1823       // Check that we don't have same operands. No need to reorder if operands
1824       // are just perfect diamond or shuffled diamond match. Do not do it only
1825       // for possible broadcasts or non-power of 2 number of scalars (just for
1826       // now).
1827       auto &&SkipReordering = [this]() {
1828         SmallPtrSet<Value *, 4> UniqueValues;
1829         ArrayRef<OperandData> Op0 = OpsVec.front();
1830         for (const OperandData &Data : Op0)
1831           UniqueValues.insert(Data.V);
1832         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1833           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1834                 return !UniqueValues.contains(Data.V);
1835               }))
1836             return false;
1837         }
1838         // TODO: Check if we can remove a check for non-power-2 number of
1839         // scalars after full support of non-power-2 vectorization.
1840         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1841       };
1842 
1843       // If the initial strategy fails for any of the operand indexes, then we
1844       // perform reordering again in a second pass. This helps avoid assigning
1845       // high priority to the failed strategy, and should improve reordering for
1846       // the non-failed operand indexes.
1847       for (int Pass = 0; Pass != 2; ++Pass) {
1848         // Check if no need to reorder operands since they're are perfect or
1849         // shuffled diamond match.
1850         // Need to to do it to avoid extra external use cost counting for
1851         // shuffled matches, which may cause regressions.
1852         if (SkipReordering())
1853           break;
1854         // Skip the second pass if the first pass did not fail.
1855         bool StrategyFailed = false;
1856         // Mark all operand data as free to use.
1857         clearUsed();
1858         // We keep the original operand order for the FirstLane, so reorder the
1859         // rest of the lanes. We are visiting the nodes in a circular fashion,
1860         // using FirstLane as the center point and increasing the radius
1861         // distance.
1862         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1863         for (unsigned I = 0; I < NumOperands; ++I)
1864           MainAltOps[I].push_back(getData(I, FirstLane).V);
1865 
1866         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1867           // Visit the lane on the right and then the lane on the left.
1868           for (int Direction : {+1, -1}) {
1869             int Lane = FirstLane + Direction * Distance;
1870             if (Lane < 0 || Lane >= (int)NumLanes)
1871               continue;
1872             int LastLane = Lane - Direction;
1873             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1874                    "Out of bounds");
1875             // Look for a good match for each operand.
1876             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1877               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1878               Optional<unsigned> BestIdx = getBestOperand(
1879                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1880               // By not selecting a value, we allow the operands that follow to
1881               // select a better matching value. We will get a non-null value in
1882               // the next run of getBestOperand().
1883               if (BestIdx) {
1884                 // Swap the current operand with the one returned by
1885                 // getBestOperand().
1886                 swap(OpIdx, BestIdx.getValue(), Lane);
1887               } else {
1888                 // We failed to find a best operand, set mode to 'Failed'.
1889                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1890                 // Enable the second pass.
1891                 StrategyFailed = true;
1892               }
1893               // Try to get the alternate opcode and follow it during analysis.
1894               if (MainAltOps[OpIdx].size() != 2) {
1895                 OperandData &AltOp = getData(OpIdx, Lane);
1896                 InstructionsState OpS =
1897                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1898                 if (OpS.getOpcode() && OpS.isAltShuffle())
1899                   MainAltOps[OpIdx].push_back(AltOp.V);
1900               }
1901             }
1902           }
1903         }
1904         // Skip second pass if the strategy did not fail.
1905         if (!StrategyFailed)
1906           break;
1907       }
1908     }
1909 
1910 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1911     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1912       switch (RMode) {
1913       case ReorderingMode::Load:
1914         return "Load";
1915       case ReorderingMode::Opcode:
1916         return "Opcode";
1917       case ReorderingMode::Constant:
1918         return "Constant";
1919       case ReorderingMode::Splat:
1920         return "Splat";
1921       case ReorderingMode::Failed:
1922         return "Failed";
1923       }
1924       llvm_unreachable("Unimplemented Reordering Type");
1925     }
1926 
1927     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1928                                                    raw_ostream &OS) {
1929       return OS << getModeStr(RMode);
1930     }
1931 
1932     /// Debug print.
1933     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1934       printMode(RMode, dbgs());
1935     }
1936 
1937     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1938       return printMode(RMode, OS);
1939     }
1940 
1941     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1942       const unsigned Indent = 2;
1943       unsigned Cnt = 0;
1944       for (const OperandDataVec &OpDataVec : OpsVec) {
1945         OS << "Operand " << Cnt++ << "\n";
1946         for (const OperandData &OpData : OpDataVec) {
1947           OS.indent(Indent) << "{";
1948           if (Value *V = OpData.V)
1949             OS << *V;
1950           else
1951             OS << "null";
1952           OS << ", APO:" << OpData.APO << "}\n";
1953         }
1954         OS << "\n";
1955       }
1956       return OS;
1957     }
1958 
1959     /// Debug print.
1960     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1961 #endif
1962   };
1963 
1964   /// Checks if the instruction is marked for deletion.
1965   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1966 
1967   /// Removes an instruction from its block and eventually deletes it.
1968   /// It's like Instruction::eraseFromParent() except that the actual deletion
1969   /// is delayed until BoUpSLP is destructed.
1970   void eraseInstruction(Instruction *I) {
1971     DeletedInstructions.insert(I);
1972   }
1973 
1974   ~BoUpSLP();
1975 
1976 private:
1977   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1978   /// reordering (i.e. the operands can be reordered because they have only one
1979   /// user and reordarable).
1980   /// \param ReorderableGathers List of all gather nodes that require reordering
1981   /// (e.g., gather of extractlements or partially vectorizable loads).
1982   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1983   /// reordering, subset of \p NonVectorized.
1984   bool
1985   canReorderOperands(TreeEntry *UserTE,
1986                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1987                      ArrayRef<TreeEntry *> ReorderableGathers,
1988                      SmallVectorImpl<TreeEntry *> &GatherOps);
1989 
1990   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1991   /// if any. If it is not vectorized (gather node), returns nullptr.
1992   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1993     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1994     TreeEntry *TE = nullptr;
1995     const auto *It = find_if(VL, [this, &TE](Value *V) {
1996       TE = getTreeEntry(V);
1997       return TE;
1998     });
1999     if (It != VL.end() && TE->isSame(VL))
2000       return TE;
2001     return nullptr;
2002   }
2003 
2004   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2005   /// if any. If it is not vectorized (gather node), returns nullptr.
2006   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2007                                         unsigned OpIdx) const {
2008     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2009         const_cast<TreeEntry *>(UserTE), OpIdx);
2010   }
2011 
2012   /// Checks if all users of \p I are the part of the vectorization tree.
2013   bool areAllUsersVectorized(Instruction *I,
2014                              ArrayRef<Value *> VectorizedVals) const;
2015 
2016   /// \returns the cost of the vectorizable entry.
2017   InstructionCost getEntryCost(const TreeEntry *E,
2018                                ArrayRef<Value *> VectorizedVals);
2019 
2020   /// This is the recursive part of buildTree.
2021   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2022                      const EdgeInfo &EI);
2023 
2024   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2025   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2026   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2027   /// returns false, setting \p CurrentOrder to either an empty vector or a
2028   /// non-identity permutation that allows to reuse extract instructions.
2029   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2030                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2031 
2032   /// Vectorize a single entry in the tree.
2033   Value *vectorizeTree(TreeEntry *E);
2034 
2035   /// Vectorize a single entry in the tree, starting in \p VL.
2036   Value *vectorizeTree(ArrayRef<Value *> VL);
2037 
2038   /// Create a new vector from a list of scalar values.  Produces a sequence
2039   /// which exploits values reused across lanes, and arranges the inserts
2040   /// for ease of later optimization.
2041   Value *createBuildVector(ArrayRef<Value *> VL);
2042 
2043   /// \returns the scalarization cost for this type. Scalarization in this
2044   /// context means the creation of vectors from a group of scalars. If \p
2045   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2046   /// vector elements.
2047   InstructionCost getGatherCost(FixedVectorType *Ty,
2048                                 const APInt &ShuffledIndices,
2049                                 bool NeedToShuffle) const;
2050 
2051   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2052   /// tree entries.
2053   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2054   /// previous tree entries. \p Mask is filled with the shuffle mask.
2055   Optional<TargetTransformInfo::ShuffleKind>
2056   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2057                         SmallVectorImpl<const TreeEntry *> &Entries);
2058 
2059   /// \returns the scalarization cost for this list of values. Assuming that
2060   /// this subtree gets vectorized, we may need to extract the values from the
2061   /// roots. This method calculates the cost of extracting the values.
2062   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2063 
2064   /// Set the Builder insert point to one after the last instruction in
2065   /// the bundle
2066   void setInsertPointAfterBundle(const TreeEntry *E);
2067 
2068   /// \returns a vector from a collection of scalars in \p VL.
2069   Value *gather(ArrayRef<Value *> VL);
2070 
2071   /// \returns whether the VectorizableTree is fully vectorizable and will
2072   /// be beneficial even the tree height is tiny.
2073   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2074 
2075   /// Reorder commutative or alt operands to get better probability of
2076   /// generating vectorized code.
2077   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2078                                              SmallVectorImpl<Value *> &Left,
2079                                              SmallVectorImpl<Value *> &Right,
2080                                              const DataLayout &DL,
2081                                              ScalarEvolution &SE,
2082                                              const BoUpSLP &R);
2083   struct TreeEntry {
2084     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2085     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2086 
2087     /// \returns true if the scalars in VL are equal to this entry.
2088     bool isSame(ArrayRef<Value *> VL) const {
2089       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2090         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2091           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2092         return VL.size() == Mask.size() &&
2093                std::equal(VL.begin(), VL.end(), Mask.begin(),
2094                           [Scalars](Value *V, int Idx) {
2095                             return (isa<UndefValue>(V) &&
2096                                     Idx == UndefMaskElem) ||
2097                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2098                           });
2099       };
2100       if (!ReorderIndices.empty()) {
2101         // TODO: implement matching if the nodes are just reordered, still can
2102         // treat the vector as the same if the list of scalars matches VL
2103         // directly, without reordering.
2104         SmallVector<int> Mask;
2105         inversePermutation(ReorderIndices, Mask);
2106         if (VL.size() == Scalars.size())
2107           return IsSame(Scalars, Mask);
2108         if (VL.size() == ReuseShuffleIndices.size()) {
2109           ::addMask(Mask, ReuseShuffleIndices);
2110           return IsSame(Scalars, Mask);
2111         }
2112         return false;
2113       }
2114       return IsSame(Scalars, ReuseShuffleIndices);
2115     }
2116 
2117     /// \returns true if current entry has same operands as \p TE.
2118     bool hasEqualOperands(const TreeEntry &TE) const {
2119       if (TE.getNumOperands() != getNumOperands())
2120         return false;
2121       SmallBitVector Used(getNumOperands());
2122       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2123         unsigned PrevCount = Used.count();
2124         for (unsigned K = 0; K < E; ++K) {
2125           if (Used.test(K))
2126             continue;
2127           if (getOperand(K) == TE.getOperand(I)) {
2128             Used.set(K);
2129             break;
2130           }
2131         }
2132         // Check if we actually found the matching operand.
2133         if (PrevCount == Used.count())
2134           return false;
2135       }
2136       return true;
2137     }
2138 
2139     /// \return Final vectorization factor for the node. Defined by the total
2140     /// number of vectorized scalars, including those, used several times in the
2141     /// entry and counted in the \a ReuseShuffleIndices, if any.
2142     unsigned getVectorFactor() const {
2143       if (!ReuseShuffleIndices.empty())
2144         return ReuseShuffleIndices.size();
2145       return Scalars.size();
2146     };
2147 
2148     /// A vector of scalars.
2149     ValueList Scalars;
2150 
2151     /// The Scalars are vectorized into this value. It is initialized to Null.
2152     Value *VectorizedValue = nullptr;
2153 
2154     /// Do we need to gather this sequence or vectorize it
2155     /// (either with vector instruction or with scatter/gather
2156     /// intrinsics for store/load)?
2157     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2158     EntryState State;
2159 
2160     /// Does this sequence require some shuffling?
2161     SmallVector<int, 4> ReuseShuffleIndices;
2162 
2163     /// Does this entry require reordering?
2164     SmallVector<unsigned, 4> ReorderIndices;
2165 
2166     /// Points back to the VectorizableTree.
2167     ///
2168     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2169     /// to be a pointer and needs to be able to initialize the child iterator.
2170     /// Thus we need a reference back to the container to translate the indices
2171     /// to entries.
2172     VecTreeTy &Container;
2173 
2174     /// The TreeEntry index containing the user of this entry.  We can actually
2175     /// have multiple users so the data structure is not truly a tree.
2176     SmallVector<EdgeInfo, 1> UserTreeIndices;
2177 
2178     /// The index of this treeEntry in VectorizableTree.
2179     int Idx = -1;
2180 
2181   private:
2182     /// The operands of each instruction in each lane Operands[op_index][lane].
2183     /// Note: This helps avoid the replication of the code that performs the
2184     /// reordering of operands during buildTree_rec() and vectorizeTree().
2185     SmallVector<ValueList, 2> Operands;
2186 
2187     /// The main/alternate instruction.
2188     Instruction *MainOp = nullptr;
2189     Instruction *AltOp = nullptr;
2190 
2191   public:
2192     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2193     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2194       if (Operands.size() < OpIdx + 1)
2195         Operands.resize(OpIdx + 1);
2196       assert(Operands[OpIdx].empty() && "Already resized?");
2197       assert(OpVL.size() <= Scalars.size() &&
2198              "Number of operands is greater than the number of scalars.");
2199       Operands[OpIdx].resize(OpVL.size());
2200       copy(OpVL, Operands[OpIdx].begin());
2201     }
2202 
2203     /// Set the operands of this bundle in their original order.
2204     void setOperandsInOrder() {
2205       assert(Operands.empty() && "Already initialized?");
2206       auto *I0 = cast<Instruction>(Scalars[0]);
2207       Operands.resize(I0->getNumOperands());
2208       unsigned NumLanes = Scalars.size();
2209       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2210            OpIdx != NumOperands; ++OpIdx) {
2211         Operands[OpIdx].resize(NumLanes);
2212         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2213           auto *I = cast<Instruction>(Scalars[Lane]);
2214           assert(I->getNumOperands() == NumOperands &&
2215                  "Expected same number of operands");
2216           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2217         }
2218       }
2219     }
2220 
2221     /// Reorders operands of the node to the given mask \p Mask.
2222     void reorderOperands(ArrayRef<int> Mask) {
2223       for (ValueList &Operand : Operands)
2224         reorderScalars(Operand, Mask);
2225     }
2226 
2227     /// \returns the \p OpIdx operand of this TreeEntry.
2228     ValueList &getOperand(unsigned OpIdx) {
2229       assert(OpIdx < Operands.size() && "Off bounds");
2230       return Operands[OpIdx];
2231     }
2232 
2233     /// \returns the \p OpIdx operand of this TreeEntry.
2234     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2235       assert(OpIdx < Operands.size() && "Off bounds");
2236       return Operands[OpIdx];
2237     }
2238 
2239     /// \returns the number of operands.
2240     unsigned getNumOperands() const { return Operands.size(); }
2241 
2242     /// \return the single \p OpIdx operand.
2243     Value *getSingleOperand(unsigned OpIdx) const {
2244       assert(OpIdx < Operands.size() && "Off bounds");
2245       assert(!Operands[OpIdx].empty() && "No operand available");
2246       return Operands[OpIdx][0];
2247     }
2248 
2249     /// Some of the instructions in the list have alternate opcodes.
2250     bool isAltShuffle() const { return MainOp != AltOp; }
2251 
2252     bool isOpcodeOrAlt(Instruction *I) const {
2253       unsigned CheckedOpcode = I->getOpcode();
2254       return (getOpcode() == CheckedOpcode ||
2255               getAltOpcode() == CheckedOpcode);
2256     }
2257 
2258     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2259     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2260     /// \p OpValue.
2261     Value *isOneOf(Value *Op) const {
2262       auto *I = dyn_cast<Instruction>(Op);
2263       if (I && isOpcodeOrAlt(I))
2264         return Op;
2265       return MainOp;
2266     }
2267 
2268     void setOperations(const InstructionsState &S) {
2269       MainOp = S.MainOp;
2270       AltOp = S.AltOp;
2271     }
2272 
2273     Instruction *getMainOp() const {
2274       return MainOp;
2275     }
2276 
2277     Instruction *getAltOp() const {
2278       return AltOp;
2279     }
2280 
2281     /// The main/alternate opcodes for the list of instructions.
2282     unsigned getOpcode() const {
2283       return MainOp ? MainOp->getOpcode() : 0;
2284     }
2285 
2286     unsigned getAltOpcode() const {
2287       return AltOp ? AltOp->getOpcode() : 0;
2288     }
2289 
2290     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2291     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2292     int findLaneForValue(Value *V) const {
2293       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2294       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2295       if (!ReorderIndices.empty())
2296         FoundLane = ReorderIndices[FoundLane];
2297       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2298       if (!ReuseShuffleIndices.empty()) {
2299         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2300                                   find(ReuseShuffleIndices, FoundLane));
2301       }
2302       return FoundLane;
2303     }
2304 
2305 #ifndef NDEBUG
2306     /// Debug printer.
2307     LLVM_DUMP_METHOD void dump() const {
2308       dbgs() << Idx << ".\n";
2309       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2310         dbgs() << "Operand " << OpI << ":\n";
2311         for (const Value *V : Operands[OpI])
2312           dbgs().indent(2) << *V << "\n";
2313       }
2314       dbgs() << "Scalars: \n";
2315       for (Value *V : Scalars)
2316         dbgs().indent(2) << *V << "\n";
2317       dbgs() << "State: ";
2318       switch (State) {
2319       case Vectorize:
2320         dbgs() << "Vectorize\n";
2321         break;
2322       case ScatterVectorize:
2323         dbgs() << "ScatterVectorize\n";
2324         break;
2325       case NeedToGather:
2326         dbgs() << "NeedToGather\n";
2327         break;
2328       }
2329       dbgs() << "MainOp: ";
2330       if (MainOp)
2331         dbgs() << *MainOp << "\n";
2332       else
2333         dbgs() << "NULL\n";
2334       dbgs() << "AltOp: ";
2335       if (AltOp)
2336         dbgs() << *AltOp << "\n";
2337       else
2338         dbgs() << "NULL\n";
2339       dbgs() << "VectorizedValue: ";
2340       if (VectorizedValue)
2341         dbgs() << *VectorizedValue << "\n";
2342       else
2343         dbgs() << "NULL\n";
2344       dbgs() << "ReuseShuffleIndices: ";
2345       if (ReuseShuffleIndices.empty())
2346         dbgs() << "Empty";
2347       else
2348         for (int ReuseIdx : ReuseShuffleIndices)
2349           dbgs() << ReuseIdx << ", ";
2350       dbgs() << "\n";
2351       dbgs() << "ReorderIndices: ";
2352       for (unsigned ReorderIdx : ReorderIndices)
2353         dbgs() << ReorderIdx << ", ";
2354       dbgs() << "\n";
2355       dbgs() << "UserTreeIndices: ";
2356       for (const auto &EInfo : UserTreeIndices)
2357         dbgs() << EInfo << ", ";
2358       dbgs() << "\n";
2359     }
2360 #endif
2361   };
2362 
2363 #ifndef NDEBUG
2364   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2365                      InstructionCost VecCost,
2366                      InstructionCost ScalarCost) const {
2367     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2368     dbgs() << "SLP: Costs:\n";
2369     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2370     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2371     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2372     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2373                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2374   }
2375 #endif
2376 
2377   /// Create a new VectorizableTree entry.
2378   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2379                           const InstructionsState &S,
2380                           const EdgeInfo &UserTreeIdx,
2381                           ArrayRef<int> ReuseShuffleIndices = None,
2382                           ArrayRef<unsigned> ReorderIndices = None) {
2383     TreeEntry::EntryState EntryState =
2384         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2385     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2386                         ReuseShuffleIndices, ReorderIndices);
2387   }
2388 
2389   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2390                           TreeEntry::EntryState EntryState,
2391                           Optional<ScheduleData *> Bundle,
2392                           const InstructionsState &S,
2393                           const EdgeInfo &UserTreeIdx,
2394                           ArrayRef<int> ReuseShuffleIndices = None,
2395                           ArrayRef<unsigned> ReorderIndices = None) {
2396     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2397             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2398            "Need to vectorize gather entry?");
2399     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2400     TreeEntry *Last = VectorizableTree.back().get();
2401     Last->Idx = VectorizableTree.size() - 1;
2402     Last->State = EntryState;
2403     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2404                                      ReuseShuffleIndices.end());
2405     if (ReorderIndices.empty()) {
2406       Last->Scalars.assign(VL.begin(), VL.end());
2407       Last->setOperations(S);
2408     } else {
2409       // Reorder scalars and build final mask.
2410       Last->Scalars.assign(VL.size(), nullptr);
2411       transform(ReorderIndices, Last->Scalars.begin(),
2412                 [VL](unsigned Idx) -> Value * {
2413                   if (Idx >= VL.size())
2414                     return UndefValue::get(VL.front()->getType());
2415                   return VL[Idx];
2416                 });
2417       InstructionsState S = getSameOpcode(Last->Scalars);
2418       Last->setOperations(S);
2419       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2420     }
2421     if (Last->State != TreeEntry::NeedToGather) {
2422       for (Value *V : VL) {
2423         assert(!getTreeEntry(V) && "Scalar already in tree!");
2424         ScalarToTreeEntry[V] = Last;
2425       }
2426       // Update the scheduler bundle to point to this TreeEntry.
2427       ScheduleData *BundleMember = Bundle.getValue();
2428       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2429               isVectorLikeInstWithConstOps(S.MainOp) ||
2430               doesNotNeedToSchedule(VL)) &&
2431              "Bundle and VL out of sync");
2432       if (BundleMember) {
2433         for (Value *V : VL) {
2434           if (doesNotNeedToBeScheduled(V))
2435             continue;
2436           assert(BundleMember && "Unexpected end of bundle.");
2437           BundleMember->TE = Last;
2438           BundleMember = BundleMember->NextInBundle;
2439         }
2440       }
2441       assert(!BundleMember && "Bundle and VL out of sync");
2442     } else {
2443       MustGather.insert(VL.begin(), VL.end());
2444     }
2445 
2446     if (UserTreeIdx.UserTE)
2447       Last->UserTreeIndices.push_back(UserTreeIdx);
2448 
2449     return Last;
2450   }
2451 
2452   /// -- Vectorization State --
2453   /// Holds all of the tree entries.
2454   TreeEntry::VecTreeTy VectorizableTree;
2455 
2456 #ifndef NDEBUG
2457   /// Debug printer.
2458   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2459     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2460       VectorizableTree[Id]->dump();
2461       dbgs() << "\n";
2462     }
2463   }
2464 #endif
2465 
2466   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2467 
2468   const TreeEntry *getTreeEntry(Value *V) const {
2469     return ScalarToTreeEntry.lookup(V);
2470   }
2471 
2472   /// Maps a specific scalar to its tree entry.
2473   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2474 
2475   /// Maps a value to the proposed vectorizable size.
2476   SmallDenseMap<Value *, unsigned> InstrElementSize;
2477 
2478   /// A list of scalars that we found that we need to keep as scalars.
2479   ValueSet MustGather;
2480 
2481   /// This POD struct describes one external user in the vectorized tree.
2482   struct ExternalUser {
2483     ExternalUser(Value *S, llvm::User *U, int L)
2484         : Scalar(S), User(U), Lane(L) {}
2485 
2486     // Which scalar in our function.
2487     Value *Scalar;
2488 
2489     // Which user that uses the scalar.
2490     llvm::User *User;
2491 
2492     // Which lane does the scalar belong to.
2493     int Lane;
2494   };
2495   using UserList = SmallVector<ExternalUser, 16>;
2496 
2497   /// Checks if two instructions may access the same memory.
2498   ///
2499   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2500   /// is invariant in the calling loop.
2501   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2502                  Instruction *Inst2) {
2503     // First check if the result is already in the cache.
2504     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2505     Optional<bool> &result = AliasCache[key];
2506     if (result.hasValue()) {
2507       return result.getValue();
2508     }
2509     bool aliased = true;
2510     if (Loc1.Ptr && isSimple(Inst1))
2511       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2512     // Store the result in the cache.
2513     result = aliased;
2514     return aliased;
2515   }
2516 
2517   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2518 
2519   /// Cache for alias results.
2520   /// TODO: consider moving this to the AliasAnalysis itself.
2521   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2522 
2523   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2524   // globally through SLP because we don't perform any action which
2525   // invalidates capture results.
2526   BatchAAResults BatchAA;
2527 
2528   /// Temporary store for deleted instructions. Instructions will be deleted
2529   /// eventually when the BoUpSLP is destructed.  The deferral is required to
2530   /// ensure that there are no incorrect collisions in the AliasCache, which
2531   /// can happen if a new instruction is allocated at the same address as a
2532   /// previously deleted instruction.
2533   DenseSet<Instruction *> DeletedInstructions;
2534 
2535   /// A list of values that need to extracted out of the tree.
2536   /// This list holds pairs of (Internal Scalar : External User). External User
2537   /// can be nullptr, it means that this Internal Scalar will be used later,
2538   /// after vectorization.
2539   UserList ExternalUses;
2540 
2541   /// Values used only by @llvm.assume calls.
2542   SmallPtrSet<const Value *, 32> EphValues;
2543 
2544   /// Holds all of the instructions that we gathered.
2545   SetVector<Instruction *> GatherShuffleSeq;
2546 
2547   /// A list of blocks that we are going to CSE.
2548   SetVector<BasicBlock *> CSEBlocks;
2549 
2550   /// Contains all scheduling relevant data for an instruction.
2551   /// A ScheduleData either represents a single instruction or a member of an
2552   /// instruction bundle (= a group of instructions which is combined into a
2553   /// vector instruction).
2554   struct ScheduleData {
2555     // The initial value for the dependency counters. It means that the
2556     // dependencies are not calculated yet.
2557     enum { InvalidDeps = -1 };
2558 
2559     ScheduleData() = default;
2560 
2561     void init(int BlockSchedulingRegionID, Value *OpVal) {
2562       FirstInBundle = this;
2563       NextInBundle = nullptr;
2564       NextLoadStore = nullptr;
2565       IsScheduled = false;
2566       SchedulingRegionID = BlockSchedulingRegionID;
2567       clearDependencies();
2568       OpValue = OpVal;
2569       TE = nullptr;
2570     }
2571 
2572     /// Verify basic self consistency properties
2573     void verify() {
2574       if (hasValidDependencies()) {
2575         assert(UnscheduledDeps <= Dependencies && "invariant");
2576       } else {
2577         assert(UnscheduledDeps == Dependencies && "invariant");
2578       }
2579 
2580       if (IsScheduled) {
2581         assert(isSchedulingEntity() &&
2582                 "unexpected scheduled state");
2583         for (const ScheduleData *BundleMember = this; BundleMember;
2584              BundleMember = BundleMember->NextInBundle) {
2585           assert(BundleMember->hasValidDependencies() &&
2586                  BundleMember->UnscheduledDeps == 0 &&
2587                  "unexpected scheduled state");
2588           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2589                  "only bundle is marked scheduled");
2590         }
2591       }
2592 
2593       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2594              "all bundle members must be in same basic block");
2595     }
2596 
2597     /// Returns true if the dependency information has been calculated.
2598     /// Note that depenendency validity can vary between instructions within
2599     /// a single bundle.
2600     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2601 
2602     /// Returns true for single instructions and for bundle representatives
2603     /// (= the head of a bundle).
2604     bool isSchedulingEntity() const { return FirstInBundle == this; }
2605 
2606     /// Returns true if it represents an instruction bundle and not only a
2607     /// single instruction.
2608     bool isPartOfBundle() const {
2609       return NextInBundle != nullptr || FirstInBundle != this || TE;
2610     }
2611 
2612     /// Returns true if it is ready for scheduling, i.e. it has no more
2613     /// unscheduled depending instructions/bundles.
2614     bool isReady() const {
2615       assert(isSchedulingEntity() &&
2616              "can't consider non-scheduling entity for ready list");
2617       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2618     }
2619 
2620     /// Modifies the number of unscheduled dependencies for this instruction,
2621     /// and returns the number of remaining dependencies for the containing
2622     /// bundle.
2623     int incrementUnscheduledDeps(int Incr) {
2624       assert(hasValidDependencies() &&
2625              "increment of unscheduled deps would be meaningless");
2626       UnscheduledDeps += Incr;
2627       return FirstInBundle->unscheduledDepsInBundle();
2628     }
2629 
2630     /// Sets the number of unscheduled dependencies to the number of
2631     /// dependencies.
2632     void resetUnscheduledDeps() {
2633       UnscheduledDeps = Dependencies;
2634     }
2635 
2636     /// Clears all dependency information.
2637     void clearDependencies() {
2638       Dependencies = InvalidDeps;
2639       resetUnscheduledDeps();
2640       MemoryDependencies.clear();
2641       ControlDependencies.clear();
2642     }
2643 
2644     int unscheduledDepsInBundle() const {
2645       assert(isSchedulingEntity() && "only meaningful on the bundle");
2646       int Sum = 0;
2647       for (const ScheduleData *BundleMember = this; BundleMember;
2648            BundleMember = BundleMember->NextInBundle) {
2649         if (BundleMember->UnscheduledDeps == InvalidDeps)
2650           return InvalidDeps;
2651         Sum += BundleMember->UnscheduledDeps;
2652       }
2653       return Sum;
2654     }
2655 
2656     void dump(raw_ostream &os) const {
2657       if (!isSchedulingEntity()) {
2658         os << "/ " << *Inst;
2659       } else if (NextInBundle) {
2660         os << '[' << *Inst;
2661         ScheduleData *SD = NextInBundle;
2662         while (SD) {
2663           os << ';' << *SD->Inst;
2664           SD = SD->NextInBundle;
2665         }
2666         os << ']';
2667       } else {
2668         os << *Inst;
2669       }
2670     }
2671 
2672     Instruction *Inst = nullptr;
2673 
2674     /// Opcode of the current instruction in the schedule data.
2675     Value *OpValue = nullptr;
2676 
2677     /// The TreeEntry that this instruction corresponds to.
2678     TreeEntry *TE = nullptr;
2679 
2680     /// Points to the head in an instruction bundle (and always to this for
2681     /// single instructions).
2682     ScheduleData *FirstInBundle = nullptr;
2683 
2684     /// Single linked list of all instructions in a bundle. Null if it is a
2685     /// single instruction.
2686     ScheduleData *NextInBundle = nullptr;
2687 
2688     /// Single linked list of all memory instructions (e.g. load, store, call)
2689     /// in the block - until the end of the scheduling region.
2690     ScheduleData *NextLoadStore = nullptr;
2691 
2692     /// The dependent memory instructions.
2693     /// This list is derived on demand in calculateDependencies().
2694     SmallVector<ScheduleData *, 4> MemoryDependencies;
2695 
2696     /// List of instructions which this instruction could be control dependent
2697     /// on.  Allowing such nodes to be scheduled below this one could introduce
2698     /// a runtime fault which didn't exist in the original program.
2699     /// ex: this is a load or udiv following a readonly call which inf loops
2700     SmallVector<ScheduleData *, 4> ControlDependencies;
2701 
2702     /// This ScheduleData is in the current scheduling region if this matches
2703     /// the current SchedulingRegionID of BlockScheduling.
2704     int SchedulingRegionID = 0;
2705 
2706     /// Used for getting a "good" final ordering of instructions.
2707     int SchedulingPriority = 0;
2708 
2709     /// The number of dependencies. Constitutes of the number of users of the
2710     /// instruction plus the number of dependent memory instructions (if any).
2711     /// This value is calculated on demand.
2712     /// If InvalidDeps, the number of dependencies is not calculated yet.
2713     int Dependencies = InvalidDeps;
2714 
2715     /// The number of dependencies minus the number of dependencies of scheduled
2716     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2717     /// for scheduling.
2718     /// Note that this is negative as long as Dependencies is not calculated.
2719     int UnscheduledDeps = InvalidDeps;
2720 
2721     /// True if this instruction is scheduled (or considered as scheduled in the
2722     /// dry-run).
2723     bool IsScheduled = false;
2724   };
2725 
2726 #ifndef NDEBUG
2727   friend inline raw_ostream &operator<<(raw_ostream &os,
2728                                         const BoUpSLP::ScheduleData &SD) {
2729     SD.dump(os);
2730     return os;
2731   }
2732 #endif
2733 
2734   friend struct GraphTraits<BoUpSLP *>;
2735   friend struct DOTGraphTraits<BoUpSLP *>;
2736 
2737   /// Contains all scheduling data for a basic block.
2738   /// It does not schedules instructions, which are not memory read/write
2739   /// instructions and their operands are either constants, or arguments, or
2740   /// phis, or instructions from others blocks, or their users are phis or from
2741   /// the other blocks. The resulting vector instructions can be placed at the
2742   /// beginning of the basic block without scheduling (if operands does not need
2743   /// to be scheduled) or at the end of the block (if users are outside of the
2744   /// block). It allows to save some compile time and memory used by the
2745   /// compiler.
2746   /// ScheduleData is assigned for each instruction in between the boundaries of
2747   /// the tree entry, even for those, which are not part of the graph. It is
2748   /// required to correctly follow the dependencies between the instructions and
2749   /// their correct scheduling. The ScheduleData is not allocated for the
2750   /// instructions, which do not require scheduling, like phis, nodes with
2751   /// extractelements/insertelements only or nodes with instructions, with
2752   /// uses/operands outside of the block.
2753   struct BlockScheduling {
2754     BlockScheduling(BasicBlock *BB)
2755         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2756 
2757     void clear() {
2758       ReadyInsts.clear();
2759       ScheduleStart = nullptr;
2760       ScheduleEnd = nullptr;
2761       FirstLoadStoreInRegion = nullptr;
2762       LastLoadStoreInRegion = nullptr;
2763       RegionHasStackSave = false;
2764 
2765       // Reduce the maximum schedule region size by the size of the
2766       // previous scheduling run.
2767       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2768       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2769         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2770       ScheduleRegionSize = 0;
2771 
2772       // Make a new scheduling region, i.e. all existing ScheduleData is not
2773       // in the new region yet.
2774       ++SchedulingRegionID;
2775     }
2776 
2777     ScheduleData *getScheduleData(Instruction *I) {
2778       if (BB != I->getParent())
2779         // Avoid lookup if can't possibly be in map.
2780         return nullptr;
2781       ScheduleData *SD = ScheduleDataMap.lookup(I);
2782       if (SD && isInSchedulingRegion(SD))
2783         return SD;
2784       return nullptr;
2785     }
2786 
2787     ScheduleData *getScheduleData(Value *V) {
2788       if (auto *I = dyn_cast<Instruction>(V))
2789         return getScheduleData(I);
2790       return nullptr;
2791     }
2792 
2793     ScheduleData *getScheduleData(Value *V, Value *Key) {
2794       if (V == Key)
2795         return getScheduleData(V);
2796       auto I = ExtraScheduleDataMap.find(V);
2797       if (I != ExtraScheduleDataMap.end()) {
2798         ScheduleData *SD = I->second.lookup(Key);
2799         if (SD && isInSchedulingRegion(SD))
2800           return SD;
2801       }
2802       return nullptr;
2803     }
2804 
2805     bool isInSchedulingRegion(ScheduleData *SD) const {
2806       return SD->SchedulingRegionID == SchedulingRegionID;
2807     }
2808 
2809     /// Marks an instruction as scheduled and puts all dependent ready
2810     /// instructions into the ready-list.
2811     template <typename ReadyListType>
2812     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2813       SD->IsScheduled = true;
2814       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2815 
2816       for (ScheduleData *BundleMember = SD; BundleMember;
2817            BundleMember = BundleMember->NextInBundle) {
2818         if (BundleMember->Inst != BundleMember->OpValue)
2819           continue;
2820 
2821         // Handle the def-use chain dependencies.
2822 
2823         // Decrement the unscheduled counter and insert to ready list if ready.
2824         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2825           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2826             if (OpDef && OpDef->hasValidDependencies() &&
2827                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2828               // There are no more unscheduled dependencies after
2829               // decrementing, so we can put the dependent instruction
2830               // into the ready list.
2831               ScheduleData *DepBundle = OpDef->FirstInBundle;
2832               assert(!DepBundle->IsScheduled &&
2833                      "already scheduled bundle gets ready");
2834               ReadyList.insert(DepBundle);
2835               LLVM_DEBUG(dbgs()
2836                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2837             }
2838           });
2839         };
2840 
2841         // If BundleMember is a vector bundle, its operands may have been
2842         // reordered during buildTree(). We therefore need to get its operands
2843         // through the TreeEntry.
2844         if (TreeEntry *TE = BundleMember->TE) {
2845           // Need to search for the lane since the tree entry can be reordered.
2846           int Lane = std::distance(TE->Scalars.begin(),
2847                                    find(TE->Scalars, BundleMember->Inst));
2848           assert(Lane >= 0 && "Lane not set");
2849 
2850           // Since vectorization tree is being built recursively this assertion
2851           // ensures that the tree entry has all operands set before reaching
2852           // this code. Couple of exceptions known at the moment are extracts
2853           // where their second (immediate) operand is not added. Since
2854           // immediates do not affect scheduler behavior this is considered
2855           // okay.
2856           auto *In = BundleMember->Inst;
2857           assert(In &&
2858                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2859                   In->getNumOperands() == TE->getNumOperands()) &&
2860                  "Missed TreeEntry operands?");
2861           (void)In; // fake use to avoid build failure when assertions disabled
2862 
2863           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2864                OpIdx != NumOperands; ++OpIdx)
2865             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2866               DecrUnsched(I);
2867         } else {
2868           // If BundleMember is a stand-alone instruction, no operand reordering
2869           // has taken place, so we directly access its operands.
2870           for (Use &U : BundleMember->Inst->operands())
2871             if (auto *I = dyn_cast<Instruction>(U.get()))
2872               DecrUnsched(I);
2873         }
2874         // Handle the memory dependencies.
2875         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2876           if (MemoryDepSD->hasValidDependencies() &&
2877               MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2878             // There are no more unscheduled dependencies after decrementing,
2879             // so we can put the dependent instruction into the ready list.
2880             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2881             assert(!DepBundle->IsScheduled &&
2882                    "already scheduled bundle gets ready");
2883             ReadyList.insert(DepBundle);
2884             LLVM_DEBUG(dbgs()
2885                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2886           }
2887         }
2888         // Handle the control dependencies.
2889         for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
2890           if (DepSD->incrementUnscheduledDeps(-1) == 0) {
2891             // There are no more unscheduled dependencies after decrementing,
2892             // so we can put the dependent instruction into the ready list.
2893             ScheduleData *DepBundle = DepSD->FirstInBundle;
2894             assert(!DepBundle->IsScheduled &&
2895                    "already scheduled bundle gets ready");
2896             ReadyList.insert(DepBundle);
2897             LLVM_DEBUG(dbgs()
2898                        << "SLP:    gets ready (ctl): " << *DepBundle << "\n");
2899           }
2900         }
2901 
2902       }
2903     }
2904 
2905     /// Verify basic self consistency properties of the data structure.
2906     void verify() {
2907       if (!ScheduleStart)
2908         return;
2909 
2910       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2911              ScheduleStart->comesBefore(ScheduleEnd) &&
2912              "Not a valid scheduling region?");
2913 
2914       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2915         auto *SD = getScheduleData(I);
2916         if (!SD)
2917           continue;
2918         assert(isInSchedulingRegion(SD) &&
2919                "primary schedule data not in window?");
2920         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2921                "entire bundle in window!");
2922         (void)SD;
2923         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2924       }
2925 
2926       for (auto *SD : ReadyInsts) {
2927         assert(SD->isSchedulingEntity() && SD->isReady() &&
2928                "item in ready list not ready?");
2929         (void)SD;
2930       }
2931     }
2932 
2933     void doForAllOpcodes(Value *V,
2934                          function_ref<void(ScheduleData *SD)> Action) {
2935       if (ScheduleData *SD = getScheduleData(V))
2936         Action(SD);
2937       auto I = ExtraScheduleDataMap.find(V);
2938       if (I != ExtraScheduleDataMap.end())
2939         for (auto &P : I->second)
2940           if (isInSchedulingRegion(P.second))
2941             Action(P.second);
2942     }
2943 
2944     /// Put all instructions into the ReadyList which are ready for scheduling.
2945     template <typename ReadyListType>
2946     void initialFillReadyList(ReadyListType &ReadyList) {
2947       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2948         doForAllOpcodes(I, [&](ScheduleData *SD) {
2949           if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
2950               SD->isReady()) {
2951             ReadyList.insert(SD);
2952             LLVM_DEBUG(dbgs()
2953                        << "SLP:    initially in ready list: " << *SD << "\n");
2954           }
2955         });
2956       }
2957     }
2958 
2959     /// Build a bundle from the ScheduleData nodes corresponding to the
2960     /// scalar instruction for each lane.
2961     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2962 
2963     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2964     /// cyclic dependencies. This is only a dry-run, no instructions are
2965     /// actually moved at this stage.
2966     /// \returns the scheduling bundle. The returned Optional value is non-None
2967     /// if \p VL is allowed to be scheduled.
2968     Optional<ScheduleData *>
2969     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2970                       const InstructionsState &S);
2971 
2972     /// Un-bundles a group of instructions.
2973     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2974 
2975     /// Allocates schedule data chunk.
2976     ScheduleData *allocateScheduleDataChunks();
2977 
2978     /// Extends the scheduling region so that V is inside the region.
2979     /// \returns true if the region size is within the limit.
2980     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2981 
2982     /// Initialize the ScheduleData structures for new instructions in the
2983     /// scheduling region.
2984     void initScheduleData(Instruction *FromI, Instruction *ToI,
2985                           ScheduleData *PrevLoadStore,
2986                           ScheduleData *NextLoadStore);
2987 
2988     /// Updates the dependency information of a bundle and of all instructions/
2989     /// bundles which depend on the original bundle.
2990     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2991                                BoUpSLP *SLP);
2992 
2993     /// Sets all instruction in the scheduling region to un-scheduled.
2994     void resetSchedule();
2995 
2996     BasicBlock *BB;
2997 
2998     /// Simple memory allocation for ScheduleData.
2999     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3000 
3001     /// The size of a ScheduleData array in ScheduleDataChunks.
3002     int ChunkSize;
3003 
3004     /// The allocator position in the current chunk, which is the last entry
3005     /// of ScheduleDataChunks.
3006     int ChunkPos;
3007 
3008     /// Attaches ScheduleData to Instruction.
3009     /// Note that the mapping survives during all vectorization iterations, i.e.
3010     /// ScheduleData structures are recycled.
3011     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
3012 
3013     /// Attaches ScheduleData to Instruction with the leading key.
3014     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
3015         ExtraScheduleDataMap;
3016 
3017     /// The ready-list for scheduling (only used for the dry-run).
3018     SetVector<ScheduleData *> ReadyInsts;
3019 
3020     /// The first instruction of the scheduling region.
3021     Instruction *ScheduleStart = nullptr;
3022 
3023     /// The first instruction _after_ the scheduling region.
3024     Instruction *ScheduleEnd = nullptr;
3025 
3026     /// The first memory accessing instruction in the scheduling region
3027     /// (can be null).
3028     ScheduleData *FirstLoadStoreInRegion = nullptr;
3029 
3030     /// The last memory accessing instruction in the scheduling region
3031     /// (can be null).
3032     ScheduleData *LastLoadStoreInRegion = nullptr;
3033 
3034     /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3035     /// region?  Used to optimize the dependence calculation for the
3036     /// common case where there isn't.
3037     bool RegionHasStackSave = false;
3038 
3039     /// The current size of the scheduling region.
3040     int ScheduleRegionSize = 0;
3041 
3042     /// The maximum size allowed for the scheduling region.
3043     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3044 
3045     /// The ID of the scheduling region. For a new vectorization iteration this
3046     /// is incremented which "removes" all ScheduleData from the region.
3047     /// Make sure that the initial SchedulingRegionID is greater than the
3048     /// initial SchedulingRegionID in ScheduleData (which is 0).
3049     int SchedulingRegionID = 1;
3050   };
3051 
3052   /// Attaches the BlockScheduling structures to basic blocks.
3053   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3054 
3055   /// Performs the "real" scheduling. Done before vectorization is actually
3056   /// performed in a basic block.
3057   void scheduleBlock(BlockScheduling *BS);
3058 
3059   /// List of users to ignore during scheduling and that don't need extracting.
3060   ArrayRef<Value *> UserIgnoreList;
3061 
3062   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3063   /// sorted SmallVectors of unsigned.
3064   struct OrdersTypeDenseMapInfo {
3065     static OrdersType getEmptyKey() {
3066       OrdersType V;
3067       V.push_back(~1U);
3068       return V;
3069     }
3070 
3071     static OrdersType getTombstoneKey() {
3072       OrdersType V;
3073       V.push_back(~2U);
3074       return V;
3075     }
3076 
3077     static unsigned getHashValue(const OrdersType &V) {
3078       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3079     }
3080 
3081     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3082       return LHS == RHS;
3083     }
3084   };
3085 
3086   // Analysis and block reference.
3087   Function *F;
3088   ScalarEvolution *SE;
3089   TargetTransformInfo *TTI;
3090   TargetLibraryInfo *TLI;
3091   LoopInfo *LI;
3092   DominatorTree *DT;
3093   AssumptionCache *AC;
3094   DemandedBits *DB;
3095   const DataLayout *DL;
3096   OptimizationRemarkEmitter *ORE;
3097 
3098   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3099   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3100 
3101   /// Instruction builder to construct the vectorized tree.
3102   IRBuilder<> Builder;
3103 
3104   /// A map of scalar integer values to the smallest bit width with which they
3105   /// can legally be represented. The values map to (width, signed) pairs,
3106   /// where "width" indicates the minimum bit width and "signed" is True if the
3107   /// value must be signed-extended, rather than zero-extended, back to its
3108   /// original width.
3109   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3110 };
3111 
3112 } // end namespace slpvectorizer
3113 
3114 template <> struct GraphTraits<BoUpSLP *> {
3115   using TreeEntry = BoUpSLP::TreeEntry;
3116 
3117   /// NodeRef has to be a pointer per the GraphWriter.
3118   using NodeRef = TreeEntry *;
3119 
3120   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3121 
3122   /// Add the VectorizableTree to the index iterator to be able to return
3123   /// TreeEntry pointers.
3124   struct ChildIteratorType
3125       : public iterator_adaptor_base<
3126             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3127     ContainerTy &VectorizableTree;
3128 
3129     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3130                       ContainerTy &VT)
3131         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3132 
3133     NodeRef operator*() { return I->UserTE; }
3134   };
3135 
3136   static NodeRef getEntryNode(BoUpSLP &R) {
3137     return R.VectorizableTree[0].get();
3138   }
3139 
3140   static ChildIteratorType child_begin(NodeRef N) {
3141     return {N->UserTreeIndices.begin(), N->Container};
3142   }
3143 
3144   static ChildIteratorType child_end(NodeRef N) {
3145     return {N->UserTreeIndices.end(), N->Container};
3146   }
3147 
3148   /// For the node iterator we just need to turn the TreeEntry iterator into a
3149   /// TreeEntry* iterator so that it dereferences to NodeRef.
3150   class nodes_iterator {
3151     using ItTy = ContainerTy::iterator;
3152     ItTy It;
3153 
3154   public:
3155     nodes_iterator(const ItTy &It2) : It(It2) {}
3156     NodeRef operator*() { return It->get(); }
3157     nodes_iterator operator++() {
3158       ++It;
3159       return *this;
3160     }
3161     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3162   };
3163 
3164   static nodes_iterator nodes_begin(BoUpSLP *R) {
3165     return nodes_iterator(R->VectorizableTree.begin());
3166   }
3167 
3168   static nodes_iterator nodes_end(BoUpSLP *R) {
3169     return nodes_iterator(R->VectorizableTree.end());
3170   }
3171 
3172   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3173 };
3174 
3175 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3176   using TreeEntry = BoUpSLP::TreeEntry;
3177 
3178   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3179 
3180   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3181     std::string Str;
3182     raw_string_ostream OS(Str);
3183     if (isSplat(Entry->Scalars))
3184       OS << "<splat> ";
3185     for (auto V : Entry->Scalars) {
3186       OS << *V;
3187       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3188             return EU.Scalar == V;
3189           }))
3190         OS << " <extract>";
3191       OS << "\n";
3192     }
3193     return Str;
3194   }
3195 
3196   static std::string getNodeAttributes(const TreeEntry *Entry,
3197                                        const BoUpSLP *) {
3198     if (Entry->State == TreeEntry::NeedToGather)
3199       return "color=red";
3200     return "";
3201   }
3202 };
3203 
3204 } // end namespace llvm
3205 
3206 BoUpSLP::~BoUpSLP() {
3207   for (auto *I : DeletedInstructions)
3208     I->dropAllReferences();
3209   for (auto *I : DeletedInstructions) {
3210     assert(I->use_empty() &&
3211            "trying to erase instruction with users.");
3212     I->eraseFromParent();
3213   }
3214 #ifdef EXPENSIVE_CHECKS
3215   // If we could guarantee that this call is not extremely slow, we could
3216   // remove the ifdef limitation (see PR47712).
3217   assert(!verifyFunction(*F, &dbgs()));
3218 #endif
3219 }
3220 
3221 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3222 /// contains original mask for the scalars reused in the node. Procedure
3223 /// transform this mask in accordance with the given \p Mask.
3224 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3225   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3226          "Expected non-empty mask.");
3227   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3228   Prev.swap(Reuses);
3229   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3230     if (Mask[I] != UndefMaskElem)
3231       Reuses[Mask[I]] = Prev[I];
3232 }
3233 
3234 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3235 /// the original order of the scalars. Procedure transforms the provided order
3236 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3237 /// identity order, \p Order is cleared.
3238 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3239   assert(!Mask.empty() && "Expected non-empty mask.");
3240   SmallVector<int> MaskOrder;
3241   if (Order.empty()) {
3242     MaskOrder.resize(Mask.size());
3243     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3244   } else {
3245     inversePermutation(Order, MaskOrder);
3246   }
3247   reorderReuses(MaskOrder, Mask);
3248   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3249     Order.clear();
3250     return;
3251   }
3252   Order.assign(Mask.size(), Mask.size());
3253   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3254     if (MaskOrder[I] != UndefMaskElem)
3255       Order[MaskOrder[I]] = I;
3256   fixupOrderingIndices(Order);
3257 }
3258 
3259 Optional<BoUpSLP::OrdersType>
3260 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3261   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3262   unsigned NumScalars = TE.Scalars.size();
3263   OrdersType CurrentOrder(NumScalars, NumScalars);
3264   SmallVector<int> Positions;
3265   SmallBitVector UsedPositions(NumScalars);
3266   const TreeEntry *STE = nullptr;
3267   // Try to find all gathered scalars that are gets vectorized in other
3268   // vectorize node. Here we can have only one single tree vector node to
3269   // correctly identify order of the gathered scalars.
3270   for (unsigned I = 0; I < NumScalars; ++I) {
3271     Value *V = TE.Scalars[I];
3272     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3273       continue;
3274     if (const auto *LocalSTE = getTreeEntry(V)) {
3275       if (!STE)
3276         STE = LocalSTE;
3277       else if (STE != LocalSTE)
3278         // Take the order only from the single vector node.
3279         return None;
3280       unsigned Lane =
3281           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3282       if (Lane >= NumScalars)
3283         return None;
3284       if (CurrentOrder[Lane] != NumScalars) {
3285         if (Lane != I)
3286           continue;
3287         UsedPositions.reset(CurrentOrder[Lane]);
3288       }
3289       // The partial identity (where only some elements of the gather node are
3290       // in the identity order) is good.
3291       CurrentOrder[Lane] = I;
3292       UsedPositions.set(I);
3293     }
3294   }
3295   // Need to keep the order if we have a vector entry and at least 2 scalars or
3296   // the vectorized entry has just 2 scalars.
3297   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3298     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3299       for (unsigned I = 0; I < NumScalars; ++I)
3300         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3301           return false;
3302       return true;
3303     };
3304     if (IsIdentityOrder(CurrentOrder)) {
3305       CurrentOrder.clear();
3306       return CurrentOrder;
3307     }
3308     auto *It = CurrentOrder.begin();
3309     for (unsigned I = 0; I < NumScalars;) {
3310       if (UsedPositions.test(I)) {
3311         ++I;
3312         continue;
3313       }
3314       if (*It == NumScalars) {
3315         *It = I;
3316         ++I;
3317       }
3318       ++It;
3319     }
3320     return CurrentOrder;
3321   }
3322   return None;
3323 }
3324 
3325 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3326                                                          bool TopToBottom) {
3327   // No need to reorder if need to shuffle reuses, still need to shuffle the
3328   // node.
3329   if (!TE.ReuseShuffleIndices.empty())
3330     return None;
3331   if (TE.State == TreeEntry::Vectorize &&
3332       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3333        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3334       !TE.isAltShuffle())
3335     return TE.ReorderIndices;
3336   if (TE.State == TreeEntry::NeedToGather) {
3337     // TODO: add analysis of other gather nodes with extractelement
3338     // instructions and other values/instructions, not only undefs.
3339     if (((TE.getOpcode() == Instruction::ExtractElement &&
3340           !TE.isAltShuffle()) ||
3341          (all_of(TE.Scalars,
3342                  [](Value *V) {
3343                    return isa<UndefValue, ExtractElementInst>(V);
3344                  }) &&
3345           any_of(TE.Scalars,
3346                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3347         all_of(TE.Scalars,
3348                [](Value *V) {
3349                  auto *EE = dyn_cast<ExtractElementInst>(V);
3350                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3351                }) &&
3352         allSameType(TE.Scalars)) {
3353       // Check that gather of extractelements can be represented as
3354       // just a shuffle of a single vector.
3355       OrdersType CurrentOrder;
3356       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3357       if (Reuse || !CurrentOrder.empty()) {
3358         if (!CurrentOrder.empty())
3359           fixupOrderingIndices(CurrentOrder);
3360         return CurrentOrder;
3361       }
3362     }
3363     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3364       return CurrentOrder;
3365   }
3366   return None;
3367 }
3368 
3369 void BoUpSLP::reorderTopToBottom() {
3370   // Maps VF to the graph nodes.
3371   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3372   // ExtractElement gather nodes which can be vectorized and need to handle
3373   // their ordering.
3374   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3375   // Find all reorderable nodes with the given VF.
3376   // Currently the are vectorized stores,loads,extracts + some gathering of
3377   // extracts.
3378   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3379                                  const std::unique_ptr<TreeEntry> &TE) {
3380     if (Optional<OrdersType> CurrentOrder =
3381             getReorderingData(*TE, /*TopToBottom=*/true)) {
3382       // Do not include ordering for nodes used in the alt opcode vectorization,
3383       // better to reorder them during bottom-to-top stage. If follow the order
3384       // here, it causes reordering of the whole graph though actually it is
3385       // profitable just to reorder the subgraph that starts from the alternate
3386       // opcode vectorization node. Such nodes already end-up with the shuffle
3387       // instruction and it is just enough to change this shuffle rather than
3388       // rotate the scalars for the whole graph.
3389       unsigned Cnt = 0;
3390       const TreeEntry *UserTE = TE.get();
3391       while (UserTE && Cnt < RecursionMaxDepth) {
3392         if (UserTE->UserTreeIndices.size() != 1)
3393           break;
3394         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3395               return EI.UserTE->State == TreeEntry::Vectorize &&
3396                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3397             }))
3398           return;
3399         if (UserTE->UserTreeIndices.empty())
3400           UserTE = nullptr;
3401         else
3402           UserTE = UserTE->UserTreeIndices.back().UserTE;
3403         ++Cnt;
3404       }
3405       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3406       if (TE->State != TreeEntry::Vectorize)
3407         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3408     }
3409   });
3410 
3411   // Reorder the graph nodes according to their vectorization factor.
3412   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3413        VF /= 2) {
3414     auto It = VFToOrderedEntries.find(VF);
3415     if (It == VFToOrderedEntries.end())
3416       continue;
3417     // Try to find the most profitable order. We just are looking for the most
3418     // used order and reorder scalar elements in the nodes according to this
3419     // mostly used order.
3420     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3421     // All operands are reordered and used only in this node - propagate the
3422     // most used order to the user node.
3423     MapVector<OrdersType, unsigned,
3424               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3425         OrdersUses;
3426     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3427     for (const TreeEntry *OpTE : OrderedEntries) {
3428       // No need to reorder this nodes, still need to extend and to use shuffle,
3429       // just need to merge reordering shuffle and the reuse shuffle.
3430       if (!OpTE->ReuseShuffleIndices.empty())
3431         continue;
3432       // Count number of orders uses.
3433       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3434         if (OpTE->State == TreeEntry::NeedToGather)
3435           return GathersToOrders.find(OpTE)->second;
3436         return OpTE->ReorderIndices;
3437       }();
3438       // Stores actually store the mask, not the order, need to invert.
3439       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3440           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3441         SmallVector<int> Mask;
3442         inversePermutation(Order, Mask);
3443         unsigned E = Order.size();
3444         OrdersType CurrentOrder(E, E);
3445         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3446           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3447         });
3448         fixupOrderingIndices(CurrentOrder);
3449         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3450       } else {
3451         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3452       }
3453     }
3454     // Set order of the user node.
3455     if (OrdersUses.empty())
3456       continue;
3457     // Choose the most used order.
3458     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3459     unsigned Cnt = OrdersUses.front().second;
3460     for (const auto &Pair : drop_begin(OrdersUses)) {
3461       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3462         BestOrder = Pair.first;
3463         Cnt = Pair.second;
3464       }
3465     }
3466     // Set order of the user node.
3467     if (BestOrder.empty())
3468       continue;
3469     SmallVector<int> Mask;
3470     inversePermutation(BestOrder, Mask);
3471     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3472     unsigned E = BestOrder.size();
3473     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3474       return I < E ? static_cast<int>(I) : UndefMaskElem;
3475     });
3476     // Do an actual reordering, if profitable.
3477     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3478       // Just do the reordering for the nodes with the given VF.
3479       if (TE->Scalars.size() != VF) {
3480         if (TE->ReuseShuffleIndices.size() == VF) {
3481           // Need to reorder the reuses masks of the operands with smaller VF to
3482           // be able to find the match between the graph nodes and scalar
3483           // operands of the given node during vectorization/cost estimation.
3484           assert(all_of(TE->UserTreeIndices,
3485                         [VF, &TE](const EdgeInfo &EI) {
3486                           return EI.UserTE->Scalars.size() == VF ||
3487                                  EI.UserTE->Scalars.size() ==
3488                                      TE->Scalars.size();
3489                         }) &&
3490                  "All users must be of VF size.");
3491           // Update ordering of the operands with the smaller VF than the given
3492           // one.
3493           reorderReuses(TE->ReuseShuffleIndices, Mask);
3494         }
3495         continue;
3496       }
3497       if (TE->State == TreeEntry::Vectorize &&
3498           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3499               InsertElementInst>(TE->getMainOp()) &&
3500           !TE->isAltShuffle()) {
3501         // Build correct orders for extract{element,value}, loads and
3502         // stores.
3503         reorderOrder(TE->ReorderIndices, Mask);
3504         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3505           TE->reorderOperands(Mask);
3506       } else {
3507         // Reorder the node and its operands.
3508         TE->reorderOperands(Mask);
3509         assert(TE->ReorderIndices.empty() &&
3510                "Expected empty reorder sequence.");
3511         reorderScalars(TE->Scalars, Mask);
3512       }
3513       if (!TE->ReuseShuffleIndices.empty()) {
3514         // Apply reversed order to keep the original ordering of the reused
3515         // elements to avoid extra reorder indices shuffling.
3516         OrdersType CurrentOrder;
3517         reorderOrder(CurrentOrder, MaskOrder);
3518         SmallVector<int> NewReuses;
3519         inversePermutation(CurrentOrder, NewReuses);
3520         addMask(NewReuses, TE->ReuseShuffleIndices);
3521         TE->ReuseShuffleIndices.swap(NewReuses);
3522       }
3523     }
3524   }
3525 }
3526 
3527 bool BoUpSLP::canReorderOperands(
3528     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3529     ArrayRef<TreeEntry *> ReorderableGathers,
3530     SmallVectorImpl<TreeEntry *> &GatherOps) {
3531   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3532     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3533           return OpData.first == I &&
3534                  OpData.second->State == TreeEntry::Vectorize;
3535         }))
3536       continue;
3537     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3538       // Do not reorder if operand node is used by many user nodes.
3539       if (any_of(TE->UserTreeIndices,
3540                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3541         return false;
3542       // Add the node to the list of the ordered nodes with the identity
3543       // order.
3544       Edges.emplace_back(I, TE);
3545       continue;
3546     }
3547     ArrayRef<Value *> VL = UserTE->getOperand(I);
3548     TreeEntry *Gather = nullptr;
3549     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3550           assert(TE->State != TreeEntry::Vectorize &&
3551                  "Only non-vectorized nodes are expected.");
3552           if (TE->isSame(VL)) {
3553             Gather = TE;
3554             return true;
3555           }
3556           return false;
3557         }) > 1)
3558       return false;
3559     if (Gather)
3560       GatherOps.push_back(Gather);
3561   }
3562   return true;
3563 }
3564 
3565 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3566   SetVector<TreeEntry *> OrderedEntries;
3567   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3568   // Find all reorderable leaf nodes with the given VF.
3569   // Currently the are vectorized loads,extracts without alternate operands +
3570   // some gathering of extracts.
3571   SmallVector<TreeEntry *> NonVectorized;
3572   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3573                               &NonVectorized](
3574                                  const std::unique_ptr<TreeEntry> &TE) {
3575     if (TE->State != TreeEntry::Vectorize)
3576       NonVectorized.push_back(TE.get());
3577     if (Optional<OrdersType> CurrentOrder =
3578             getReorderingData(*TE, /*TopToBottom=*/false)) {
3579       OrderedEntries.insert(TE.get());
3580       if (TE->State != TreeEntry::Vectorize)
3581         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3582     }
3583   });
3584 
3585   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3586   // I.e., if the node has operands, that are reordered, try to make at least
3587   // one operand order in the natural order and reorder others + reorder the
3588   // user node itself.
3589   SmallPtrSet<const TreeEntry *, 4> Visited;
3590   while (!OrderedEntries.empty()) {
3591     // 1. Filter out only reordered nodes.
3592     // 2. If the entry has multiple uses - skip it and jump to the next node.
3593     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3594     SmallVector<TreeEntry *> Filtered;
3595     for (TreeEntry *TE : OrderedEntries) {
3596       if (!(TE->State == TreeEntry::Vectorize ||
3597             (TE->State == TreeEntry::NeedToGather &&
3598              GathersToOrders.count(TE))) ||
3599           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3600           !all_of(drop_begin(TE->UserTreeIndices),
3601                   [TE](const EdgeInfo &EI) {
3602                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3603                   }) ||
3604           !Visited.insert(TE).second) {
3605         Filtered.push_back(TE);
3606         continue;
3607       }
3608       // Build a map between user nodes and their operands order to speedup
3609       // search. The graph currently does not provide this dependency directly.
3610       for (EdgeInfo &EI : TE->UserTreeIndices) {
3611         TreeEntry *UserTE = EI.UserTE;
3612         auto It = Users.find(UserTE);
3613         if (It == Users.end())
3614           It = Users.insert({UserTE, {}}).first;
3615         It->second.emplace_back(EI.EdgeIdx, TE);
3616       }
3617     }
3618     // Erase filtered entries.
3619     for_each(Filtered,
3620              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3621     for (auto &Data : Users) {
3622       // Check that operands are used only in the User node.
3623       SmallVector<TreeEntry *> GatherOps;
3624       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3625                               GatherOps)) {
3626         for_each(Data.second,
3627                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3628                    OrderedEntries.remove(Op.second);
3629                  });
3630         continue;
3631       }
3632       // All operands are reordered and used only in this node - propagate the
3633       // most used order to the user node.
3634       MapVector<OrdersType, unsigned,
3635                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3636           OrdersUses;
3637       // Do the analysis for each tree entry only once, otherwise the order of
3638       // the same node my be considered several times, though might be not
3639       // profitable.
3640       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3641       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3642       for (const auto &Op : Data.second) {
3643         TreeEntry *OpTE = Op.second;
3644         if (!VisitedOps.insert(OpTE).second)
3645           continue;
3646         if (!OpTE->ReuseShuffleIndices.empty() ||
3647             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3648           continue;
3649         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3650           if (OpTE->State == TreeEntry::NeedToGather)
3651             return GathersToOrders.find(OpTE)->second;
3652           return OpTE->ReorderIndices;
3653         }();
3654         unsigned NumOps = count_if(
3655             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3656               return P.second == OpTE;
3657             });
3658         // Stores actually store the mask, not the order, need to invert.
3659         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3660             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3661           SmallVector<int> Mask;
3662           inversePermutation(Order, Mask);
3663           unsigned E = Order.size();
3664           OrdersType CurrentOrder(E, E);
3665           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3666             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3667           });
3668           fixupOrderingIndices(CurrentOrder);
3669           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3670               NumOps;
3671         } else {
3672           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3673         }
3674         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3675         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3676                                             const TreeEntry *TE) {
3677           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3678               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3679               (IgnoreReorder && TE->Idx == 0))
3680             return true;
3681           if (TE->State == TreeEntry::NeedToGather) {
3682             auto It = GathersToOrders.find(TE);
3683             if (It != GathersToOrders.end())
3684               return !It->second.empty();
3685             return true;
3686           }
3687           return false;
3688         };
3689         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3690           TreeEntry *UserTE = EI.UserTE;
3691           if (!VisitedUsers.insert(UserTE).second)
3692             continue;
3693           // May reorder user node if it requires reordering, has reused
3694           // scalars, is an alternate op vectorize node or its op nodes require
3695           // reordering.
3696           if (AllowsReordering(UserTE))
3697             continue;
3698           // Check if users allow reordering.
3699           // Currently look up just 1 level of operands to avoid increase of
3700           // the compile time.
3701           // Profitable to reorder if definitely more operands allow
3702           // reordering rather than those with natural order.
3703           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3704           if (static_cast<unsigned>(count_if(
3705                   Ops, [UserTE, &AllowsReordering](
3706                            const std::pair<unsigned, TreeEntry *> &Op) {
3707                     return AllowsReordering(Op.second) &&
3708                            all_of(Op.second->UserTreeIndices,
3709                                   [UserTE](const EdgeInfo &EI) {
3710                                     return EI.UserTE == UserTE;
3711                                   });
3712                   })) <= Ops.size() / 2)
3713             ++Res.first->second;
3714         }
3715       }
3716       // If no orders - skip current nodes and jump to the next one, if any.
3717       if (OrdersUses.empty()) {
3718         for_each(Data.second,
3719                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3720                    OrderedEntries.remove(Op.second);
3721                  });
3722         continue;
3723       }
3724       // Choose the best order.
3725       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3726       unsigned Cnt = OrdersUses.front().second;
3727       for (const auto &Pair : drop_begin(OrdersUses)) {
3728         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3729           BestOrder = Pair.first;
3730           Cnt = Pair.second;
3731         }
3732       }
3733       // Set order of the user node (reordering of operands and user nodes).
3734       if (BestOrder.empty()) {
3735         for_each(Data.second,
3736                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3737                    OrderedEntries.remove(Op.second);
3738                  });
3739         continue;
3740       }
3741       // Erase operands from OrderedEntries list and adjust their orders.
3742       VisitedOps.clear();
3743       SmallVector<int> Mask;
3744       inversePermutation(BestOrder, Mask);
3745       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3746       unsigned E = BestOrder.size();
3747       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3748         return I < E ? static_cast<int>(I) : UndefMaskElem;
3749       });
3750       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3751         TreeEntry *TE = Op.second;
3752         OrderedEntries.remove(TE);
3753         if (!VisitedOps.insert(TE).second)
3754           continue;
3755         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3756           // Just reorder reuses indices.
3757           reorderReuses(TE->ReuseShuffleIndices, Mask);
3758           continue;
3759         }
3760         // Gathers are processed separately.
3761         if (TE->State != TreeEntry::Vectorize)
3762           continue;
3763         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3764                 TE->ReorderIndices.empty()) &&
3765                "Non-matching sizes of user/operand entries.");
3766         reorderOrder(TE->ReorderIndices, Mask);
3767       }
3768       // For gathers just need to reorder its scalars.
3769       for (TreeEntry *Gather : GatherOps) {
3770         assert(Gather->ReorderIndices.empty() &&
3771                "Unexpected reordering of gathers.");
3772         if (!Gather->ReuseShuffleIndices.empty()) {
3773           // Just reorder reuses indices.
3774           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3775           continue;
3776         }
3777         reorderScalars(Gather->Scalars, Mask);
3778         OrderedEntries.remove(Gather);
3779       }
3780       // Reorder operands of the user node and set the ordering for the user
3781       // node itself.
3782       if (Data.first->State != TreeEntry::Vectorize ||
3783           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3784               Data.first->getMainOp()) ||
3785           Data.first->isAltShuffle())
3786         Data.first->reorderOperands(Mask);
3787       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3788           Data.first->isAltShuffle()) {
3789         reorderScalars(Data.first->Scalars, Mask);
3790         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3791         if (Data.first->ReuseShuffleIndices.empty() &&
3792             !Data.first->ReorderIndices.empty() &&
3793             !Data.first->isAltShuffle()) {
3794           // Insert user node to the list to try to sink reordering deeper in
3795           // the graph.
3796           OrderedEntries.insert(Data.first);
3797         }
3798       } else {
3799         reorderOrder(Data.first->ReorderIndices, Mask);
3800       }
3801     }
3802   }
3803   // If the reordering is unnecessary, just remove the reorder.
3804   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3805       VectorizableTree.front()->ReuseShuffleIndices.empty())
3806     VectorizableTree.front()->ReorderIndices.clear();
3807 }
3808 
3809 void BoUpSLP::buildExternalUses(
3810     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3811   // Collect the values that we need to extract from the tree.
3812   for (auto &TEPtr : VectorizableTree) {
3813     TreeEntry *Entry = TEPtr.get();
3814 
3815     // No need to handle users of gathered values.
3816     if (Entry->State == TreeEntry::NeedToGather)
3817       continue;
3818 
3819     // For each lane:
3820     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3821       Value *Scalar = Entry->Scalars[Lane];
3822       int FoundLane = Entry->findLaneForValue(Scalar);
3823 
3824       // Check if the scalar is externally used as an extra arg.
3825       auto ExtI = ExternallyUsedValues.find(Scalar);
3826       if (ExtI != ExternallyUsedValues.end()) {
3827         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3828                           << Lane << " from " << *Scalar << ".\n");
3829         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3830       }
3831       for (User *U : Scalar->users()) {
3832         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3833 
3834         Instruction *UserInst = dyn_cast<Instruction>(U);
3835         if (!UserInst)
3836           continue;
3837 
3838         if (isDeleted(UserInst))
3839           continue;
3840 
3841         // Skip in-tree scalars that become vectors
3842         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3843           Value *UseScalar = UseEntry->Scalars[0];
3844           // Some in-tree scalars will remain as scalar in vectorized
3845           // instructions. If that is the case, the one in Lane 0 will
3846           // be used.
3847           if (UseScalar != U ||
3848               UseEntry->State == TreeEntry::ScatterVectorize ||
3849               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3850             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3851                               << ".\n");
3852             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3853             continue;
3854           }
3855         }
3856 
3857         // Ignore users in the user ignore list.
3858         if (is_contained(UserIgnoreList, UserInst))
3859           continue;
3860 
3861         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3862                           << Lane << " from " << *Scalar << ".\n");
3863         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3864       }
3865     }
3866   }
3867 }
3868 
3869 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3870                         ArrayRef<Value *> UserIgnoreLst) {
3871   deleteTree();
3872   UserIgnoreList = UserIgnoreLst;
3873   if (!allSameType(Roots))
3874     return;
3875   buildTree_rec(Roots, 0, EdgeInfo());
3876 }
3877 
3878 namespace {
3879 /// Tracks the state we can represent the loads in the given sequence.
3880 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3881 } // anonymous namespace
3882 
3883 /// Checks if the given array of loads can be represented as a vectorized,
3884 /// scatter or just simple gather.
3885 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3886                                     const TargetTransformInfo &TTI,
3887                                     const DataLayout &DL, ScalarEvolution &SE,
3888                                     SmallVectorImpl<unsigned> &Order,
3889                                     SmallVectorImpl<Value *> &PointerOps) {
3890   // Check that a vectorized load would load the same memory as a scalar
3891   // load. For example, we don't want to vectorize loads that are smaller
3892   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3893   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3894   // from such a struct, we read/write packed bits disagreeing with the
3895   // unvectorized version.
3896   Type *ScalarTy = VL0->getType();
3897 
3898   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3899     return LoadsState::Gather;
3900 
3901   // Make sure all loads in the bundle are simple - we can't vectorize
3902   // atomic or volatile loads.
3903   PointerOps.clear();
3904   PointerOps.resize(VL.size());
3905   auto *POIter = PointerOps.begin();
3906   for (Value *V : VL) {
3907     auto *L = cast<LoadInst>(V);
3908     if (!L->isSimple())
3909       return LoadsState::Gather;
3910     *POIter = L->getPointerOperand();
3911     ++POIter;
3912   }
3913 
3914   Order.clear();
3915   // Check the order of pointer operands.
3916   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3917     Value *Ptr0;
3918     Value *PtrN;
3919     if (Order.empty()) {
3920       Ptr0 = PointerOps.front();
3921       PtrN = PointerOps.back();
3922     } else {
3923       Ptr0 = PointerOps[Order.front()];
3924       PtrN = PointerOps[Order.back()];
3925     }
3926     Optional<int> Diff =
3927         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3928     // Check that the sorted loads are consecutive.
3929     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3930       return LoadsState::Vectorize;
3931     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3932     for (Value *V : VL)
3933       CommonAlignment =
3934           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3935     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3936                                 CommonAlignment))
3937       return LoadsState::ScatterVectorize;
3938   }
3939 
3940   return LoadsState::Gather;
3941 }
3942 
3943 /// \return true if the specified list of values has only one instruction that
3944 /// requires scheduling, false otherwise.
3945 #ifndef NDEBUG
3946 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3947   Value *NeedsScheduling = nullptr;
3948   for (Value *V : VL) {
3949     if (doesNotNeedToBeScheduled(V))
3950       continue;
3951     if (!NeedsScheduling) {
3952       NeedsScheduling = V;
3953       continue;
3954     }
3955     return false;
3956   }
3957   return NeedsScheduling;
3958 }
3959 #endif
3960 
3961 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3962                             const EdgeInfo &UserTreeIdx) {
3963   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3964 
3965   SmallVector<int> ReuseShuffleIndicies;
3966   SmallVector<Value *> UniqueValues;
3967   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3968                                 &UserTreeIdx,
3969                                 this](const InstructionsState &S) {
3970     // Check that every instruction appears once in this bundle.
3971     DenseMap<Value *, unsigned> UniquePositions;
3972     for (Value *V : VL) {
3973       if (isConstant(V)) {
3974         ReuseShuffleIndicies.emplace_back(
3975             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3976         UniqueValues.emplace_back(V);
3977         continue;
3978       }
3979       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3980       ReuseShuffleIndicies.emplace_back(Res.first->second);
3981       if (Res.second)
3982         UniqueValues.emplace_back(V);
3983     }
3984     size_t NumUniqueScalarValues = UniqueValues.size();
3985     if (NumUniqueScalarValues == VL.size()) {
3986       ReuseShuffleIndicies.clear();
3987     } else {
3988       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3989       if (NumUniqueScalarValues <= 1 ||
3990           (UniquePositions.size() == 1 && all_of(UniqueValues,
3991                                                  [](Value *V) {
3992                                                    return isa<UndefValue>(V) ||
3993                                                           !isConstant(V);
3994                                                  })) ||
3995           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3996         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3997         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3998         return false;
3999       }
4000       VL = UniqueValues;
4001     }
4002     return true;
4003   };
4004 
4005   InstructionsState S = getSameOpcode(VL);
4006   if (Depth == RecursionMaxDepth) {
4007     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
4008     if (TryToFindDuplicates(S))
4009       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4010                    ReuseShuffleIndicies);
4011     return;
4012   }
4013 
4014   // Don't handle scalable vectors
4015   if (S.getOpcode() == Instruction::ExtractElement &&
4016       isa<ScalableVectorType>(
4017           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4018     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4019     if (TryToFindDuplicates(S))
4020       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4021                    ReuseShuffleIndicies);
4022     return;
4023   }
4024 
4025   // Don't handle vectors.
4026   if (S.OpValue->getType()->isVectorTy() &&
4027       !isa<InsertElementInst>(S.OpValue)) {
4028     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4029     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4030     return;
4031   }
4032 
4033   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4034     if (SI->getValueOperand()->getType()->isVectorTy()) {
4035       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4036       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4037       return;
4038     }
4039 
4040   // If all of the operands are identical or constant we have a simple solution.
4041   // If we deal with insert/extract instructions, they all must have constant
4042   // indices, otherwise we should gather them, not try to vectorize.
4043   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4044       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4045        !all_of(VL, isVectorLikeInstWithConstOps))) {
4046     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4047     if (TryToFindDuplicates(S))
4048       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4049                    ReuseShuffleIndicies);
4050     return;
4051   }
4052 
4053   // We now know that this is a vector of instructions of the same type from
4054   // the same block.
4055 
4056   // Don't vectorize ephemeral values.
4057   for (Value *V : VL) {
4058     if (EphValues.count(V)) {
4059       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4060                         << ") is ephemeral.\n");
4061       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4062       return;
4063     }
4064   }
4065 
4066   // Check if this is a duplicate of another entry.
4067   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4068     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4069     if (!E->isSame(VL)) {
4070       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4071       if (TryToFindDuplicates(S))
4072         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4073                      ReuseShuffleIndicies);
4074       return;
4075     }
4076     // Record the reuse of the tree node.  FIXME, currently this is only used to
4077     // properly draw the graph rather than for the actual vectorization.
4078     E->UserTreeIndices.push_back(UserTreeIdx);
4079     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4080                       << ".\n");
4081     return;
4082   }
4083 
4084   // Check that none of the instructions in the bundle are already in the tree.
4085   for (Value *V : VL) {
4086     auto *I = dyn_cast<Instruction>(V);
4087     if (!I)
4088       continue;
4089     if (getTreeEntry(I)) {
4090       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4091                         << ") is already in tree.\n");
4092       if (TryToFindDuplicates(S))
4093         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4094                      ReuseShuffleIndicies);
4095       return;
4096     }
4097   }
4098 
4099   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4100   for (Value *V : VL) {
4101     if (is_contained(UserIgnoreList, V)) {
4102       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4103       if (TryToFindDuplicates(S))
4104         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4105                      ReuseShuffleIndicies);
4106       return;
4107     }
4108   }
4109 
4110   // Check that all of the users of the scalars that we want to vectorize are
4111   // schedulable.
4112   auto *VL0 = cast<Instruction>(S.OpValue);
4113   BasicBlock *BB = VL0->getParent();
4114 
4115   if (!DT->isReachableFromEntry(BB)) {
4116     // Don't go into unreachable blocks. They may contain instructions with
4117     // dependency cycles which confuse the final scheduling.
4118     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4119     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4120     return;
4121   }
4122 
4123   // Check that every instruction appears once in this bundle.
4124   if (!TryToFindDuplicates(S))
4125     return;
4126 
4127   auto &BSRef = BlocksSchedules[BB];
4128   if (!BSRef)
4129     BSRef = std::make_unique<BlockScheduling>(BB);
4130 
4131   BlockScheduling &BS = *BSRef;
4132 
4133   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4134 #ifdef EXPENSIVE_CHECKS
4135   // Make sure we didn't break any internal invariants
4136   BS.verify();
4137 #endif
4138   if (!Bundle) {
4139     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4140     assert((!BS.getScheduleData(VL0) ||
4141             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4142            "tryScheduleBundle should cancelScheduling on failure");
4143     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4144                  ReuseShuffleIndicies);
4145     return;
4146   }
4147   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4148 
4149   unsigned ShuffleOrOp = S.isAltShuffle() ?
4150                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4151   switch (ShuffleOrOp) {
4152     case Instruction::PHI: {
4153       auto *PH = cast<PHINode>(VL0);
4154 
4155       // Check for terminator values (e.g. invoke).
4156       for (Value *V : VL)
4157         for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
4158           Instruction *Term = dyn_cast<Instruction>(Incoming);
4159           if (Term && Term->isTerminator()) {
4160             LLVM_DEBUG(dbgs()
4161                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4162             BS.cancelScheduling(VL, VL0);
4163             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4164                          ReuseShuffleIndicies);
4165             return;
4166           }
4167         }
4168 
4169       TreeEntry *TE =
4170           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4171       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4172 
4173       // Keeps the reordered operands to avoid code duplication.
4174       SmallVector<ValueList, 2> OperandsVec;
4175       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4176         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4177           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4178           TE->setOperand(I, Operands);
4179           OperandsVec.push_back(Operands);
4180           continue;
4181         }
4182         ValueList Operands;
4183         // Prepare the operand vector.
4184         for (Value *V : VL)
4185           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4186               PH->getIncomingBlock(I)));
4187         TE->setOperand(I, Operands);
4188         OperandsVec.push_back(Operands);
4189       }
4190       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4191         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4192       return;
4193     }
4194     case Instruction::ExtractValue:
4195     case Instruction::ExtractElement: {
4196       OrdersType CurrentOrder;
4197       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4198       if (Reuse) {
4199         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4200         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4201                      ReuseShuffleIndicies);
4202         // This is a special case, as it does not gather, but at the same time
4203         // we are not extending buildTree_rec() towards the operands.
4204         ValueList Op0;
4205         Op0.assign(VL.size(), VL0->getOperand(0));
4206         VectorizableTree.back()->setOperand(0, Op0);
4207         return;
4208       }
4209       if (!CurrentOrder.empty()) {
4210         LLVM_DEBUG({
4211           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4212                     "with order";
4213           for (unsigned Idx : CurrentOrder)
4214             dbgs() << " " << Idx;
4215           dbgs() << "\n";
4216         });
4217         fixupOrderingIndices(CurrentOrder);
4218         // Insert new order with initial value 0, if it does not exist,
4219         // otherwise return the iterator to the existing one.
4220         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4221                      ReuseShuffleIndicies, CurrentOrder);
4222         // This is a special case, as it does not gather, but at the same time
4223         // we are not extending buildTree_rec() towards the operands.
4224         ValueList Op0;
4225         Op0.assign(VL.size(), VL0->getOperand(0));
4226         VectorizableTree.back()->setOperand(0, Op0);
4227         return;
4228       }
4229       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4230       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4231                    ReuseShuffleIndicies);
4232       BS.cancelScheduling(VL, VL0);
4233       return;
4234     }
4235     case Instruction::InsertElement: {
4236       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4237 
4238       // Check that we have a buildvector and not a shuffle of 2 or more
4239       // different vectors.
4240       ValueSet SourceVectors;
4241       for (Value *V : VL) {
4242         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4243         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4244       }
4245 
4246       if (count_if(VL, [&SourceVectors](Value *V) {
4247             return !SourceVectors.contains(V);
4248           }) >= 2) {
4249         // Found 2nd source vector - cancel.
4250         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4251                              "different source vectors.\n");
4252         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4253         BS.cancelScheduling(VL, VL0);
4254         return;
4255       }
4256 
4257       auto OrdCompare = [](const std::pair<int, int> &P1,
4258                            const std::pair<int, int> &P2) {
4259         return P1.first > P2.first;
4260       };
4261       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4262                     decltype(OrdCompare)>
4263           Indices(OrdCompare);
4264       for (int I = 0, E = VL.size(); I < E; ++I) {
4265         unsigned Idx = *getInsertIndex(VL[I]);
4266         Indices.emplace(Idx, I);
4267       }
4268       OrdersType CurrentOrder(VL.size(), VL.size());
4269       bool IsIdentity = true;
4270       for (int I = 0, E = VL.size(); I < E; ++I) {
4271         CurrentOrder[Indices.top().second] = I;
4272         IsIdentity &= Indices.top().second == I;
4273         Indices.pop();
4274       }
4275       if (IsIdentity)
4276         CurrentOrder.clear();
4277       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4278                                    None, CurrentOrder);
4279       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4280 
4281       constexpr int NumOps = 2;
4282       ValueList VectorOperands[NumOps];
4283       for (int I = 0; I < NumOps; ++I) {
4284         for (Value *V : VL)
4285           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4286 
4287         TE->setOperand(I, VectorOperands[I]);
4288       }
4289       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4290       return;
4291     }
4292     case Instruction::Load: {
4293       // Check that a vectorized load would load the same memory as a scalar
4294       // load. For example, we don't want to vectorize loads that are smaller
4295       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4296       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4297       // from such a struct, we read/write packed bits disagreeing with the
4298       // unvectorized version.
4299       SmallVector<Value *> PointerOps;
4300       OrdersType CurrentOrder;
4301       TreeEntry *TE = nullptr;
4302       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4303                                 PointerOps)) {
4304       case LoadsState::Vectorize:
4305         if (CurrentOrder.empty()) {
4306           // Original loads are consecutive and does not require reordering.
4307           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4308                             ReuseShuffleIndicies);
4309           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4310         } else {
4311           fixupOrderingIndices(CurrentOrder);
4312           // Need to reorder.
4313           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4314                             ReuseShuffleIndicies, CurrentOrder);
4315           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4316         }
4317         TE->setOperandsInOrder();
4318         break;
4319       case LoadsState::ScatterVectorize:
4320         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4321         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4322                           UserTreeIdx, ReuseShuffleIndicies);
4323         TE->setOperandsInOrder();
4324         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4325         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4326         break;
4327       case LoadsState::Gather:
4328         BS.cancelScheduling(VL, VL0);
4329         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4330                      ReuseShuffleIndicies);
4331 #ifndef NDEBUG
4332         Type *ScalarTy = VL0->getType();
4333         if (DL->getTypeSizeInBits(ScalarTy) !=
4334             DL->getTypeAllocSizeInBits(ScalarTy))
4335           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4336         else if (any_of(VL, [](Value *V) {
4337                    return !cast<LoadInst>(V)->isSimple();
4338                  }))
4339           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4340         else
4341           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4342 #endif // NDEBUG
4343         break;
4344       }
4345       return;
4346     }
4347     case Instruction::ZExt:
4348     case Instruction::SExt:
4349     case Instruction::FPToUI:
4350     case Instruction::FPToSI:
4351     case Instruction::FPExt:
4352     case Instruction::PtrToInt:
4353     case Instruction::IntToPtr:
4354     case Instruction::SIToFP:
4355     case Instruction::UIToFP:
4356     case Instruction::Trunc:
4357     case Instruction::FPTrunc:
4358     case Instruction::BitCast: {
4359       Type *SrcTy = VL0->getOperand(0)->getType();
4360       for (Value *V : VL) {
4361         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4362         if (Ty != SrcTy || !isValidElementType(Ty)) {
4363           BS.cancelScheduling(VL, VL0);
4364           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4365                        ReuseShuffleIndicies);
4366           LLVM_DEBUG(dbgs()
4367                      << "SLP: Gathering casts with different src types.\n");
4368           return;
4369         }
4370       }
4371       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4372                                    ReuseShuffleIndicies);
4373       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4374 
4375       TE->setOperandsInOrder();
4376       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4377         ValueList Operands;
4378         // Prepare the operand vector.
4379         for (Value *V : VL)
4380           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4381 
4382         buildTree_rec(Operands, Depth + 1, {TE, i});
4383       }
4384       return;
4385     }
4386     case Instruction::ICmp:
4387     case Instruction::FCmp: {
4388       // Check that all of the compares have the same predicate.
4389       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4390       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4391       Type *ComparedTy = VL0->getOperand(0)->getType();
4392       for (Value *V : VL) {
4393         CmpInst *Cmp = cast<CmpInst>(V);
4394         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4395             Cmp->getOperand(0)->getType() != ComparedTy) {
4396           BS.cancelScheduling(VL, VL0);
4397           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4398                        ReuseShuffleIndicies);
4399           LLVM_DEBUG(dbgs()
4400                      << "SLP: Gathering cmp with different predicate.\n");
4401           return;
4402         }
4403       }
4404 
4405       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4406                                    ReuseShuffleIndicies);
4407       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4408 
4409       ValueList Left, Right;
4410       if (cast<CmpInst>(VL0)->isCommutative()) {
4411         // Commutative predicate - collect + sort operands of the instructions
4412         // so that each side is more likely to have the same opcode.
4413         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4414         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4415       } else {
4416         // Collect operands - commute if it uses the swapped predicate.
4417         for (Value *V : VL) {
4418           auto *Cmp = cast<CmpInst>(V);
4419           Value *LHS = Cmp->getOperand(0);
4420           Value *RHS = Cmp->getOperand(1);
4421           if (Cmp->getPredicate() != P0)
4422             std::swap(LHS, RHS);
4423           Left.push_back(LHS);
4424           Right.push_back(RHS);
4425         }
4426       }
4427       TE->setOperand(0, Left);
4428       TE->setOperand(1, Right);
4429       buildTree_rec(Left, Depth + 1, {TE, 0});
4430       buildTree_rec(Right, Depth + 1, {TE, 1});
4431       return;
4432     }
4433     case Instruction::Select:
4434     case Instruction::FNeg:
4435     case Instruction::Add:
4436     case Instruction::FAdd:
4437     case Instruction::Sub:
4438     case Instruction::FSub:
4439     case Instruction::Mul:
4440     case Instruction::FMul:
4441     case Instruction::UDiv:
4442     case Instruction::SDiv:
4443     case Instruction::FDiv:
4444     case Instruction::URem:
4445     case Instruction::SRem:
4446     case Instruction::FRem:
4447     case Instruction::Shl:
4448     case Instruction::LShr:
4449     case Instruction::AShr:
4450     case Instruction::And:
4451     case Instruction::Or:
4452     case Instruction::Xor: {
4453       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4454                                    ReuseShuffleIndicies);
4455       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4456 
4457       // Sort operands of the instructions so that each side is more likely to
4458       // have the same opcode.
4459       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4460         ValueList Left, Right;
4461         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4462         TE->setOperand(0, Left);
4463         TE->setOperand(1, Right);
4464         buildTree_rec(Left, Depth + 1, {TE, 0});
4465         buildTree_rec(Right, Depth + 1, {TE, 1});
4466         return;
4467       }
4468 
4469       TE->setOperandsInOrder();
4470       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4471         ValueList Operands;
4472         // Prepare the operand vector.
4473         for (Value *V : VL)
4474           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4475 
4476         buildTree_rec(Operands, Depth + 1, {TE, i});
4477       }
4478       return;
4479     }
4480     case Instruction::GetElementPtr: {
4481       // We don't combine GEPs with complicated (nested) indexing.
4482       for (Value *V : VL) {
4483         if (cast<Instruction>(V)->getNumOperands() != 2) {
4484           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4485           BS.cancelScheduling(VL, VL0);
4486           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4487                        ReuseShuffleIndicies);
4488           return;
4489         }
4490       }
4491 
4492       // We can't combine several GEPs into one vector if they operate on
4493       // different types.
4494       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4495       for (Value *V : VL) {
4496         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4497         if (Ty0 != CurTy) {
4498           LLVM_DEBUG(dbgs()
4499                      << "SLP: not-vectorizable GEP (different types).\n");
4500           BS.cancelScheduling(VL, VL0);
4501           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4502                        ReuseShuffleIndicies);
4503           return;
4504         }
4505       }
4506 
4507       // We don't combine GEPs with non-constant indexes.
4508       Type *Ty1 = VL0->getOperand(1)->getType();
4509       for (Value *V : VL) {
4510         auto Op = cast<Instruction>(V)->getOperand(1);
4511         if (!isa<ConstantInt>(Op) ||
4512             (Op->getType() != Ty1 &&
4513              Op->getType()->getScalarSizeInBits() >
4514                  DL->getIndexSizeInBits(
4515                      V->getType()->getPointerAddressSpace()))) {
4516           LLVM_DEBUG(dbgs()
4517                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4518           BS.cancelScheduling(VL, VL0);
4519           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4520                        ReuseShuffleIndicies);
4521           return;
4522         }
4523       }
4524 
4525       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4526                                    ReuseShuffleIndicies);
4527       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4528       SmallVector<ValueList, 2> Operands(2);
4529       // Prepare the operand vector for pointer operands.
4530       for (Value *V : VL)
4531         Operands.front().push_back(
4532             cast<GetElementPtrInst>(V)->getPointerOperand());
4533       TE->setOperand(0, Operands.front());
4534       // Need to cast all indices to the same type before vectorization to
4535       // avoid crash.
4536       // Required to be able to find correct matches between different gather
4537       // nodes and reuse the vectorized values rather than trying to gather them
4538       // again.
4539       int IndexIdx = 1;
4540       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4541       Type *Ty = all_of(VL,
4542                         [VL0Ty, IndexIdx](Value *V) {
4543                           return VL0Ty == cast<GetElementPtrInst>(V)
4544                                               ->getOperand(IndexIdx)
4545                                               ->getType();
4546                         })
4547                      ? VL0Ty
4548                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4549                                             ->getPointerOperandType()
4550                                             ->getScalarType());
4551       // Prepare the operand vector.
4552       for (Value *V : VL) {
4553         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4554         auto *CI = cast<ConstantInt>(Op);
4555         Operands.back().push_back(ConstantExpr::getIntegerCast(
4556             CI, Ty, CI->getValue().isSignBitSet()));
4557       }
4558       TE->setOperand(IndexIdx, Operands.back());
4559 
4560       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4561         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4562       return;
4563     }
4564     case Instruction::Store: {
4565       // Check if the stores are consecutive or if we need to swizzle them.
4566       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4567       // Avoid types that are padded when being allocated as scalars, while
4568       // being packed together in a vector (such as i1).
4569       if (DL->getTypeSizeInBits(ScalarTy) !=
4570           DL->getTypeAllocSizeInBits(ScalarTy)) {
4571         BS.cancelScheduling(VL, VL0);
4572         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4573                      ReuseShuffleIndicies);
4574         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4575         return;
4576       }
4577       // Make sure all stores in the bundle are simple - we can't vectorize
4578       // atomic or volatile stores.
4579       SmallVector<Value *, 4> PointerOps(VL.size());
4580       ValueList Operands(VL.size());
4581       auto POIter = PointerOps.begin();
4582       auto OIter = Operands.begin();
4583       for (Value *V : VL) {
4584         auto *SI = cast<StoreInst>(V);
4585         if (!SI->isSimple()) {
4586           BS.cancelScheduling(VL, VL0);
4587           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4588                        ReuseShuffleIndicies);
4589           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4590           return;
4591         }
4592         *POIter = SI->getPointerOperand();
4593         *OIter = SI->getValueOperand();
4594         ++POIter;
4595         ++OIter;
4596       }
4597 
4598       OrdersType CurrentOrder;
4599       // Check the order of pointer operands.
4600       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4601         Value *Ptr0;
4602         Value *PtrN;
4603         if (CurrentOrder.empty()) {
4604           Ptr0 = PointerOps.front();
4605           PtrN = PointerOps.back();
4606         } else {
4607           Ptr0 = PointerOps[CurrentOrder.front()];
4608           PtrN = PointerOps[CurrentOrder.back()];
4609         }
4610         Optional<int> Dist =
4611             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4612         // Check that the sorted pointer operands are consecutive.
4613         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4614           if (CurrentOrder.empty()) {
4615             // Original stores are consecutive and does not require reordering.
4616             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4617                                          UserTreeIdx, ReuseShuffleIndicies);
4618             TE->setOperandsInOrder();
4619             buildTree_rec(Operands, Depth + 1, {TE, 0});
4620             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4621           } else {
4622             fixupOrderingIndices(CurrentOrder);
4623             TreeEntry *TE =
4624                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4625                              ReuseShuffleIndicies, CurrentOrder);
4626             TE->setOperandsInOrder();
4627             buildTree_rec(Operands, Depth + 1, {TE, 0});
4628             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4629           }
4630           return;
4631         }
4632       }
4633 
4634       BS.cancelScheduling(VL, VL0);
4635       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4636                    ReuseShuffleIndicies);
4637       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4638       return;
4639     }
4640     case Instruction::Call: {
4641       // Check if the calls are all to the same vectorizable intrinsic or
4642       // library function.
4643       CallInst *CI = cast<CallInst>(VL0);
4644       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4645 
4646       VFShape Shape = VFShape::get(
4647           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4648           false /*HasGlobalPred*/);
4649       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4650 
4651       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4652         BS.cancelScheduling(VL, VL0);
4653         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4654                      ReuseShuffleIndicies);
4655         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4656         return;
4657       }
4658       Function *F = CI->getCalledFunction();
4659       unsigned NumArgs = CI->arg_size();
4660       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4661       for (unsigned j = 0; j != NumArgs; ++j)
4662         if (hasVectorInstrinsicScalarOpd(ID, j))
4663           ScalarArgs[j] = CI->getArgOperand(j);
4664       for (Value *V : VL) {
4665         CallInst *CI2 = dyn_cast<CallInst>(V);
4666         if (!CI2 || CI2->getCalledFunction() != F ||
4667             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4668             (VecFunc &&
4669              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4670             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4671           BS.cancelScheduling(VL, VL0);
4672           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4673                        ReuseShuffleIndicies);
4674           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4675                             << "\n");
4676           return;
4677         }
4678         // Some intrinsics have scalar arguments and should be same in order for
4679         // them to be vectorized.
4680         for (unsigned j = 0; j != NumArgs; ++j) {
4681           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4682             Value *A1J = CI2->getArgOperand(j);
4683             if (ScalarArgs[j] != A1J) {
4684               BS.cancelScheduling(VL, VL0);
4685               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4686                            ReuseShuffleIndicies);
4687               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4688                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4689                                 << "\n");
4690               return;
4691             }
4692           }
4693         }
4694         // Verify that the bundle operands are identical between the two calls.
4695         if (CI->hasOperandBundles() &&
4696             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4697                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4698                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4699           BS.cancelScheduling(VL, VL0);
4700           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4701                        ReuseShuffleIndicies);
4702           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4703                             << *CI << "!=" << *V << '\n');
4704           return;
4705         }
4706       }
4707 
4708       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4709                                    ReuseShuffleIndicies);
4710       TE->setOperandsInOrder();
4711       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4712         // For scalar operands no need to to create an entry since no need to
4713         // vectorize it.
4714         if (hasVectorInstrinsicScalarOpd(ID, i))
4715           continue;
4716         ValueList Operands;
4717         // Prepare the operand vector.
4718         for (Value *V : VL) {
4719           auto *CI2 = cast<CallInst>(V);
4720           Operands.push_back(CI2->getArgOperand(i));
4721         }
4722         buildTree_rec(Operands, Depth + 1, {TE, i});
4723       }
4724       return;
4725     }
4726     case Instruction::ShuffleVector: {
4727       // If this is not an alternate sequence of opcode like add-sub
4728       // then do not vectorize this instruction.
4729       if (!S.isAltShuffle()) {
4730         BS.cancelScheduling(VL, VL0);
4731         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4732                      ReuseShuffleIndicies);
4733         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4734         return;
4735       }
4736       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4737                                    ReuseShuffleIndicies);
4738       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4739 
4740       // Reorder operands if reordering would enable vectorization.
4741       auto *CI = dyn_cast<CmpInst>(VL0);
4742       if (isa<BinaryOperator>(VL0) || CI) {
4743         ValueList Left, Right;
4744         if (!CI || all_of(VL, [](Value *V) {
4745               return cast<CmpInst>(V)->isCommutative();
4746             })) {
4747           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4748         } else {
4749           CmpInst::Predicate P0 = CI->getPredicate();
4750           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4751           assert(P0 != AltP0 &&
4752                  "Expected different main/alternate predicates.");
4753           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4754           Value *BaseOp0 = VL0->getOperand(0);
4755           Value *BaseOp1 = VL0->getOperand(1);
4756           // Collect operands - commute if it uses the swapped predicate or
4757           // alternate operation.
4758           for (Value *V : VL) {
4759             auto *Cmp = cast<CmpInst>(V);
4760             Value *LHS = Cmp->getOperand(0);
4761             Value *RHS = Cmp->getOperand(1);
4762             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4763             if (P0 == AltP0Swapped) {
4764               if (CI != Cmp && S.AltOp != Cmp &&
4765                   ((P0 == CurrentPred &&
4766                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4767                    (AltP0 == CurrentPred &&
4768                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4769                 std::swap(LHS, RHS);
4770             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4771               std::swap(LHS, RHS);
4772             }
4773             Left.push_back(LHS);
4774             Right.push_back(RHS);
4775           }
4776         }
4777         TE->setOperand(0, Left);
4778         TE->setOperand(1, Right);
4779         buildTree_rec(Left, Depth + 1, {TE, 0});
4780         buildTree_rec(Right, Depth + 1, {TE, 1});
4781         return;
4782       }
4783 
4784       TE->setOperandsInOrder();
4785       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4786         ValueList Operands;
4787         // Prepare the operand vector.
4788         for (Value *V : VL)
4789           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4790 
4791         buildTree_rec(Operands, Depth + 1, {TE, i});
4792       }
4793       return;
4794     }
4795     default:
4796       BS.cancelScheduling(VL, VL0);
4797       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4798                    ReuseShuffleIndicies);
4799       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4800       return;
4801   }
4802 }
4803 
4804 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4805   unsigned N = 1;
4806   Type *EltTy = T;
4807 
4808   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4809          isa<VectorType>(EltTy)) {
4810     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4811       // Check that struct is homogeneous.
4812       for (const auto *Ty : ST->elements())
4813         if (Ty != *ST->element_begin())
4814           return 0;
4815       N *= ST->getNumElements();
4816       EltTy = *ST->element_begin();
4817     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4818       N *= AT->getNumElements();
4819       EltTy = AT->getElementType();
4820     } else {
4821       auto *VT = cast<FixedVectorType>(EltTy);
4822       N *= VT->getNumElements();
4823       EltTy = VT->getElementType();
4824     }
4825   }
4826 
4827   if (!isValidElementType(EltTy))
4828     return 0;
4829   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4830   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4831     return 0;
4832   return N;
4833 }
4834 
4835 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4836                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4837   const auto *It = find_if(VL, [](Value *V) {
4838     return isa<ExtractElementInst, ExtractValueInst>(V);
4839   });
4840   assert(It != VL.end() && "Expected at least one extract instruction.");
4841   auto *E0 = cast<Instruction>(*It);
4842   assert(all_of(VL,
4843                 [](Value *V) {
4844                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4845                       V);
4846                 }) &&
4847          "Invalid opcode");
4848   // Check if all of the extracts come from the same vector and from the
4849   // correct offset.
4850   Value *Vec = E0->getOperand(0);
4851 
4852   CurrentOrder.clear();
4853 
4854   // We have to extract from a vector/aggregate with the same number of elements.
4855   unsigned NElts;
4856   if (E0->getOpcode() == Instruction::ExtractValue) {
4857     const DataLayout &DL = E0->getModule()->getDataLayout();
4858     NElts = canMapToVector(Vec->getType(), DL);
4859     if (!NElts)
4860       return false;
4861     // Check if load can be rewritten as load of vector.
4862     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4863     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4864       return false;
4865   } else {
4866     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4867   }
4868 
4869   if (NElts != VL.size())
4870     return false;
4871 
4872   // Check that all of the indices extract from the correct offset.
4873   bool ShouldKeepOrder = true;
4874   unsigned E = VL.size();
4875   // Assign to all items the initial value E + 1 so we can check if the extract
4876   // instruction index was used already.
4877   // Also, later we can check that all the indices are used and we have a
4878   // consecutive access in the extract instructions, by checking that no
4879   // element of CurrentOrder still has value E + 1.
4880   CurrentOrder.assign(E, E);
4881   unsigned I = 0;
4882   for (; I < E; ++I) {
4883     auto *Inst = dyn_cast<Instruction>(VL[I]);
4884     if (!Inst)
4885       continue;
4886     if (Inst->getOperand(0) != Vec)
4887       break;
4888     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4889       if (isa<UndefValue>(EE->getIndexOperand()))
4890         continue;
4891     Optional<unsigned> Idx = getExtractIndex(Inst);
4892     if (!Idx)
4893       break;
4894     const unsigned ExtIdx = *Idx;
4895     if (ExtIdx != I) {
4896       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4897         break;
4898       ShouldKeepOrder = false;
4899       CurrentOrder[ExtIdx] = I;
4900     } else {
4901       if (CurrentOrder[I] != E)
4902         break;
4903       CurrentOrder[I] = I;
4904     }
4905   }
4906   if (I < E) {
4907     CurrentOrder.clear();
4908     return false;
4909   }
4910   if (ShouldKeepOrder)
4911     CurrentOrder.clear();
4912 
4913   return ShouldKeepOrder;
4914 }
4915 
4916 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4917                                     ArrayRef<Value *> VectorizedVals) const {
4918   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4919          all_of(I->users(), [this](User *U) {
4920            return ScalarToTreeEntry.count(U) > 0 ||
4921                   isVectorLikeInstWithConstOps(U) ||
4922                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4923          });
4924 }
4925 
4926 static std::pair<InstructionCost, InstructionCost>
4927 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4928                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4929   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4930 
4931   // Calculate the cost of the scalar and vector calls.
4932   SmallVector<Type *, 4> VecTys;
4933   for (Use &Arg : CI->args())
4934     VecTys.push_back(
4935         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4936   FastMathFlags FMF;
4937   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4938     FMF = FPCI->getFastMathFlags();
4939   SmallVector<const Value *> Arguments(CI->args());
4940   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4941                                     dyn_cast<IntrinsicInst>(CI));
4942   auto IntrinsicCost =
4943     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4944 
4945   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4946                                      VecTy->getNumElements())),
4947                             false /*HasGlobalPred*/);
4948   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4949   auto LibCost = IntrinsicCost;
4950   if (!CI->isNoBuiltin() && VecFunc) {
4951     // Calculate the cost of the vector library call.
4952     // If the corresponding vector call is cheaper, return its cost.
4953     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4954                                     TTI::TCK_RecipThroughput);
4955   }
4956   return {IntrinsicCost, LibCost};
4957 }
4958 
4959 /// Compute the cost of creating a vector of type \p VecTy containing the
4960 /// extracted values from \p VL.
4961 static InstructionCost
4962 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4963                    TargetTransformInfo::ShuffleKind ShuffleKind,
4964                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4965   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4966 
4967   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4968       VecTy->getNumElements() < NumOfParts)
4969     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4970 
4971   bool AllConsecutive = true;
4972   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4973   unsigned Idx = -1;
4974   InstructionCost Cost = 0;
4975 
4976   // Process extracts in blocks of EltsPerVector to check if the source vector
4977   // operand can be re-used directly. If not, add the cost of creating a shuffle
4978   // to extract the values into a vector register.
4979   for (auto *V : VL) {
4980     ++Idx;
4981 
4982     // Need to exclude undefs from analysis.
4983     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4984       continue;
4985 
4986     // Reached the start of a new vector registers.
4987     if (Idx % EltsPerVector == 0) {
4988       AllConsecutive = true;
4989       continue;
4990     }
4991 
4992     // Check all extracts for a vector register on the target directly
4993     // extract values in order.
4994     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4995     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4996       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4997       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4998                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4999     }
5000 
5001     if (AllConsecutive)
5002       continue;
5003 
5004     // Skip all indices, except for the last index per vector block.
5005     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5006       continue;
5007 
5008     // If we have a series of extracts which are not consecutive and hence
5009     // cannot re-use the source vector register directly, compute the shuffle
5010     // cost to extract the a vector with EltsPerVector elements.
5011     Cost += TTI.getShuffleCost(
5012         TargetTransformInfo::SK_PermuteSingleSrc,
5013         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5014   }
5015   return Cost;
5016 }
5017 
5018 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5019 /// operations operands.
5020 static void
5021 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5022                       ArrayRef<int> ReusesIndices,
5023                       const function_ref<bool(Instruction *)> IsAltOp,
5024                       SmallVectorImpl<int> &Mask,
5025                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5026                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5027   unsigned Sz = VL.size();
5028   Mask.assign(Sz, UndefMaskElem);
5029   SmallVector<int> OrderMask;
5030   if (!ReorderIndices.empty())
5031     inversePermutation(ReorderIndices, OrderMask);
5032   for (unsigned I = 0; I < Sz; ++I) {
5033     unsigned Idx = I;
5034     if (!ReorderIndices.empty())
5035       Idx = OrderMask[I];
5036     auto *OpInst = cast<Instruction>(VL[Idx]);
5037     if (IsAltOp(OpInst)) {
5038       Mask[I] = Sz + Idx;
5039       if (AltScalars)
5040         AltScalars->push_back(OpInst);
5041     } else {
5042       Mask[I] = Idx;
5043       if (OpScalars)
5044         OpScalars->push_back(OpInst);
5045     }
5046   }
5047   if (!ReusesIndices.empty()) {
5048     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5049     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5050       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5051     });
5052     Mask.swap(NewMask);
5053   }
5054 }
5055 
5056 /// Checks if the specified instruction \p I is an alternate operation for the
5057 /// given \p MainOp and \p AltOp instructions.
5058 static bool isAlternateInstruction(const Instruction *I,
5059                                    const Instruction *MainOp,
5060                                    const Instruction *AltOp) {
5061   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5062     auto *AltCI0 = cast<CmpInst>(AltOp);
5063     auto *CI = cast<CmpInst>(I);
5064     CmpInst::Predicate P0 = CI0->getPredicate();
5065     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5066     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5067     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5068     CmpInst::Predicate CurrentPred = CI->getPredicate();
5069     if (P0 == AltP0Swapped)
5070       return I == AltCI0 ||
5071              (I != MainOp &&
5072               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5073                                    CI->getOperand(0), CI->getOperand(1)));
5074     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5075   }
5076   return I->getOpcode() == AltOp->getOpcode();
5077 }
5078 
5079 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5080                                       ArrayRef<Value *> VectorizedVals) {
5081   ArrayRef<Value*> VL = E->Scalars;
5082 
5083   Type *ScalarTy = VL[0]->getType();
5084   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5085     ScalarTy = SI->getValueOperand()->getType();
5086   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5087     ScalarTy = CI->getOperand(0)->getType();
5088   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5089     ScalarTy = IE->getOperand(1)->getType();
5090   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5091   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5092 
5093   // If we have computed a smaller type for the expression, update VecTy so
5094   // that the costs will be accurate.
5095   if (MinBWs.count(VL[0]))
5096     VecTy = FixedVectorType::get(
5097         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5098   unsigned EntryVF = E->getVectorFactor();
5099   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5100 
5101   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5102   // FIXME: it tries to fix a problem with MSVC buildbots.
5103   TargetTransformInfo &TTIRef = *TTI;
5104   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5105                                VectorizedVals, E](InstructionCost &Cost) {
5106     DenseMap<Value *, int> ExtractVectorsTys;
5107     SmallPtrSet<Value *, 4> CheckedExtracts;
5108     for (auto *V : VL) {
5109       if (isa<UndefValue>(V))
5110         continue;
5111       // If all users of instruction are going to be vectorized and this
5112       // instruction itself is not going to be vectorized, consider this
5113       // instruction as dead and remove its cost from the final cost of the
5114       // vectorized tree.
5115       // Also, avoid adjusting the cost for extractelements with multiple uses
5116       // in different graph entries.
5117       const TreeEntry *VE = getTreeEntry(V);
5118       if (!CheckedExtracts.insert(V).second ||
5119           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5120           (VE && VE != E))
5121         continue;
5122       auto *EE = cast<ExtractElementInst>(V);
5123       Optional<unsigned> EEIdx = getExtractIndex(EE);
5124       if (!EEIdx)
5125         continue;
5126       unsigned Idx = *EEIdx;
5127       if (TTIRef.getNumberOfParts(VecTy) !=
5128           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5129         auto It =
5130             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5131         It->getSecond() = std::min<int>(It->second, Idx);
5132       }
5133       // Take credit for instruction that will become dead.
5134       if (EE->hasOneUse()) {
5135         Instruction *Ext = EE->user_back();
5136         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5137             all_of(Ext->users(),
5138                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5139           // Use getExtractWithExtendCost() to calculate the cost of
5140           // extractelement/ext pair.
5141           Cost -=
5142               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5143                                               EE->getVectorOperandType(), Idx);
5144           // Add back the cost of s|zext which is subtracted separately.
5145           Cost += TTIRef.getCastInstrCost(
5146               Ext->getOpcode(), Ext->getType(), EE->getType(),
5147               TTI::getCastContextHint(Ext), CostKind, Ext);
5148           continue;
5149         }
5150       }
5151       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5152                                         EE->getVectorOperandType(), Idx);
5153     }
5154     // Add a cost for subvector extracts/inserts if required.
5155     for (const auto &Data : ExtractVectorsTys) {
5156       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5157       unsigned NumElts = VecTy->getNumElements();
5158       if (Data.second % NumElts == 0)
5159         continue;
5160       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5161         unsigned Idx = (Data.second / NumElts) * NumElts;
5162         unsigned EENumElts = EEVTy->getNumElements();
5163         if (Idx + NumElts <= EENumElts) {
5164           Cost +=
5165               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5166                                     EEVTy, None, Idx, VecTy);
5167         } else {
5168           // Need to round up the subvector type vectorization factor to avoid a
5169           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5170           // <= EENumElts.
5171           auto *SubVT =
5172               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5173           Cost +=
5174               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5175                                     EEVTy, None, Idx, SubVT);
5176         }
5177       } else {
5178         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5179                                       VecTy, None, 0, EEVTy);
5180       }
5181     }
5182   };
5183   if (E->State == TreeEntry::NeedToGather) {
5184     if (allConstant(VL))
5185       return 0;
5186     if (isa<InsertElementInst>(VL[0]))
5187       return InstructionCost::getInvalid();
5188     SmallVector<int> Mask;
5189     SmallVector<const TreeEntry *> Entries;
5190     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5191         isGatherShuffledEntry(E, Mask, Entries);
5192     if (Shuffle.hasValue()) {
5193       InstructionCost GatherCost = 0;
5194       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5195         // Perfect match in the graph, will reuse the previously vectorized
5196         // node. Cost is 0.
5197         LLVM_DEBUG(
5198             dbgs()
5199             << "SLP: perfect diamond match for gather bundle that starts with "
5200             << *VL.front() << ".\n");
5201         if (NeedToShuffleReuses)
5202           GatherCost =
5203               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5204                                   FinalVecTy, E->ReuseShuffleIndices);
5205       } else {
5206         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5207                           << " entries for bundle that starts with "
5208                           << *VL.front() << ".\n");
5209         // Detected that instead of gather we can emit a shuffle of single/two
5210         // previously vectorized nodes. Add the cost of the permutation rather
5211         // than gather.
5212         ::addMask(Mask, E->ReuseShuffleIndices);
5213         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5214       }
5215       return GatherCost;
5216     }
5217     if ((E->getOpcode() == Instruction::ExtractElement ||
5218          all_of(E->Scalars,
5219                 [](Value *V) {
5220                   return isa<ExtractElementInst, UndefValue>(V);
5221                 })) &&
5222         allSameType(VL)) {
5223       // Check that gather of extractelements can be represented as just a
5224       // shuffle of a single/two vectors the scalars are extracted from.
5225       SmallVector<int> Mask;
5226       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5227           isFixedVectorShuffle(VL, Mask);
5228       if (ShuffleKind.hasValue()) {
5229         // Found the bunch of extractelement instructions that must be gathered
5230         // into a vector and can be represented as a permutation elements in a
5231         // single input vector or of 2 input vectors.
5232         InstructionCost Cost =
5233             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5234         AdjustExtractsCost(Cost);
5235         if (NeedToShuffleReuses)
5236           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5237                                       FinalVecTy, E->ReuseShuffleIndices);
5238         return Cost;
5239       }
5240     }
5241     if (isSplat(VL)) {
5242       // Found the broadcasting of the single scalar, calculate the cost as the
5243       // broadcast.
5244       assert(VecTy == FinalVecTy &&
5245              "No reused scalars expected for broadcast.");
5246       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy,
5247                                  /*Mask=*/None, /*Index=*/0,
5248                                  /*SubTp=*/nullptr, /*Args=*/VL);
5249     }
5250     InstructionCost ReuseShuffleCost = 0;
5251     if (NeedToShuffleReuses)
5252       ReuseShuffleCost = TTI->getShuffleCost(
5253           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5254     // Improve gather cost for gather of loads, if we can group some of the
5255     // loads into vector loads.
5256     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5257         !E->isAltShuffle()) {
5258       BoUpSLP::ValueSet VectorizedLoads;
5259       unsigned StartIdx = 0;
5260       unsigned VF = VL.size() / 2;
5261       unsigned VectorizedCnt = 0;
5262       unsigned ScatterVectorizeCnt = 0;
5263       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5264       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5265         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5266              Cnt += VF) {
5267           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5268           if (!VectorizedLoads.count(Slice.front()) &&
5269               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5270             SmallVector<Value *> PointerOps;
5271             OrdersType CurrentOrder;
5272             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5273                                               *SE, CurrentOrder, PointerOps);
5274             switch (LS) {
5275             case LoadsState::Vectorize:
5276             case LoadsState::ScatterVectorize:
5277               // Mark the vectorized loads so that we don't vectorize them
5278               // again.
5279               if (LS == LoadsState::Vectorize)
5280                 ++VectorizedCnt;
5281               else
5282                 ++ScatterVectorizeCnt;
5283               VectorizedLoads.insert(Slice.begin(), Slice.end());
5284               // If we vectorized initial block, no need to try to vectorize it
5285               // again.
5286               if (Cnt == StartIdx)
5287                 StartIdx += VF;
5288               break;
5289             case LoadsState::Gather:
5290               break;
5291             }
5292           }
5293         }
5294         // Check if the whole array was vectorized already - exit.
5295         if (StartIdx >= VL.size())
5296           break;
5297         // Found vectorizable parts - exit.
5298         if (!VectorizedLoads.empty())
5299           break;
5300       }
5301       if (!VectorizedLoads.empty()) {
5302         InstructionCost GatherCost = 0;
5303         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5304         bool NeedInsertSubvectorAnalysis =
5305             !NumParts || (VL.size() / VF) > NumParts;
5306         // Get the cost for gathered loads.
5307         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5308           if (VectorizedLoads.contains(VL[I]))
5309             continue;
5310           GatherCost += getGatherCost(VL.slice(I, VF));
5311         }
5312         // The cost for vectorized loads.
5313         InstructionCost ScalarsCost = 0;
5314         for (Value *V : VectorizedLoads) {
5315           auto *LI = cast<LoadInst>(V);
5316           ScalarsCost += TTI->getMemoryOpCost(
5317               Instruction::Load, LI->getType(), LI->getAlign(),
5318               LI->getPointerAddressSpace(), CostKind, LI);
5319         }
5320         auto *LI = cast<LoadInst>(E->getMainOp());
5321         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5322         Align Alignment = LI->getAlign();
5323         GatherCost +=
5324             VectorizedCnt *
5325             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5326                                  LI->getPointerAddressSpace(), CostKind, LI);
5327         GatherCost += ScatterVectorizeCnt *
5328                       TTI->getGatherScatterOpCost(
5329                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5330                           /*VariableMask=*/false, Alignment, CostKind, LI);
5331         if (NeedInsertSubvectorAnalysis) {
5332           // Add the cost for the subvectors insert.
5333           for (int I = VF, E = VL.size(); I < E; I += VF)
5334             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5335                                               None, I, LoadTy);
5336         }
5337         return ReuseShuffleCost + GatherCost - ScalarsCost;
5338       }
5339     }
5340     return ReuseShuffleCost + getGatherCost(VL);
5341   }
5342   InstructionCost CommonCost = 0;
5343   SmallVector<int> Mask;
5344   if (!E->ReorderIndices.empty()) {
5345     SmallVector<int> NewMask;
5346     if (E->getOpcode() == Instruction::Store) {
5347       // For stores the order is actually a mask.
5348       NewMask.resize(E->ReorderIndices.size());
5349       copy(E->ReorderIndices, NewMask.begin());
5350     } else {
5351       inversePermutation(E->ReorderIndices, NewMask);
5352     }
5353     ::addMask(Mask, NewMask);
5354   }
5355   if (NeedToShuffleReuses)
5356     ::addMask(Mask, E->ReuseShuffleIndices);
5357   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5358     CommonCost =
5359         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5360   assert((E->State == TreeEntry::Vectorize ||
5361           E->State == TreeEntry::ScatterVectorize) &&
5362          "Unhandled state");
5363   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5364   Instruction *VL0 = E->getMainOp();
5365   unsigned ShuffleOrOp =
5366       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5367   switch (ShuffleOrOp) {
5368     case Instruction::PHI:
5369       return 0;
5370 
5371     case Instruction::ExtractValue:
5372     case Instruction::ExtractElement: {
5373       // The common cost of removal ExtractElement/ExtractValue instructions +
5374       // the cost of shuffles, if required to resuffle the original vector.
5375       if (NeedToShuffleReuses) {
5376         unsigned Idx = 0;
5377         for (unsigned I : E->ReuseShuffleIndices) {
5378           if (ShuffleOrOp == Instruction::ExtractElement) {
5379             auto *EE = cast<ExtractElementInst>(VL[I]);
5380             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5381                                                   EE->getVectorOperandType(),
5382                                                   *getExtractIndex(EE));
5383           } else {
5384             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5385                                                   VecTy, Idx);
5386             ++Idx;
5387           }
5388         }
5389         Idx = EntryVF;
5390         for (Value *V : VL) {
5391           if (ShuffleOrOp == Instruction::ExtractElement) {
5392             auto *EE = cast<ExtractElementInst>(V);
5393             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5394                                                   EE->getVectorOperandType(),
5395                                                   *getExtractIndex(EE));
5396           } else {
5397             --Idx;
5398             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5399                                                   VecTy, Idx);
5400           }
5401         }
5402       }
5403       if (ShuffleOrOp == Instruction::ExtractValue) {
5404         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5405           auto *EI = cast<Instruction>(VL[I]);
5406           // Take credit for instruction that will become dead.
5407           if (EI->hasOneUse()) {
5408             Instruction *Ext = EI->user_back();
5409             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5410                 all_of(Ext->users(),
5411                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5412               // Use getExtractWithExtendCost() to calculate the cost of
5413               // extractelement/ext pair.
5414               CommonCost -= TTI->getExtractWithExtendCost(
5415                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5416               // Add back the cost of s|zext which is subtracted separately.
5417               CommonCost += TTI->getCastInstrCost(
5418                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5419                   TTI::getCastContextHint(Ext), CostKind, Ext);
5420               continue;
5421             }
5422           }
5423           CommonCost -=
5424               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5425         }
5426       } else {
5427         AdjustExtractsCost(CommonCost);
5428       }
5429       return CommonCost;
5430     }
5431     case Instruction::InsertElement: {
5432       assert(E->ReuseShuffleIndices.empty() &&
5433              "Unique insertelements only are expected.");
5434       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5435 
5436       unsigned const NumElts = SrcVecTy->getNumElements();
5437       unsigned const NumScalars = VL.size();
5438       APInt DemandedElts = APInt::getZero(NumElts);
5439       // TODO: Add support for Instruction::InsertValue.
5440       SmallVector<int> Mask;
5441       if (!E->ReorderIndices.empty()) {
5442         inversePermutation(E->ReorderIndices, Mask);
5443         Mask.append(NumElts - NumScalars, UndefMaskElem);
5444       } else {
5445         Mask.assign(NumElts, UndefMaskElem);
5446         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5447       }
5448       unsigned Offset = *getInsertIndex(VL0);
5449       bool IsIdentity = true;
5450       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5451       Mask.swap(PrevMask);
5452       for (unsigned I = 0; I < NumScalars; ++I) {
5453         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5454         DemandedElts.setBit(InsertIdx);
5455         IsIdentity &= InsertIdx - Offset == I;
5456         Mask[InsertIdx - Offset] = I;
5457       }
5458       assert(Offset < NumElts && "Failed to find vector index offset");
5459 
5460       InstructionCost Cost = 0;
5461       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5462                                             /*Insert*/ true, /*Extract*/ false);
5463 
5464       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5465         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5466         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5467         Cost += TTI->getShuffleCost(
5468             TargetTransformInfo::SK_PermuteSingleSrc,
5469             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5470       } else if (!IsIdentity) {
5471         auto *FirstInsert =
5472             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5473               return !is_contained(E->Scalars,
5474                                    cast<Instruction>(V)->getOperand(0));
5475             }));
5476         if (isUndefVector(FirstInsert->getOperand(0))) {
5477           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5478         } else {
5479           SmallVector<int> InsertMask(NumElts);
5480           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5481           for (unsigned I = 0; I < NumElts; I++) {
5482             if (Mask[I] != UndefMaskElem)
5483               InsertMask[Offset + I] = NumElts + I;
5484           }
5485           Cost +=
5486               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5487         }
5488       }
5489 
5490       return Cost;
5491     }
5492     case Instruction::ZExt:
5493     case Instruction::SExt:
5494     case Instruction::FPToUI:
5495     case Instruction::FPToSI:
5496     case Instruction::FPExt:
5497     case Instruction::PtrToInt:
5498     case Instruction::IntToPtr:
5499     case Instruction::SIToFP:
5500     case Instruction::UIToFP:
5501     case Instruction::Trunc:
5502     case Instruction::FPTrunc:
5503     case Instruction::BitCast: {
5504       Type *SrcTy = VL0->getOperand(0)->getType();
5505       InstructionCost ScalarEltCost =
5506           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5507                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5508       if (NeedToShuffleReuses) {
5509         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5510       }
5511 
5512       // Calculate the cost of this instruction.
5513       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5514 
5515       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5516       InstructionCost VecCost = 0;
5517       // Check if the values are candidates to demote.
5518       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5519         VecCost = CommonCost + TTI->getCastInstrCost(
5520                                    E->getOpcode(), VecTy, SrcVecTy,
5521                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5522       }
5523       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5524       return VecCost - ScalarCost;
5525     }
5526     case Instruction::FCmp:
5527     case Instruction::ICmp:
5528     case Instruction::Select: {
5529       // Calculate the cost of this instruction.
5530       InstructionCost ScalarEltCost =
5531           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5532                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5533       if (NeedToShuffleReuses) {
5534         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5535       }
5536       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5537       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5538 
5539       // Check if all entries in VL are either compares or selects with compares
5540       // as condition that have the same predicates.
5541       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5542       bool First = true;
5543       for (auto *V : VL) {
5544         CmpInst::Predicate CurrentPred;
5545         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5546         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5547              !match(V, MatchCmp)) ||
5548             (!First && VecPred != CurrentPred)) {
5549           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5550           break;
5551         }
5552         First = false;
5553         VecPred = CurrentPred;
5554       }
5555 
5556       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5557           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5558       // Check if it is possible and profitable to use min/max for selects in
5559       // VL.
5560       //
5561       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5562       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5563         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5564                                           {VecTy, VecTy});
5565         InstructionCost IntrinsicCost =
5566             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5567         // If the selects are the only uses of the compares, they will be dead
5568         // and we can adjust the cost by removing their cost.
5569         if (IntrinsicAndUse.second)
5570           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5571                                                    MaskTy, VecPred, CostKind);
5572         VecCost = std::min(VecCost, IntrinsicCost);
5573       }
5574       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5575       return CommonCost + VecCost - ScalarCost;
5576     }
5577     case Instruction::FNeg:
5578     case Instruction::Add:
5579     case Instruction::FAdd:
5580     case Instruction::Sub:
5581     case Instruction::FSub:
5582     case Instruction::Mul:
5583     case Instruction::FMul:
5584     case Instruction::UDiv:
5585     case Instruction::SDiv:
5586     case Instruction::FDiv:
5587     case Instruction::URem:
5588     case Instruction::SRem:
5589     case Instruction::FRem:
5590     case Instruction::Shl:
5591     case Instruction::LShr:
5592     case Instruction::AShr:
5593     case Instruction::And:
5594     case Instruction::Or:
5595     case Instruction::Xor: {
5596       // Certain instructions can be cheaper to vectorize if they have a
5597       // constant second vector operand.
5598       TargetTransformInfo::OperandValueKind Op1VK =
5599           TargetTransformInfo::OK_AnyValue;
5600       TargetTransformInfo::OperandValueKind Op2VK =
5601           TargetTransformInfo::OK_UniformConstantValue;
5602       TargetTransformInfo::OperandValueProperties Op1VP =
5603           TargetTransformInfo::OP_None;
5604       TargetTransformInfo::OperandValueProperties Op2VP =
5605           TargetTransformInfo::OP_PowerOf2;
5606 
5607       // If all operands are exactly the same ConstantInt then set the
5608       // operand kind to OK_UniformConstantValue.
5609       // If instead not all operands are constants, then set the operand kind
5610       // to OK_AnyValue. If all operands are constants but not the same,
5611       // then set the operand kind to OK_NonUniformConstantValue.
5612       ConstantInt *CInt0 = nullptr;
5613       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5614         const Instruction *I = cast<Instruction>(VL[i]);
5615         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5616         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5617         if (!CInt) {
5618           Op2VK = TargetTransformInfo::OK_AnyValue;
5619           Op2VP = TargetTransformInfo::OP_None;
5620           break;
5621         }
5622         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5623             !CInt->getValue().isPowerOf2())
5624           Op2VP = TargetTransformInfo::OP_None;
5625         if (i == 0) {
5626           CInt0 = CInt;
5627           continue;
5628         }
5629         if (CInt0 != CInt)
5630           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5631       }
5632 
5633       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5634       InstructionCost ScalarEltCost =
5635           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5636                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5637       if (NeedToShuffleReuses) {
5638         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5639       }
5640       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5641       InstructionCost VecCost =
5642           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5643                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5644       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5645       return CommonCost + VecCost - ScalarCost;
5646     }
5647     case Instruction::GetElementPtr: {
5648       TargetTransformInfo::OperandValueKind Op1VK =
5649           TargetTransformInfo::OK_AnyValue;
5650       TargetTransformInfo::OperandValueKind Op2VK =
5651           TargetTransformInfo::OK_UniformConstantValue;
5652 
5653       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5654           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5655       if (NeedToShuffleReuses) {
5656         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5657       }
5658       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5659       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5660           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5661       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5662       return CommonCost + VecCost - ScalarCost;
5663     }
5664     case Instruction::Load: {
5665       // Cost of wide load - cost of scalar loads.
5666       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5667       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5668           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5669       if (NeedToShuffleReuses) {
5670         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5671       }
5672       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5673       InstructionCost VecLdCost;
5674       if (E->State == TreeEntry::Vectorize) {
5675         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5676                                          CostKind, VL0);
5677       } else {
5678         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5679         Align CommonAlignment = Alignment;
5680         for (Value *V : VL)
5681           CommonAlignment =
5682               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5683         VecLdCost = TTI->getGatherScatterOpCost(
5684             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5685             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5686       }
5687       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5688       return CommonCost + VecLdCost - ScalarLdCost;
5689     }
5690     case Instruction::Store: {
5691       // We know that we can merge the stores. Calculate the cost.
5692       bool IsReorder = !E->ReorderIndices.empty();
5693       auto *SI =
5694           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5695       Align Alignment = SI->getAlign();
5696       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5697           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5698       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5699       InstructionCost VecStCost = TTI->getMemoryOpCost(
5700           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5701       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5702       return CommonCost + VecStCost - ScalarStCost;
5703     }
5704     case Instruction::Call: {
5705       CallInst *CI = cast<CallInst>(VL0);
5706       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5707 
5708       // Calculate the cost of the scalar and vector calls.
5709       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5710       InstructionCost ScalarEltCost =
5711           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5712       if (NeedToShuffleReuses) {
5713         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5714       }
5715       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5716 
5717       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5718       InstructionCost VecCallCost =
5719           std::min(VecCallCosts.first, VecCallCosts.second);
5720 
5721       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5722                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5723                         << " for " << *CI << "\n");
5724 
5725       return CommonCost + VecCallCost - ScalarCallCost;
5726     }
5727     case Instruction::ShuffleVector: {
5728       assert(E->isAltShuffle() &&
5729              ((Instruction::isBinaryOp(E->getOpcode()) &&
5730                Instruction::isBinaryOp(E->getAltOpcode())) ||
5731               (Instruction::isCast(E->getOpcode()) &&
5732                Instruction::isCast(E->getAltOpcode())) ||
5733               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5734              "Invalid Shuffle Vector Operand");
5735       InstructionCost ScalarCost = 0;
5736       if (NeedToShuffleReuses) {
5737         for (unsigned Idx : E->ReuseShuffleIndices) {
5738           Instruction *I = cast<Instruction>(VL[Idx]);
5739           CommonCost -= TTI->getInstructionCost(I, CostKind);
5740         }
5741         for (Value *V : VL) {
5742           Instruction *I = cast<Instruction>(V);
5743           CommonCost += TTI->getInstructionCost(I, CostKind);
5744         }
5745       }
5746       for (Value *V : VL) {
5747         Instruction *I = cast<Instruction>(V);
5748         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5749         ScalarCost += TTI->getInstructionCost(I, CostKind);
5750       }
5751       // VecCost is equal to sum of the cost of creating 2 vectors
5752       // and the cost of creating shuffle.
5753       InstructionCost VecCost = 0;
5754       // Try to find the previous shuffle node with the same operands and same
5755       // main/alternate ops.
5756       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5757         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5758           if (TE.get() == E)
5759             break;
5760           if (TE->isAltShuffle() &&
5761               ((TE->getOpcode() == E->getOpcode() &&
5762                 TE->getAltOpcode() == E->getAltOpcode()) ||
5763                (TE->getOpcode() == E->getAltOpcode() &&
5764                 TE->getAltOpcode() == E->getOpcode())) &&
5765               TE->hasEqualOperands(*E))
5766             return true;
5767         }
5768         return false;
5769       };
5770       if (TryFindNodeWithEqualOperands()) {
5771         LLVM_DEBUG({
5772           dbgs() << "SLP: diamond match for alternate node found.\n";
5773           E->dump();
5774         });
5775         // No need to add new vector costs here since we're going to reuse
5776         // same main/alternate vector ops, just do different shuffling.
5777       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5778         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5779         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5780                                                CostKind);
5781       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5782         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5783                                           Builder.getInt1Ty(),
5784                                           CI0->getPredicate(), CostKind, VL0);
5785         VecCost += TTI->getCmpSelInstrCost(
5786             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5787             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5788             E->getAltOp());
5789       } else {
5790         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5791         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5792         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5793         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5794         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5795                                         TTI::CastContextHint::None, CostKind);
5796         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5797                                          TTI::CastContextHint::None, CostKind);
5798       }
5799 
5800       SmallVector<int> Mask;
5801       buildShuffleEntryMask(
5802           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5803           [E](Instruction *I) {
5804             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5805             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5806           },
5807           Mask);
5808       CommonCost =
5809           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5810       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5811       return CommonCost + VecCost - ScalarCost;
5812     }
5813     default:
5814       llvm_unreachable("Unknown instruction");
5815   }
5816 }
5817 
5818 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5819   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5820                     << VectorizableTree.size() << " is fully vectorizable .\n");
5821 
5822   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5823     SmallVector<int> Mask;
5824     return TE->State == TreeEntry::NeedToGather &&
5825            !any_of(TE->Scalars,
5826                    [this](Value *V) { return EphValues.contains(V); }) &&
5827            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5828             TE->Scalars.size() < Limit ||
5829             ((TE->getOpcode() == Instruction::ExtractElement ||
5830               all_of(TE->Scalars,
5831                      [](Value *V) {
5832                        return isa<ExtractElementInst, UndefValue>(V);
5833                      })) &&
5834              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5835             (TE->State == TreeEntry::NeedToGather &&
5836              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5837   };
5838 
5839   // We only handle trees of heights 1 and 2.
5840   if (VectorizableTree.size() == 1 &&
5841       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5842        (ForReduction &&
5843         AreVectorizableGathers(VectorizableTree[0].get(),
5844                                VectorizableTree[0]->Scalars.size()) &&
5845         VectorizableTree[0]->getVectorFactor() > 2)))
5846     return true;
5847 
5848   if (VectorizableTree.size() != 2)
5849     return false;
5850 
5851   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5852   // with the second gather nodes if they have less scalar operands rather than
5853   // the initial tree element (may be profitable to shuffle the second gather)
5854   // or they are extractelements, which form shuffle.
5855   SmallVector<int> Mask;
5856   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5857       AreVectorizableGathers(VectorizableTree[1].get(),
5858                              VectorizableTree[0]->Scalars.size()))
5859     return true;
5860 
5861   // Gathering cost would be too much for tiny trees.
5862   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5863       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5864        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5865     return false;
5866 
5867   return true;
5868 }
5869 
5870 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5871                                        TargetTransformInfo *TTI,
5872                                        bool MustMatchOrInst) {
5873   // Look past the root to find a source value. Arbitrarily follow the
5874   // path through operand 0 of any 'or'. Also, peek through optional
5875   // shift-left-by-multiple-of-8-bits.
5876   Value *ZextLoad = Root;
5877   const APInt *ShAmtC;
5878   bool FoundOr = false;
5879   while (!isa<ConstantExpr>(ZextLoad) &&
5880          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5881           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5882            ShAmtC->urem(8) == 0))) {
5883     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5884     ZextLoad = BinOp->getOperand(0);
5885     if (BinOp->getOpcode() == Instruction::Or)
5886       FoundOr = true;
5887   }
5888   // Check if the input is an extended load of the required or/shift expression.
5889   Value *Load;
5890   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5891       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5892     return false;
5893 
5894   // Require that the total load bit width is a legal integer type.
5895   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5896   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5897   Type *SrcTy = Load->getType();
5898   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5899   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5900     return false;
5901 
5902   // Everything matched - assume that we can fold the whole sequence using
5903   // load combining.
5904   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5905              << *(cast<Instruction>(Root)) << "\n");
5906 
5907   return true;
5908 }
5909 
5910 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5911   if (RdxKind != RecurKind::Or)
5912     return false;
5913 
5914   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5915   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5916   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5917                                     /* MatchOr */ false);
5918 }
5919 
5920 bool BoUpSLP::isLoadCombineCandidate() const {
5921   // Peek through a final sequence of stores and check if all operations are
5922   // likely to be load-combined.
5923   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5924   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5925     Value *X;
5926     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5927         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5928       return false;
5929   }
5930   return true;
5931 }
5932 
5933 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5934   // No need to vectorize inserts of gathered values.
5935   if (VectorizableTree.size() == 2 &&
5936       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5937       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5938     return true;
5939 
5940   // We can vectorize the tree if its size is greater than or equal to the
5941   // minimum size specified by the MinTreeSize command line option.
5942   if (VectorizableTree.size() >= MinTreeSize)
5943     return false;
5944 
5945   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5946   // can vectorize it if we can prove it fully vectorizable.
5947   if (isFullyVectorizableTinyTree(ForReduction))
5948     return false;
5949 
5950   assert(VectorizableTree.empty()
5951              ? ExternalUses.empty()
5952              : true && "We shouldn't have any external users");
5953 
5954   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5955   // vectorizable.
5956   return true;
5957 }
5958 
5959 InstructionCost BoUpSLP::getSpillCost() const {
5960   // Walk from the bottom of the tree to the top, tracking which values are
5961   // live. When we see a call instruction that is not part of our tree,
5962   // query TTI to see if there is a cost to keeping values live over it
5963   // (for example, if spills and fills are required).
5964   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5965   InstructionCost Cost = 0;
5966 
5967   SmallPtrSet<Instruction*, 4> LiveValues;
5968   Instruction *PrevInst = nullptr;
5969 
5970   // The entries in VectorizableTree are not necessarily ordered by their
5971   // position in basic blocks. Collect them and order them by dominance so later
5972   // instructions are guaranteed to be visited first. For instructions in
5973   // different basic blocks, we only scan to the beginning of the block, so
5974   // their order does not matter, as long as all instructions in a basic block
5975   // are grouped together. Using dominance ensures a deterministic order.
5976   SmallVector<Instruction *, 16> OrderedScalars;
5977   for (const auto &TEPtr : VectorizableTree) {
5978     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5979     if (!Inst)
5980       continue;
5981     OrderedScalars.push_back(Inst);
5982   }
5983   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5984     auto *NodeA = DT->getNode(A->getParent());
5985     auto *NodeB = DT->getNode(B->getParent());
5986     assert(NodeA && "Should only process reachable instructions");
5987     assert(NodeB && "Should only process reachable instructions");
5988     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5989            "Different nodes should have different DFS numbers");
5990     if (NodeA != NodeB)
5991       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5992     return B->comesBefore(A);
5993   });
5994 
5995   for (Instruction *Inst : OrderedScalars) {
5996     if (!PrevInst) {
5997       PrevInst = Inst;
5998       continue;
5999     }
6000 
6001     // Update LiveValues.
6002     LiveValues.erase(PrevInst);
6003     for (auto &J : PrevInst->operands()) {
6004       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6005         LiveValues.insert(cast<Instruction>(&*J));
6006     }
6007 
6008     LLVM_DEBUG({
6009       dbgs() << "SLP: #LV: " << LiveValues.size();
6010       for (auto *X : LiveValues)
6011         dbgs() << " " << X->getName();
6012       dbgs() << ", Looking at ";
6013       Inst->dump();
6014     });
6015 
6016     // Now find the sequence of instructions between PrevInst and Inst.
6017     unsigned NumCalls = 0;
6018     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6019                                  PrevInstIt =
6020                                      PrevInst->getIterator().getReverse();
6021     while (InstIt != PrevInstIt) {
6022       if (PrevInstIt == PrevInst->getParent()->rend()) {
6023         PrevInstIt = Inst->getParent()->rbegin();
6024         continue;
6025       }
6026 
6027       // Debug information does not impact spill cost.
6028       if ((isa<CallInst>(&*PrevInstIt) &&
6029            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6030           &*PrevInstIt != PrevInst)
6031         NumCalls++;
6032 
6033       ++PrevInstIt;
6034     }
6035 
6036     if (NumCalls) {
6037       SmallVector<Type*, 4> V;
6038       for (auto *II : LiveValues) {
6039         auto *ScalarTy = II->getType();
6040         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6041           ScalarTy = VectorTy->getElementType();
6042         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6043       }
6044       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6045     }
6046 
6047     PrevInst = Inst;
6048   }
6049 
6050   return Cost;
6051 }
6052 
6053 /// Check if two insertelement instructions are from the same buildvector.
6054 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6055                                             InsertElementInst *V) {
6056   // Instructions must be from the same basic blocks.
6057   if (VU->getParent() != V->getParent())
6058     return false;
6059   // Checks if 2 insertelements are from the same buildvector.
6060   if (VU->getType() != V->getType())
6061     return false;
6062   // Multiple used inserts are separate nodes.
6063   if (!VU->hasOneUse() && !V->hasOneUse())
6064     return false;
6065   auto *IE1 = VU;
6066   auto *IE2 = V;
6067   // Go through the vector operand of insertelement instructions trying to find
6068   // either VU as the original vector for IE2 or V as the original vector for
6069   // IE1.
6070   do {
6071     if (IE2 == VU || IE1 == V)
6072       return true;
6073     if (IE1) {
6074       if (IE1 != VU && !IE1->hasOneUse())
6075         IE1 = nullptr;
6076       else
6077         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6078     }
6079     if (IE2) {
6080       if (IE2 != V && !IE2->hasOneUse())
6081         IE2 = nullptr;
6082       else
6083         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6084     }
6085   } while (IE1 || IE2);
6086   return false;
6087 }
6088 
6089 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6090   InstructionCost Cost = 0;
6091   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6092                     << VectorizableTree.size() << ".\n");
6093 
6094   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6095 
6096   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6097     TreeEntry &TE = *VectorizableTree[I];
6098 
6099     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6100     Cost += C;
6101     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6102                       << " for bundle that starts with " << *TE.Scalars[0]
6103                       << ".\n"
6104                       << "SLP: Current total cost = " << Cost << "\n");
6105   }
6106 
6107   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6108   InstructionCost ExtractCost = 0;
6109   SmallVector<unsigned> VF;
6110   SmallVector<SmallVector<int>> ShuffleMask;
6111   SmallVector<Value *> FirstUsers;
6112   SmallVector<APInt> DemandedElts;
6113   for (ExternalUser &EU : ExternalUses) {
6114     // We only add extract cost once for the same scalar.
6115     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6116         !ExtractCostCalculated.insert(EU.Scalar).second)
6117       continue;
6118 
6119     // Uses by ephemeral values are free (because the ephemeral value will be
6120     // removed prior to code generation, and so the extraction will be
6121     // removed as well).
6122     if (EphValues.count(EU.User))
6123       continue;
6124 
6125     // No extract cost for vector "scalar"
6126     if (isa<FixedVectorType>(EU.Scalar->getType()))
6127       continue;
6128 
6129     // Already counted the cost for external uses when tried to adjust the cost
6130     // for extractelements, no need to add it again.
6131     if (isa<ExtractElementInst>(EU.Scalar))
6132       continue;
6133 
6134     // If found user is an insertelement, do not calculate extract cost but try
6135     // to detect it as a final shuffled/identity match.
6136     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6137       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6138         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6139         if (InsertIdx) {
6140           auto *It = find_if(FirstUsers, [VU](Value *V) {
6141             return areTwoInsertFromSameBuildVector(VU,
6142                                                    cast<InsertElementInst>(V));
6143           });
6144           int VecId = -1;
6145           if (It == FirstUsers.end()) {
6146             VF.push_back(FTy->getNumElements());
6147             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6148             // Find the insertvector, vectorized in tree, if any.
6149             Value *Base = VU;
6150             while (isa<InsertElementInst>(Base)) {
6151               // Build the mask for the vectorized insertelement instructions.
6152               if (const TreeEntry *E = getTreeEntry(Base)) {
6153                 VU = cast<InsertElementInst>(Base);
6154                 do {
6155                   int Idx = E->findLaneForValue(Base);
6156                   ShuffleMask.back()[Idx] = Idx;
6157                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6158                 } while (E == getTreeEntry(Base));
6159                 break;
6160               }
6161               Base = cast<InsertElementInst>(Base)->getOperand(0);
6162             }
6163             FirstUsers.push_back(VU);
6164             DemandedElts.push_back(APInt::getZero(VF.back()));
6165             VecId = FirstUsers.size() - 1;
6166           } else {
6167             VecId = std::distance(FirstUsers.begin(), It);
6168           }
6169           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6170           DemandedElts[VecId].setBit(*InsertIdx);
6171           continue;
6172         }
6173       }
6174     }
6175 
6176     // If we plan to rewrite the tree in a smaller type, we will need to sign
6177     // extend the extracted value back to the original type. Here, we account
6178     // for the extract and the added cost of the sign extend if needed.
6179     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6180     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6181     if (MinBWs.count(ScalarRoot)) {
6182       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6183       auto Extend =
6184           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6185       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6186       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6187                                                    VecTy, EU.Lane);
6188     } else {
6189       ExtractCost +=
6190           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6191     }
6192   }
6193 
6194   InstructionCost SpillCost = getSpillCost();
6195   Cost += SpillCost + ExtractCost;
6196   if (FirstUsers.size() == 1) {
6197     int Limit = ShuffleMask.front().size() * 2;
6198     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6199         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6200       InstructionCost C = TTI->getShuffleCost(
6201           TTI::SK_PermuteSingleSrc,
6202           cast<FixedVectorType>(FirstUsers.front()->getType()),
6203           ShuffleMask.front());
6204       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6205                         << " for final shuffle of insertelement external users "
6206                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6207                         << "SLP: Current total cost = " << Cost << "\n");
6208       Cost += C;
6209     }
6210     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6211         cast<FixedVectorType>(FirstUsers.front()->getType()),
6212         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6213     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6214                       << " for insertelements gather.\n"
6215                       << "SLP: Current total cost = " << Cost << "\n");
6216     Cost -= InsertCost;
6217   } else if (FirstUsers.size() >= 2) {
6218     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6219     // Combined masks of the first 2 vectors.
6220     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6221     copy(ShuffleMask.front(), CombinedMask.begin());
6222     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6223     auto *VecTy = FixedVectorType::get(
6224         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6225         MaxVF);
6226     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6227       if (ShuffleMask[1][I] != UndefMaskElem) {
6228         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6229         CombinedDemandedElts.setBit(I);
6230       }
6231     }
6232     InstructionCost C =
6233         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6234     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6235                       << " for final shuffle of vector node and external "
6236                          "insertelement users "
6237                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6238                       << "SLP: Current total cost = " << Cost << "\n");
6239     Cost += C;
6240     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6241         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6242     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6243                       << " for insertelements gather.\n"
6244                       << "SLP: Current total cost = " << Cost << "\n");
6245     Cost -= InsertCost;
6246     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6247       // Other elements - permutation of 2 vectors (the initial one and the
6248       // next Ith incoming vector).
6249       unsigned VF = ShuffleMask[I].size();
6250       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6251         int Mask = ShuffleMask[I][Idx];
6252         if (Mask != UndefMaskElem)
6253           CombinedMask[Idx] = MaxVF + Mask;
6254         else if (CombinedMask[Idx] != UndefMaskElem)
6255           CombinedMask[Idx] = Idx;
6256       }
6257       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6258         if (CombinedMask[Idx] != UndefMaskElem)
6259           CombinedMask[Idx] = Idx;
6260       InstructionCost C =
6261           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6262       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6263                         << " for final shuffle of vector node and external "
6264                            "insertelement users "
6265                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6266                         << "SLP: Current total cost = " << Cost << "\n");
6267       Cost += C;
6268       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6269           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6270           /*Insert*/ true, /*Extract*/ false);
6271       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6272                         << " for insertelements gather.\n"
6273                         << "SLP: Current total cost = " << Cost << "\n");
6274       Cost -= InsertCost;
6275     }
6276   }
6277 
6278 #ifndef NDEBUG
6279   SmallString<256> Str;
6280   {
6281     raw_svector_ostream OS(Str);
6282     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6283        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6284        << "SLP: Total Cost = " << Cost << ".\n";
6285   }
6286   LLVM_DEBUG(dbgs() << Str);
6287   if (ViewSLPTree)
6288     ViewGraph(this, "SLP" + F->getName(), false, Str);
6289 #endif
6290 
6291   return Cost;
6292 }
6293 
6294 Optional<TargetTransformInfo::ShuffleKind>
6295 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6296                                SmallVectorImpl<const TreeEntry *> &Entries) {
6297   // TODO: currently checking only for Scalars in the tree entry, need to count
6298   // reused elements too for better cost estimation.
6299   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6300   Entries.clear();
6301   // Build a lists of values to tree entries.
6302   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6303   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6304     if (EntryPtr.get() == TE)
6305       break;
6306     if (EntryPtr->State != TreeEntry::NeedToGather)
6307       continue;
6308     for (Value *V : EntryPtr->Scalars)
6309       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6310   }
6311   // Find all tree entries used by the gathered values. If no common entries
6312   // found - not a shuffle.
6313   // Here we build a set of tree nodes for each gathered value and trying to
6314   // find the intersection between these sets. If we have at least one common
6315   // tree node for each gathered value - we have just a permutation of the
6316   // single vector. If we have 2 different sets, we're in situation where we
6317   // have a permutation of 2 input vectors.
6318   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6319   DenseMap<Value *, int> UsedValuesEntry;
6320   for (Value *V : TE->Scalars) {
6321     if (isa<UndefValue>(V))
6322       continue;
6323     // Build a list of tree entries where V is used.
6324     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6325     auto It = ValueToTEs.find(V);
6326     if (It != ValueToTEs.end())
6327       VToTEs = It->second;
6328     if (const TreeEntry *VTE = getTreeEntry(V))
6329       VToTEs.insert(VTE);
6330     if (VToTEs.empty())
6331       return None;
6332     if (UsedTEs.empty()) {
6333       // The first iteration, just insert the list of nodes to vector.
6334       UsedTEs.push_back(VToTEs);
6335     } else {
6336       // Need to check if there are any previously used tree nodes which use V.
6337       // If there are no such nodes, consider that we have another one input
6338       // vector.
6339       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6340       unsigned Idx = 0;
6341       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6342         // Do we have a non-empty intersection of previously listed tree entries
6343         // and tree entries using current V?
6344         set_intersect(VToTEs, Set);
6345         if (!VToTEs.empty()) {
6346           // Yes, write the new subset and continue analysis for the next
6347           // scalar.
6348           Set.swap(VToTEs);
6349           break;
6350         }
6351         VToTEs = SavedVToTEs;
6352         ++Idx;
6353       }
6354       // No non-empty intersection found - need to add a second set of possible
6355       // source vectors.
6356       if (Idx == UsedTEs.size()) {
6357         // If the number of input vectors is greater than 2 - not a permutation,
6358         // fallback to the regular gather.
6359         if (UsedTEs.size() == 2)
6360           return None;
6361         UsedTEs.push_back(SavedVToTEs);
6362         Idx = UsedTEs.size() - 1;
6363       }
6364       UsedValuesEntry.try_emplace(V, Idx);
6365     }
6366   }
6367 
6368   unsigned VF = 0;
6369   if (UsedTEs.size() == 1) {
6370     // Try to find the perfect match in another gather node at first.
6371     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6372       return EntryPtr->isSame(TE->Scalars);
6373     });
6374     if (It != UsedTEs.front().end()) {
6375       Entries.push_back(*It);
6376       std::iota(Mask.begin(), Mask.end(), 0);
6377       return TargetTransformInfo::SK_PermuteSingleSrc;
6378     }
6379     // No perfect match, just shuffle, so choose the first tree node.
6380     Entries.push_back(*UsedTEs.front().begin());
6381   } else {
6382     // Try to find nodes with the same vector factor.
6383     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6384     DenseMap<int, const TreeEntry *> VFToTE;
6385     for (const TreeEntry *TE : UsedTEs.front())
6386       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6387     for (const TreeEntry *TE : UsedTEs.back()) {
6388       auto It = VFToTE.find(TE->getVectorFactor());
6389       if (It != VFToTE.end()) {
6390         VF = It->first;
6391         Entries.push_back(It->second);
6392         Entries.push_back(TE);
6393         break;
6394       }
6395     }
6396     // No 2 source vectors with the same vector factor - give up and do regular
6397     // gather.
6398     if (Entries.empty())
6399       return None;
6400   }
6401 
6402   // Build a shuffle mask for better cost estimation and vector emission.
6403   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6404     Value *V = TE->Scalars[I];
6405     if (isa<UndefValue>(V))
6406       continue;
6407     unsigned Idx = UsedValuesEntry.lookup(V);
6408     const TreeEntry *VTE = Entries[Idx];
6409     int FoundLane = VTE->findLaneForValue(V);
6410     Mask[I] = Idx * VF + FoundLane;
6411     // Extra check required by isSingleSourceMaskImpl function (called by
6412     // ShuffleVectorInst::isSingleSourceMask).
6413     if (Mask[I] >= 2 * E)
6414       return None;
6415   }
6416   switch (Entries.size()) {
6417   case 1:
6418     return TargetTransformInfo::SK_PermuteSingleSrc;
6419   case 2:
6420     return TargetTransformInfo::SK_PermuteTwoSrc;
6421   default:
6422     break;
6423   }
6424   return None;
6425 }
6426 
6427 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6428                                        const APInt &ShuffledIndices,
6429                                        bool NeedToShuffle) const {
6430   InstructionCost Cost =
6431       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6432                                     /*Extract*/ false);
6433   if (NeedToShuffle)
6434     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6435   return Cost;
6436 }
6437 
6438 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6439   // Find the type of the operands in VL.
6440   Type *ScalarTy = VL[0]->getType();
6441   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6442     ScalarTy = SI->getValueOperand()->getType();
6443   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6444   bool DuplicateNonConst = false;
6445   // Find the cost of inserting/extracting values from the vector.
6446   // Check if the same elements are inserted several times and count them as
6447   // shuffle candidates.
6448   APInt ShuffledElements = APInt::getZero(VL.size());
6449   DenseSet<Value *> UniqueElements;
6450   // Iterate in reverse order to consider insert elements with the high cost.
6451   for (unsigned I = VL.size(); I > 0; --I) {
6452     unsigned Idx = I - 1;
6453     // No need to shuffle duplicates for constants.
6454     if (isConstant(VL[Idx])) {
6455       ShuffledElements.setBit(Idx);
6456       continue;
6457     }
6458     if (!UniqueElements.insert(VL[Idx]).second) {
6459       DuplicateNonConst = true;
6460       ShuffledElements.setBit(Idx);
6461     }
6462   }
6463   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6464 }
6465 
6466 // Perform operand reordering on the instructions in VL and return the reordered
6467 // operands in Left and Right.
6468 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6469                                              SmallVectorImpl<Value *> &Left,
6470                                              SmallVectorImpl<Value *> &Right,
6471                                              const DataLayout &DL,
6472                                              ScalarEvolution &SE,
6473                                              const BoUpSLP &R) {
6474   if (VL.empty())
6475     return;
6476   VLOperands Ops(VL, DL, SE, R);
6477   // Reorder the operands in place.
6478   Ops.reorder();
6479   Left = Ops.getVL(0);
6480   Right = Ops.getVL(1);
6481 }
6482 
6483 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6484   // Get the basic block this bundle is in. All instructions in the bundle
6485   // should be in this block.
6486   auto *Front = E->getMainOp();
6487   auto *BB = Front->getParent();
6488   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6489     auto *I = cast<Instruction>(V);
6490     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6491   }));
6492 
6493   auto &&FindLastInst = [E, Front]() {
6494     Instruction *LastInst = Front;
6495     for (Value *V : E->Scalars) {
6496       auto *I = dyn_cast<Instruction>(V);
6497       if (!I)
6498         continue;
6499       if (LastInst->comesBefore(I))
6500         LastInst = I;
6501     }
6502     return LastInst;
6503   };
6504 
6505   auto &&FindFirstInst = [E, Front]() {
6506     Instruction *FirstInst = Front;
6507     for (Value *V : E->Scalars) {
6508       auto *I = dyn_cast<Instruction>(V);
6509       if (!I)
6510         continue;
6511       if (I->comesBefore(FirstInst))
6512         FirstInst = I;
6513     }
6514     return FirstInst;
6515   };
6516 
6517   // Set the insert point to the beginning of the basic block if the entry
6518   // should not be scheduled.
6519   if (E->State != TreeEntry::NeedToGather &&
6520       doesNotNeedToSchedule(E->Scalars)) {
6521     BasicBlock::iterator InsertPt;
6522     if (all_of(E->Scalars, isUsedOutsideBlock))
6523       InsertPt = FindLastInst()->getIterator();
6524     else
6525       InsertPt = FindFirstInst()->getIterator();
6526     Builder.SetInsertPoint(BB, InsertPt);
6527     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6528     return;
6529   }
6530 
6531   // The last instruction in the bundle in program order.
6532   Instruction *LastInst = nullptr;
6533 
6534   // Find the last instruction. The common case should be that BB has been
6535   // scheduled, and the last instruction is VL.back(). So we start with
6536   // VL.back() and iterate over schedule data until we reach the end of the
6537   // bundle. The end of the bundle is marked by null ScheduleData.
6538   if (BlocksSchedules.count(BB)) {
6539     Value *V = E->isOneOf(E->Scalars.back());
6540     if (doesNotNeedToBeScheduled(V))
6541       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6542     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6543     if (Bundle && Bundle->isPartOfBundle())
6544       for (; Bundle; Bundle = Bundle->NextInBundle)
6545         if (Bundle->OpValue == Bundle->Inst)
6546           LastInst = Bundle->Inst;
6547   }
6548 
6549   // LastInst can still be null at this point if there's either not an entry
6550   // for BB in BlocksSchedules or there's no ScheduleData available for
6551   // VL.back(). This can be the case if buildTree_rec aborts for various
6552   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6553   // size is reached, etc.). ScheduleData is initialized in the scheduling
6554   // "dry-run".
6555   //
6556   // If this happens, we can still find the last instruction by brute force. We
6557   // iterate forwards from Front (inclusive) until we either see all
6558   // instructions in the bundle or reach the end of the block. If Front is the
6559   // last instruction in program order, LastInst will be set to Front, and we
6560   // will visit all the remaining instructions in the block.
6561   //
6562   // One of the reasons we exit early from buildTree_rec is to place an upper
6563   // bound on compile-time. Thus, taking an additional compile-time hit here is
6564   // not ideal. However, this should be exceedingly rare since it requires that
6565   // we both exit early from buildTree_rec and that the bundle be out-of-order
6566   // (causing us to iterate all the way to the end of the block).
6567   if (!LastInst)
6568     LastInst = FindLastInst();
6569   assert(LastInst && "Failed to find last instruction in bundle");
6570 
6571   // Set the insertion point after the last instruction in the bundle. Set the
6572   // debug location to Front.
6573   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6574   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6575 }
6576 
6577 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6578   // List of instructions/lanes from current block and/or the blocks which are
6579   // part of the current loop. These instructions will be inserted at the end to
6580   // make it possible to optimize loops and hoist invariant instructions out of
6581   // the loops body with better chances for success.
6582   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6583   SmallSet<int, 4> PostponedIndices;
6584   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6585   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6586     SmallPtrSet<BasicBlock *, 4> Visited;
6587     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6588       InsertBB = InsertBB->getSinglePredecessor();
6589     return InsertBB && InsertBB == InstBB;
6590   };
6591   for (int I = 0, E = VL.size(); I < E; ++I) {
6592     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6593       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6594            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6595           PostponedIndices.insert(I).second)
6596         PostponedInsts.emplace_back(Inst, I);
6597   }
6598 
6599   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6600     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6601     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6602     if (!InsElt)
6603       return Vec;
6604     GatherShuffleSeq.insert(InsElt);
6605     CSEBlocks.insert(InsElt->getParent());
6606     // Add to our 'need-to-extract' list.
6607     if (TreeEntry *Entry = getTreeEntry(V)) {
6608       // Find which lane we need to extract.
6609       unsigned FoundLane = Entry->findLaneForValue(V);
6610       ExternalUses.emplace_back(V, InsElt, FoundLane);
6611     }
6612     return Vec;
6613   };
6614   Value *Val0 =
6615       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6616   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6617   Value *Vec = PoisonValue::get(VecTy);
6618   SmallVector<int> NonConsts;
6619   // Insert constant values at first.
6620   for (int I = 0, E = VL.size(); I < E; ++I) {
6621     if (PostponedIndices.contains(I))
6622       continue;
6623     if (!isConstant(VL[I])) {
6624       NonConsts.push_back(I);
6625       continue;
6626     }
6627     Vec = CreateInsertElement(Vec, VL[I], I);
6628   }
6629   // Insert non-constant values.
6630   for (int I : NonConsts)
6631     Vec = CreateInsertElement(Vec, VL[I], I);
6632   // Append instructions, which are/may be part of the loop, in the end to make
6633   // it possible to hoist non-loop-based instructions.
6634   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6635     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6636 
6637   return Vec;
6638 }
6639 
6640 namespace {
6641 /// Merges shuffle masks and emits final shuffle instruction, if required.
6642 class ShuffleInstructionBuilder {
6643   IRBuilderBase &Builder;
6644   const unsigned VF = 0;
6645   bool IsFinalized = false;
6646   SmallVector<int, 4> Mask;
6647   /// Holds all of the instructions that we gathered.
6648   SetVector<Instruction *> &GatherShuffleSeq;
6649   /// A list of blocks that we are going to CSE.
6650   SetVector<BasicBlock *> &CSEBlocks;
6651 
6652 public:
6653   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6654                             SetVector<Instruction *> &GatherShuffleSeq,
6655                             SetVector<BasicBlock *> &CSEBlocks)
6656       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6657         CSEBlocks(CSEBlocks) {}
6658 
6659   /// Adds a mask, inverting it before applying.
6660   void addInversedMask(ArrayRef<unsigned> SubMask) {
6661     if (SubMask.empty())
6662       return;
6663     SmallVector<int, 4> NewMask;
6664     inversePermutation(SubMask, NewMask);
6665     addMask(NewMask);
6666   }
6667 
6668   /// Functions adds masks, merging them into  single one.
6669   void addMask(ArrayRef<unsigned> SubMask) {
6670     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6671     addMask(NewMask);
6672   }
6673 
6674   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6675 
6676   Value *finalize(Value *V) {
6677     IsFinalized = true;
6678     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6679     if (VF == ValueVF && Mask.empty())
6680       return V;
6681     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6682     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6683     addMask(NormalizedMask);
6684 
6685     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6686       return V;
6687     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6688     if (auto *I = dyn_cast<Instruction>(Vec)) {
6689       GatherShuffleSeq.insert(I);
6690       CSEBlocks.insert(I->getParent());
6691     }
6692     return Vec;
6693   }
6694 
6695   ~ShuffleInstructionBuilder() {
6696     assert((IsFinalized || Mask.empty()) &&
6697            "Shuffle construction must be finalized.");
6698   }
6699 };
6700 } // namespace
6701 
6702 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6703   const unsigned VF = VL.size();
6704   InstructionsState S = getSameOpcode(VL);
6705   if (S.getOpcode()) {
6706     if (TreeEntry *E = getTreeEntry(S.OpValue))
6707       if (E->isSame(VL)) {
6708         Value *V = vectorizeTree(E);
6709         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6710           if (!E->ReuseShuffleIndices.empty()) {
6711             // Reshuffle to get only unique values.
6712             // If some of the scalars are duplicated in the vectorization tree
6713             // entry, we do not vectorize them but instead generate a mask for
6714             // the reuses. But if there are several users of the same entry,
6715             // they may have different vectorization factors. This is especially
6716             // important for PHI nodes. In this case, we need to adapt the
6717             // resulting instruction for the user vectorization factor and have
6718             // to reshuffle it again to take only unique elements of the vector.
6719             // Without this code the function incorrectly returns reduced vector
6720             // instruction with the same elements, not with the unique ones.
6721 
6722             // block:
6723             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6724             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6725             // ... (use %2)
6726             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6727             // br %block
6728             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6729             SmallSet<int, 4> UsedIdxs;
6730             int Pos = 0;
6731             int Sz = VL.size();
6732             for (int Idx : E->ReuseShuffleIndices) {
6733               if (Idx != Sz && Idx != UndefMaskElem &&
6734                   UsedIdxs.insert(Idx).second)
6735                 UniqueIdxs[Idx] = Pos;
6736               ++Pos;
6737             }
6738             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6739                                             "less than original vector size.");
6740             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6741             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6742           } else {
6743             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6744                    "Expected vectorization factor less "
6745                    "than original vector size.");
6746             SmallVector<int> UniformMask(VF, 0);
6747             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6748             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6749           }
6750           if (auto *I = dyn_cast<Instruction>(V)) {
6751             GatherShuffleSeq.insert(I);
6752             CSEBlocks.insert(I->getParent());
6753           }
6754         }
6755         return V;
6756       }
6757   }
6758 
6759   // Can't vectorize this, so simply build a new vector with each lane
6760   // corresponding to the requested value.
6761   return createBuildVector(VL);
6762 }
6763 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6764   unsigned VF = VL.size();
6765   // Exploit possible reuse of values across lanes.
6766   SmallVector<int> ReuseShuffleIndicies;
6767   SmallVector<Value *> UniqueValues;
6768   if (VL.size() > 2) {
6769     DenseMap<Value *, unsigned> UniquePositions;
6770     unsigned NumValues =
6771         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6772                                     return !isa<UndefValue>(V);
6773                                   }).base());
6774     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6775     int UniqueVals = 0;
6776     for (Value *V : VL.drop_back(VL.size() - VF)) {
6777       if (isa<UndefValue>(V)) {
6778         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6779         continue;
6780       }
6781       if (isConstant(V)) {
6782         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6783         UniqueValues.emplace_back(V);
6784         continue;
6785       }
6786       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6787       ReuseShuffleIndicies.emplace_back(Res.first->second);
6788       if (Res.second) {
6789         UniqueValues.emplace_back(V);
6790         ++UniqueVals;
6791       }
6792     }
6793     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6794       // Emit pure splat vector.
6795       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6796                                   UndefMaskElem);
6797     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6798       ReuseShuffleIndicies.clear();
6799       UniqueValues.clear();
6800       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6801     }
6802     UniqueValues.append(VF - UniqueValues.size(),
6803                         PoisonValue::get(VL[0]->getType()));
6804     VL = UniqueValues;
6805   }
6806 
6807   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6808                                            CSEBlocks);
6809   Value *Vec = gather(VL);
6810   if (!ReuseShuffleIndicies.empty()) {
6811     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6812     Vec = ShuffleBuilder.finalize(Vec);
6813   }
6814   return Vec;
6815 }
6816 
6817 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6818   IRBuilder<>::InsertPointGuard Guard(Builder);
6819 
6820   if (E->VectorizedValue) {
6821     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6822     return E->VectorizedValue;
6823   }
6824 
6825   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6826   unsigned VF = E->getVectorFactor();
6827   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6828                                            CSEBlocks);
6829   if (E->State == TreeEntry::NeedToGather) {
6830     if (E->getMainOp())
6831       setInsertPointAfterBundle(E);
6832     Value *Vec;
6833     SmallVector<int> Mask;
6834     SmallVector<const TreeEntry *> Entries;
6835     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6836         isGatherShuffledEntry(E, Mask, Entries);
6837     if (Shuffle.hasValue()) {
6838       assert((Entries.size() == 1 || Entries.size() == 2) &&
6839              "Expected shuffle of 1 or 2 entries.");
6840       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6841                                         Entries.back()->VectorizedValue, Mask);
6842       if (auto *I = dyn_cast<Instruction>(Vec)) {
6843         GatherShuffleSeq.insert(I);
6844         CSEBlocks.insert(I->getParent());
6845       }
6846     } else {
6847       Vec = gather(E->Scalars);
6848     }
6849     if (NeedToShuffleReuses) {
6850       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6851       Vec = ShuffleBuilder.finalize(Vec);
6852     }
6853     E->VectorizedValue = Vec;
6854     return Vec;
6855   }
6856 
6857   assert((E->State == TreeEntry::Vectorize ||
6858           E->State == TreeEntry::ScatterVectorize) &&
6859          "Unhandled state");
6860   unsigned ShuffleOrOp =
6861       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6862   Instruction *VL0 = E->getMainOp();
6863   Type *ScalarTy = VL0->getType();
6864   if (auto *Store = dyn_cast<StoreInst>(VL0))
6865     ScalarTy = Store->getValueOperand()->getType();
6866   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6867     ScalarTy = IE->getOperand(1)->getType();
6868   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6869   switch (ShuffleOrOp) {
6870     case Instruction::PHI: {
6871       assert(
6872           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6873           "PHI reordering is free.");
6874       auto *PH = cast<PHINode>(VL0);
6875       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6876       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6877       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6878       Value *V = NewPhi;
6879 
6880       // Adjust insertion point once all PHI's have been generated.
6881       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6882       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6883 
6884       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6885       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6886       V = ShuffleBuilder.finalize(V);
6887 
6888       E->VectorizedValue = V;
6889 
6890       // PHINodes may have multiple entries from the same block. We want to
6891       // visit every block once.
6892       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6893 
6894       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6895         ValueList Operands;
6896         BasicBlock *IBB = PH->getIncomingBlock(i);
6897 
6898         if (!VisitedBBs.insert(IBB).second) {
6899           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6900           continue;
6901         }
6902 
6903         Builder.SetInsertPoint(IBB->getTerminator());
6904         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6905         Value *Vec = vectorizeTree(E->getOperand(i));
6906         NewPhi->addIncoming(Vec, IBB);
6907       }
6908 
6909       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6910              "Invalid number of incoming values");
6911       return V;
6912     }
6913 
6914     case Instruction::ExtractElement: {
6915       Value *V = E->getSingleOperand(0);
6916       Builder.SetInsertPoint(VL0);
6917       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6918       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6919       V = ShuffleBuilder.finalize(V);
6920       E->VectorizedValue = V;
6921       return V;
6922     }
6923     case Instruction::ExtractValue: {
6924       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6925       Builder.SetInsertPoint(LI);
6926       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6927       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6928       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6929       Value *NewV = propagateMetadata(V, E->Scalars);
6930       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6931       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6932       NewV = ShuffleBuilder.finalize(NewV);
6933       E->VectorizedValue = NewV;
6934       return NewV;
6935     }
6936     case Instruction::InsertElement: {
6937       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6938       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6939       Value *V = vectorizeTree(E->getOperand(1));
6940 
6941       // Create InsertVector shuffle if necessary
6942       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6943         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6944       }));
6945       const unsigned NumElts =
6946           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6947       const unsigned NumScalars = E->Scalars.size();
6948 
6949       unsigned Offset = *getInsertIndex(VL0);
6950       assert(Offset < NumElts && "Failed to find vector index offset");
6951 
6952       // Create shuffle to resize vector
6953       SmallVector<int> Mask;
6954       if (!E->ReorderIndices.empty()) {
6955         inversePermutation(E->ReorderIndices, Mask);
6956         Mask.append(NumElts - NumScalars, UndefMaskElem);
6957       } else {
6958         Mask.assign(NumElts, UndefMaskElem);
6959         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6960       }
6961       // Create InsertVector shuffle if necessary
6962       bool IsIdentity = true;
6963       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6964       Mask.swap(PrevMask);
6965       for (unsigned I = 0; I < NumScalars; ++I) {
6966         Value *Scalar = E->Scalars[PrevMask[I]];
6967         unsigned InsertIdx = *getInsertIndex(Scalar);
6968         IsIdentity &= InsertIdx - Offset == I;
6969         Mask[InsertIdx - Offset] = I;
6970       }
6971       if (!IsIdentity || NumElts != NumScalars) {
6972         V = Builder.CreateShuffleVector(V, Mask);
6973         if (auto *I = dyn_cast<Instruction>(V)) {
6974           GatherShuffleSeq.insert(I);
6975           CSEBlocks.insert(I->getParent());
6976         }
6977       }
6978 
6979       if ((!IsIdentity || Offset != 0 ||
6980            !isUndefVector(FirstInsert->getOperand(0))) &&
6981           NumElts != NumScalars) {
6982         SmallVector<int> InsertMask(NumElts);
6983         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6984         for (unsigned I = 0; I < NumElts; I++) {
6985           if (Mask[I] != UndefMaskElem)
6986             InsertMask[Offset + I] = NumElts + I;
6987         }
6988 
6989         V = Builder.CreateShuffleVector(
6990             FirstInsert->getOperand(0), V, InsertMask,
6991             cast<Instruction>(E->Scalars.back())->getName());
6992         if (auto *I = dyn_cast<Instruction>(V)) {
6993           GatherShuffleSeq.insert(I);
6994           CSEBlocks.insert(I->getParent());
6995         }
6996       }
6997 
6998       ++NumVectorInstructions;
6999       E->VectorizedValue = V;
7000       return V;
7001     }
7002     case Instruction::ZExt:
7003     case Instruction::SExt:
7004     case Instruction::FPToUI:
7005     case Instruction::FPToSI:
7006     case Instruction::FPExt:
7007     case Instruction::PtrToInt:
7008     case Instruction::IntToPtr:
7009     case Instruction::SIToFP:
7010     case Instruction::UIToFP:
7011     case Instruction::Trunc:
7012     case Instruction::FPTrunc:
7013     case Instruction::BitCast: {
7014       setInsertPointAfterBundle(E);
7015 
7016       Value *InVec = vectorizeTree(E->getOperand(0));
7017 
7018       if (E->VectorizedValue) {
7019         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7020         return E->VectorizedValue;
7021       }
7022 
7023       auto *CI = cast<CastInst>(VL0);
7024       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7025       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7026       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7027       V = ShuffleBuilder.finalize(V);
7028 
7029       E->VectorizedValue = V;
7030       ++NumVectorInstructions;
7031       return V;
7032     }
7033     case Instruction::FCmp:
7034     case Instruction::ICmp: {
7035       setInsertPointAfterBundle(E);
7036 
7037       Value *L = vectorizeTree(E->getOperand(0));
7038       Value *R = vectorizeTree(E->getOperand(1));
7039 
7040       if (E->VectorizedValue) {
7041         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7042         return E->VectorizedValue;
7043       }
7044 
7045       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7046       Value *V = Builder.CreateCmp(P0, L, R);
7047       propagateIRFlags(V, E->Scalars, VL0);
7048       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7049       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7050       V = ShuffleBuilder.finalize(V);
7051 
7052       E->VectorizedValue = V;
7053       ++NumVectorInstructions;
7054       return V;
7055     }
7056     case Instruction::Select: {
7057       setInsertPointAfterBundle(E);
7058 
7059       Value *Cond = vectorizeTree(E->getOperand(0));
7060       Value *True = vectorizeTree(E->getOperand(1));
7061       Value *False = vectorizeTree(E->getOperand(2));
7062 
7063       if (E->VectorizedValue) {
7064         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7065         return E->VectorizedValue;
7066       }
7067 
7068       Value *V = Builder.CreateSelect(Cond, True, False);
7069       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7070       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7071       V = ShuffleBuilder.finalize(V);
7072 
7073       E->VectorizedValue = V;
7074       ++NumVectorInstructions;
7075       return V;
7076     }
7077     case Instruction::FNeg: {
7078       setInsertPointAfterBundle(E);
7079 
7080       Value *Op = vectorizeTree(E->getOperand(0));
7081 
7082       if (E->VectorizedValue) {
7083         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7084         return E->VectorizedValue;
7085       }
7086 
7087       Value *V = Builder.CreateUnOp(
7088           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7089       propagateIRFlags(V, E->Scalars, VL0);
7090       if (auto *I = dyn_cast<Instruction>(V))
7091         V = propagateMetadata(I, E->Scalars);
7092 
7093       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7094       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7095       V = ShuffleBuilder.finalize(V);
7096 
7097       E->VectorizedValue = V;
7098       ++NumVectorInstructions;
7099 
7100       return V;
7101     }
7102     case Instruction::Add:
7103     case Instruction::FAdd:
7104     case Instruction::Sub:
7105     case Instruction::FSub:
7106     case Instruction::Mul:
7107     case Instruction::FMul:
7108     case Instruction::UDiv:
7109     case Instruction::SDiv:
7110     case Instruction::FDiv:
7111     case Instruction::URem:
7112     case Instruction::SRem:
7113     case Instruction::FRem:
7114     case Instruction::Shl:
7115     case Instruction::LShr:
7116     case Instruction::AShr:
7117     case Instruction::And:
7118     case Instruction::Or:
7119     case Instruction::Xor: {
7120       setInsertPointAfterBundle(E);
7121 
7122       Value *LHS = vectorizeTree(E->getOperand(0));
7123       Value *RHS = vectorizeTree(E->getOperand(1));
7124 
7125       if (E->VectorizedValue) {
7126         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7127         return E->VectorizedValue;
7128       }
7129 
7130       Value *V = Builder.CreateBinOp(
7131           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7132           RHS);
7133       propagateIRFlags(V, E->Scalars, VL0);
7134       if (auto *I = dyn_cast<Instruction>(V))
7135         V = propagateMetadata(I, E->Scalars);
7136 
7137       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7138       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7139       V = ShuffleBuilder.finalize(V);
7140 
7141       E->VectorizedValue = V;
7142       ++NumVectorInstructions;
7143 
7144       return V;
7145     }
7146     case Instruction::Load: {
7147       // Loads are inserted at the head of the tree because we don't want to
7148       // sink them all the way down past store instructions.
7149       setInsertPointAfterBundle(E);
7150 
7151       LoadInst *LI = cast<LoadInst>(VL0);
7152       Instruction *NewLI;
7153       unsigned AS = LI->getPointerAddressSpace();
7154       Value *PO = LI->getPointerOperand();
7155       if (E->State == TreeEntry::Vectorize) {
7156         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7157         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7158 
7159         // The pointer operand uses an in-tree scalar so we add the new BitCast
7160         // or LoadInst to ExternalUses list to make sure that an extract will
7161         // be generated in the future.
7162         if (TreeEntry *Entry = getTreeEntry(PO)) {
7163           // Find which lane we need to extract.
7164           unsigned FoundLane = Entry->findLaneForValue(PO);
7165           ExternalUses.emplace_back(
7166               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7167         }
7168       } else {
7169         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7170         Value *VecPtr = vectorizeTree(E->getOperand(0));
7171         // Use the minimum alignment of the gathered loads.
7172         Align CommonAlignment = LI->getAlign();
7173         for (Value *V : E->Scalars)
7174           CommonAlignment =
7175               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7176         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7177       }
7178       Value *V = propagateMetadata(NewLI, E->Scalars);
7179 
7180       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7181       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7182       V = ShuffleBuilder.finalize(V);
7183       E->VectorizedValue = V;
7184       ++NumVectorInstructions;
7185       return V;
7186     }
7187     case Instruction::Store: {
7188       auto *SI = cast<StoreInst>(VL0);
7189       unsigned AS = SI->getPointerAddressSpace();
7190 
7191       setInsertPointAfterBundle(E);
7192 
7193       Value *VecValue = vectorizeTree(E->getOperand(0));
7194       ShuffleBuilder.addMask(E->ReorderIndices);
7195       VecValue = ShuffleBuilder.finalize(VecValue);
7196 
7197       Value *ScalarPtr = SI->getPointerOperand();
7198       Value *VecPtr = Builder.CreateBitCast(
7199           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7200       StoreInst *ST =
7201           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7202 
7203       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7204       // StoreInst to ExternalUses to make sure that an extract will be
7205       // generated in the future.
7206       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7207         // Find which lane we need to extract.
7208         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7209         ExternalUses.push_back(ExternalUser(
7210             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7211             FoundLane));
7212       }
7213 
7214       Value *V = propagateMetadata(ST, E->Scalars);
7215 
7216       E->VectorizedValue = V;
7217       ++NumVectorInstructions;
7218       return V;
7219     }
7220     case Instruction::GetElementPtr: {
7221       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7222       setInsertPointAfterBundle(E);
7223 
7224       Value *Op0 = vectorizeTree(E->getOperand(0));
7225 
7226       SmallVector<Value *> OpVecs;
7227       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7228         Value *OpVec = vectorizeTree(E->getOperand(J));
7229         OpVecs.push_back(OpVec);
7230       }
7231 
7232       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7233       if (Instruction *I = dyn_cast<Instruction>(V))
7234         V = propagateMetadata(I, E->Scalars);
7235 
7236       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7237       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7238       V = ShuffleBuilder.finalize(V);
7239 
7240       E->VectorizedValue = V;
7241       ++NumVectorInstructions;
7242 
7243       return V;
7244     }
7245     case Instruction::Call: {
7246       CallInst *CI = cast<CallInst>(VL0);
7247       setInsertPointAfterBundle(E);
7248 
7249       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7250       if (Function *FI = CI->getCalledFunction())
7251         IID = FI->getIntrinsicID();
7252 
7253       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7254 
7255       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7256       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7257                           VecCallCosts.first <= VecCallCosts.second;
7258 
7259       Value *ScalarArg = nullptr;
7260       std::vector<Value *> OpVecs;
7261       SmallVector<Type *, 2> TysForDecl =
7262           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7263       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7264         ValueList OpVL;
7265         // Some intrinsics have scalar arguments. This argument should not be
7266         // vectorized.
7267         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7268           CallInst *CEI = cast<CallInst>(VL0);
7269           ScalarArg = CEI->getArgOperand(j);
7270           OpVecs.push_back(CEI->getArgOperand(j));
7271           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7272             TysForDecl.push_back(ScalarArg->getType());
7273           continue;
7274         }
7275 
7276         Value *OpVec = vectorizeTree(E->getOperand(j));
7277         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7278         OpVecs.push_back(OpVec);
7279       }
7280 
7281       Function *CF;
7282       if (!UseIntrinsic) {
7283         VFShape Shape =
7284             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7285                                   VecTy->getNumElements())),
7286                          false /*HasGlobalPred*/);
7287         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7288       } else {
7289         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7290       }
7291 
7292       SmallVector<OperandBundleDef, 1> OpBundles;
7293       CI->getOperandBundlesAsDefs(OpBundles);
7294       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7295 
7296       // The scalar argument uses an in-tree scalar so we add the new vectorized
7297       // call to ExternalUses list to make sure that an extract will be
7298       // generated in the future.
7299       if (ScalarArg) {
7300         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7301           // Find which lane we need to extract.
7302           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7303           ExternalUses.push_back(
7304               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7305         }
7306       }
7307 
7308       propagateIRFlags(V, E->Scalars, VL0);
7309       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7310       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7311       V = ShuffleBuilder.finalize(V);
7312 
7313       E->VectorizedValue = V;
7314       ++NumVectorInstructions;
7315       return V;
7316     }
7317     case Instruction::ShuffleVector: {
7318       assert(E->isAltShuffle() &&
7319              ((Instruction::isBinaryOp(E->getOpcode()) &&
7320                Instruction::isBinaryOp(E->getAltOpcode())) ||
7321               (Instruction::isCast(E->getOpcode()) &&
7322                Instruction::isCast(E->getAltOpcode())) ||
7323               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7324              "Invalid Shuffle Vector Operand");
7325 
7326       Value *LHS = nullptr, *RHS = nullptr;
7327       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7328         setInsertPointAfterBundle(E);
7329         LHS = vectorizeTree(E->getOperand(0));
7330         RHS = vectorizeTree(E->getOperand(1));
7331       } else {
7332         setInsertPointAfterBundle(E);
7333         LHS = vectorizeTree(E->getOperand(0));
7334       }
7335 
7336       if (E->VectorizedValue) {
7337         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7338         return E->VectorizedValue;
7339       }
7340 
7341       Value *V0, *V1;
7342       if (Instruction::isBinaryOp(E->getOpcode())) {
7343         V0 = Builder.CreateBinOp(
7344             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7345         V1 = Builder.CreateBinOp(
7346             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7347       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7348         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7349         auto *AltCI = cast<CmpInst>(E->getAltOp());
7350         CmpInst::Predicate AltPred = AltCI->getPredicate();
7351         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7352       } else {
7353         V0 = Builder.CreateCast(
7354             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7355         V1 = Builder.CreateCast(
7356             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7357       }
7358       // Add V0 and V1 to later analysis to try to find and remove matching
7359       // instruction, if any.
7360       for (Value *V : {V0, V1}) {
7361         if (auto *I = dyn_cast<Instruction>(V)) {
7362           GatherShuffleSeq.insert(I);
7363           CSEBlocks.insert(I->getParent());
7364         }
7365       }
7366 
7367       // Create shuffle to take alternate operations from the vector.
7368       // Also, gather up main and alt scalar ops to propagate IR flags to
7369       // each vector operation.
7370       ValueList OpScalars, AltScalars;
7371       SmallVector<int> Mask;
7372       buildShuffleEntryMask(
7373           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7374           [E](Instruction *I) {
7375             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7376             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7377           },
7378           Mask, &OpScalars, &AltScalars);
7379 
7380       propagateIRFlags(V0, OpScalars);
7381       propagateIRFlags(V1, AltScalars);
7382 
7383       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7384       if (auto *I = dyn_cast<Instruction>(V)) {
7385         V = propagateMetadata(I, E->Scalars);
7386         GatherShuffleSeq.insert(I);
7387         CSEBlocks.insert(I->getParent());
7388       }
7389       V = ShuffleBuilder.finalize(V);
7390 
7391       E->VectorizedValue = V;
7392       ++NumVectorInstructions;
7393 
7394       return V;
7395     }
7396     default:
7397     llvm_unreachable("unknown inst");
7398   }
7399   return nullptr;
7400 }
7401 
7402 Value *BoUpSLP::vectorizeTree() {
7403   ExtraValueToDebugLocsMap ExternallyUsedValues;
7404   return vectorizeTree(ExternallyUsedValues);
7405 }
7406 
7407 Value *
7408 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7409   // All blocks must be scheduled before any instructions are inserted.
7410   for (auto &BSIter : BlocksSchedules) {
7411     scheduleBlock(BSIter.second.get());
7412   }
7413 
7414   Builder.SetInsertPoint(&F->getEntryBlock().front());
7415   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7416 
7417   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7418   // vectorized root. InstCombine will then rewrite the entire expression. We
7419   // sign extend the extracted values below.
7420   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7421   if (MinBWs.count(ScalarRoot)) {
7422     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7423       // If current instr is a phi and not the last phi, insert it after the
7424       // last phi node.
7425       if (isa<PHINode>(I))
7426         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7427       else
7428         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7429     }
7430     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7431     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7432     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7433     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7434     VectorizableTree[0]->VectorizedValue = Trunc;
7435   }
7436 
7437   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7438                     << " values .\n");
7439 
7440   // Extract all of the elements with the external uses.
7441   for (const auto &ExternalUse : ExternalUses) {
7442     Value *Scalar = ExternalUse.Scalar;
7443     llvm::User *User = ExternalUse.User;
7444 
7445     // Skip users that we already RAUW. This happens when one instruction
7446     // has multiple uses of the same value.
7447     if (User && !is_contained(Scalar->users(), User))
7448       continue;
7449     TreeEntry *E = getTreeEntry(Scalar);
7450     assert(E && "Invalid scalar");
7451     assert(E->State != TreeEntry::NeedToGather &&
7452            "Extracting from a gather list");
7453 
7454     Value *Vec = E->VectorizedValue;
7455     assert(Vec && "Can't find vectorizable value");
7456 
7457     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7458     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7459       if (Scalar->getType() != Vec->getType()) {
7460         Value *Ex;
7461         // "Reuse" the existing extract to improve final codegen.
7462         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7463           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7464                                             ES->getOperand(1));
7465         } else {
7466           Ex = Builder.CreateExtractElement(Vec, Lane);
7467         }
7468         // If necessary, sign-extend or zero-extend ScalarRoot
7469         // to the larger type.
7470         if (!MinBWs.count(ScalarRoot))
7471           return Ex;
7472         if (MinBWs[ScalarRoot].second)
7473           return Builder.CreateSExt(Ex, Scalar->getType());
7474         return Builder.CreateZExt(Ex, Scalar->getType());
7475       }
7476       assert(isa<FixedVectorType>(Scalar->getType()) &&
7477              isa<InsertElementInst>(Scalar) &&
7478              "In-tree scalar of vector type is not insertelement?");
7479       return Vec;
7480     };
7481     // If User == nullptr, the Scalar is used as extra arg. Generate
7482     // ExtractElement instruction and update the record for this scalar in
7483     // ExternallyUsedValues.
7484     if (!User) {
7485       assert(ExternallyUsedValues.count(Scalar) &&
7486              "Scalar with nullptr as an external user must be registered in "
7487              "ExternallyUsedValues map");
7488       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7489         Builder.SetInsertPoint(VecI->getParent(),
7490                                std::next(VecI->getIterator()));
7491       } else {
7492         Builder.SetInsertPoint(&F->getEntryBlock().front());
7493       }
7494       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7495       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7496       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7497       auto It = ExternallyUsedValues.find(Scalar);
7498       assert(It != ExternallyUsedValues.end() &&
7499              "Externally used scalar is not found in ExternallyUsedValues");
7500       NewInstLocs.append(It->second);
7501       ExternallyUsedValues.erase(Scalar);
7502       // Required to update internally referenced instructions.
7503       Scalar->replaceAllUsesWith(NewInst);
7504       continue;
7505     }
7506 
7507     // Generate extracts for out-of-tree users.
7508     // Find the insertion point for the extractelement lane.
7509     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7510       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7511         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7512           if (PH->getIncomingValue(i) == Scalar) {
7513             Instruction *IncomingTerminator =
7514                 PH->getIncomingBlock(i)->getTerminator();
7515             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7516               Builder.SetInsertPoint(VecI->getParent(),
7517                                      std::next(VecI->getIterator()));
7518             } else {
7519               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7520             }
7521             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7522             CSEBlocks.insert(PH->getIncomingBlock(i));
7523             PH->setOperand(i, NewInst);
7524           }
7525         }
7526       } else {
7527         Builder.SetInsertPoint(cast<Instruction>(User));
7528         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7529         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7530         User->replaceUsesOfWith(Scalar, NewInst);
7531       }
7532     } else {
7533       Builder.SetInsertPoint(&F->getEntryBlock().front());
7534       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7535       CSEBlocks.insert(&F->getEntryBlock());
7536       User->replaceUsesOfWith(Scalar, NewInst);
7537     }
7538 
7539     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7540   }
7541 
7542   // For each vectorized value:
7543   for (auto &TEPtr : VectorizableTree) {
7544     TreeEntry *Entry = TEPtr.get();
7545 
7546     // No need to handle users of gathered values.
7547     if (Entry->State == TreeEntry::NeedToGather)
7548       continue;
7549 
7550     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7551 
7552     // For each lane:
7553     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7554       Value *Scalar = Entry->Scalars[Lane];
7555 
7556 #ifndef NDEBUG
7557       Type *Ty = Scalar->getType();
7558       if (!Ty->isVoidTy()) {
7559         for (User *U : Scalar->users()) {
7560           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7561 
7562           // It is legal to delete users in the ignorelist.
7563           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7564                   (isa_and_nonnull<Instruction>(U) &&
7565                    isDeleted(cast<Instruction>(U)))) &&
7566                  "Deleting out-of-tree value");
7567         }
7568       }
7569 #endif
7570       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7571       eraseInstruction(cast<Instruction>(Scalar));
7572     }
7573   }
7574 
7575   Builder.ClearInsertionPoint();
7576   InstrElementSize.clear();
7577 
7578   return VectorizableTree[0]->VectorizedValue;
7579 }
7580 
7581 void BoUpSLP::optimizeGatherSequence() {
7582   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7583                     << " gather sequences instructions.\n");
7584   // LICM InsertElementInst sequences.
7585   for (Instruction *I : GatherShuffleSeq) {
7586     if (isDeleted(I))
7587       continue;
7588 
7589     // Check if this block is inside a loop.
7590     Loop *L = LI->getLoopFor(I->getParent());
7591     if (!L)
7592       continue;
7593 
7594     // Check if it has a preheader.
7595     BasicBlock *PreHeader = L->getLoopPreheader();
7596     if (!PreHeader)
7597       continue;
7598 
7599     // If the vector or the element that we insert into it are
7600     // instructions that are defined in this basic block then we can't
7601     // hoist this instruction.
7602     if (any_of(I->operands(), [L](Value *V) {
7603           auto *OpI = dyn_cast<Instruction>(V);
7604           return OpI && L->contains(OpI);
7605         }))
7606       continue;
7607 
7608     // We can hoist this instruction. Move it to the pre-header.
7609     I->moveBefore(PreHeader->getTerminator());
7610   }
7611 
7612   // Make a list of all reachable blocks in our CSE queue.
7613   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7614   CSEWorkList.reserve(CSEBlocks.size());
7615   for (BasicBlock *BB : CSEBlocks)
7616     if (DomTreeNode *N = DT->getNode(BB)) {
7617       assert(DT->isReachableFromEntry(N));
7618       CSEWorkList.push_back(N);
7619     }
7620 
7621   // Sort blocks by domination. This ensures we visit a block after all blocks
7622   // dominating it are visited.
7623   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7624     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7625            "Different nodes should have different DFS numbers");
7626     return A->getDFSNumIn() < B->getDFSNumIn();
7627   });
7628 
7629   // Less defined shuffles can be replaced by the more defined copies.
7630   // Between two shuffles one is less defined if it has the same vector operands
7631   // and its mask indeces are the same as in the first one or undefs. E.g.
7632   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7633   // poison, <0, 0, 0, 0>.
7634   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7635                                            SmallVectorImpl<int> &NewMask) {
7636     if (I1->getType() != I2->getType())
7637       return false;
7638     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7639     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7640     if (!SI1 || !SI2)
7641       return I1->isIdenticalTo(I2);
7642     if (SI1->isIdenticalTo(SI2))
7643       return true;
7644     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7645       if (SI1->getOperand(I) != SI2->getOperand(I))
7646         return false;
7647     // Check if the second instruction is more defined than the first one.
7648     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7649     ArrayRef<int> SM1 = SI1->getShuffleMask();
7650     // Count trailing undefs in the mask to check the final number of used
7651     // registers.
7652     unsigned LastUndefsCnt = 0;
7653     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7654       if (SM1[I] == UndefMaskElem)
7655         ++LastUndefsCnt;
7656       else
7657         LastUndefsCnt = 0;
7658       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7659           NewMask[I] != SM1[I])
7660         return false;
7661       if (NewMask[I] == UndefMaskElem)
7662         NewMask[I] = SM1[I];
7663     }
7664     // Check if the last undefs actually change the final number of used vector
7665     // registers.
7666     return SM1.size() - LastUndefsCnt > 1 &&
7667            TTI->getNumberOfParts(SI1->getType()) ==
7668                TTI->getNumberOfParts(
7669                    FixedVectorType::get(SI1->getType()->getElementType(),
7670                                         SM1.size() - LastUndefsCnt));
7671   };
7672   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7673   // instructions. TODO: We can further optimize this scan if we split the
7674   // instructions into different buckets based on the insert lane.
7675   SmallVector<Instruction *, 16> Visited;
7676   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7677     assert(*I &&
7678            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7679            "Worklist not sorted properly!");
7680     BasicBlock *BB = (*I)->getBlock();
7681     // For all instructions in blocks containing gather sequences:
7682     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7683       if (isDeleted(&In))
7684         continue;
7685       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7686           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7687         continue;
7688 
7689       // Check if we can replace this instruction with any of the
7690       // visited instructions.
7691       bool Replaced = false;
7692       for (Instruction *&V : Visited) {
7693         SmallVector<int> NewMask;
7694         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7695             DT->dominates(V->getParent(), In.getParent())) {
7696           In.replaceAllUsesWith(V);
7697           eraseInstruction(&In);
7698           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7699             if (!NewMask.empty())
7700               SI->setShuffleMask(NewMask);
7701           Replaced = true;
7702           break;
7703         }
7704         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7705             GatherShuffleSeq.contains(V) &&
7706             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7707             DT->dominates(In.getParent(), V->getParent())) {
7708           In.moveAfter(V);
7709           V->replaceAllUsesWith(&In);
7710           eraseInstruction(V);
7711           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7712             if (!NewMask.empty())
7713               SI->setShuffleMask(NewMask);
7714           V = &In;
7715           Replaced = true;
7716           break;
7717         }
7718       }
7719       if (!Replaced) {
7720         assert(!is_contained(Visited, &In));
7721         Visited.push_back(&In);
7722       }
7723     }
7724   }
7725   CSEBlocks.clear();
7726   GatherShuffleSeq.clear();
7727 }
7728 
7729 BoUpSLP::ScheduleData *
7730 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7731   ScheduleData *Bundle = nullptr;
7732   ScheduleData *PrevInBundle = nullptr;
7733   for (Value *V : VL) {
7734     if (doesNotNeedToBeScheduled(V))
7735       continue;
7736     ScheduleData *BundleMember = getScheduleData(V);
7737     assert(BundleMember &&
7738            "no ScheduleData for bundle member "
7739            "(maybe not in same basic block)");
7740     assert(BundleMember->isSchedulingEntity() &&
7741            "bundle member already part of other bundle");
7742     if (PrevInBundle) {
7743       PrevInBundle->NextInBundle = BundleMember;
7744     } else {
7745       Bundle = BundleMember;
7746     }
7747 
7748     // Group the instructions to a bundle.
7749     BundleMember->FirstInBundle = Bundle;
7750     PrevInBundle = BundleMember;
7751   }
7752   assert(Bundle && "Failed to find schedule bundle");
7753   return Bundle;
7754 }
7755 
7756 // Groups the instructions to a bundle (which is then a single scheduling entity)
7757 // and schedules instructions until the bundle gets ready.
7758 Optional<BoUpSLP::ScheduleData *>
7759 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7760                                             const InstructionsState &S) {
7761   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7762   // instructions.
7763   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7764       doesNotNeedToSchedule(VL))
7765     return nullptr;
7766 
7767   // Initialize the instruction bundle.
7768   Instruction *OldScheduleEnd = ScheduleEnd;
7769   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7770 
7771   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7772                                                          ScheduleData *Bundle) {
7773     // The scheduling region got new instructions at the lower end (or it is a
7774     // new region for the first bundle). This makes it necessary to
7775     // recalculate all dependencies.
7776     // It is seldom that this needs to be done a second time after adding the
7777     // initial bundle to the region.
7778     if (ScheduleEnd != OldScheduleEnd) {
7779       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7780         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7781       ReSchedule = true;
7782     }
7783     if (Bundle) {
7784       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7785                         << " in block " << BB->getName() << "\n");
7786       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7787     }
7788 
7789     if (ReSchedule) {
7790       resetSchedule();
7791       initialFillReadyList(ReadyInsts);
7792     }
7793 
7794     // Now try to schedule the new bundle or (if no bundle) just calculate
7795     // dependencies. As soon as the bundle is "ready" it means that there are no
7796     // cyclic dependencies and we can schedule it. Note that's important that we
7797     // don't "schedule" the bundle yet (see cancelScheduling).
7798     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7799            !ReadyInsts.empty()) {
7800       ScheduleData *Picked = ReadyInsts.pop_back_val();
7801       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7802              "must be ready to schedule");
7803       schedule(Picked, ReadyInsts);
7804     }
7805   };
7806 
7807   // Make sure that the scheduling region contains all
7808   // instructions of the bundle.
7809   for (Value *V : VL) {
7810     if (doesNotNeedToBeScheduled(V))
7811       continue;
7812     if (!extendSchedulingRegion(V, S)) {
7813       // If the scheduling region got new instructions at the lower end (or it
7814       // is a new region for the first bundle). This makes it necessary to
7815       // recalculate all dependencies.
7816       // Otherwise the compiler may crash trying to incorrectly calculate
7817       // dependencies and emit instruction in the wrong order at the actual
7818       // scheduling.
7819       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7820       return None;
7821     }
7822   }
7823 
7824   bool ReSchedule = false;
7825   for (Value *V : VL) {
7826     if (doesNotNeedToBeScheduled(V))
7827       continue;
7828     ScheduleData *BundleMember = getScheduleData(V);
7829     assert(BundleMember &&
7830            "no ScheduleData for bundle member (maybe not in same basic block)");
7831 
7832     // Make sure we don't leave the pieces of the bundle in the ready list when
7833     // whole bundle might not be ready.
7834     ReadyInsts.remove(BundleMember);
7835 
7836     if (!BundleMember->IsScheduled)
7837       continue;
7838     // A bundle member was scheduled as single instruction before and now
7839     // needs to be scheduled as part of the bundle. We just get rid of the
7840     // existing schedule.
7841     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7842                       << " was already scheduled\n");
7843     ReSchedule = true;
7844   }
7845 
7846   auto *Bundle = buildBundle(VL);
7847   TryScheduleBundleImpl(ReSchedule, Bundle);
7848   if (!Bundle->isReady()) {
7849     cancelScheduling(VL, S.OpValue);
7850     return None;
7851   }
7852   return Bundle;
7853 }
7854 
7855 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7856                                                 Value *OpValue) {
7857   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7858       doesNotNeedToSchedule(VL))
7859     return;
7860 
7861   if (doesNotNeedToBeScheduled(OpValue))
7862     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7863   ScheduleData *Bundle = getScheduleData(OpValue);
7864   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7865   assert(!Bundle->IsScheduled &&
7866          "Can't cancel bundle which is already scheduled");
7867   assert(Bundle->isSchedulingEntity() &&
7868          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7869          "tried to unbundle something which is not a bundle");
7870 
7871   // Remove the bundle from the ready list.
7872   if (Bundle->isReady())
7873     ReadyInsts.remove(Bundle);
7874 
7875   // Un-bundle: make single instructions out of the bundle.
7876   ScheduleData *BundleMember = Bundle;
7877   while (BundleMember) {
7878     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7879     BundleMember->FirstInBundle = BundleMember;
7880     ScheduleData *Next = BundleMember->NextInBundle;
7881     BundleMember->NextInBundle = nullptr;
7882     BundleMember->TE = nullptr;
7883     if (BundleMember->unscheduledDepsInBundle() == 0) {
7884       ReadyInsts.insert(BundleMember);
7885     }
7886     BundleMember = Next;
7887   }
7888 }
7889 
7890 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7891   // Allocate a new ScheduleData for the instruction.
7892   if (ChunkPos >= ChunkSize) {
7893     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7894     ChunkPos = 0;
7895   }
7896   return &(ScheduleDataChunks.back()[ChunkPos++]);
7897 }
7898 
7899 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7900                                                       const InstructionsState &S) {
7901   if (getScheduleData(V, isOneOf(S, V)))
7902     return true;
7903   Instruction *I = dyn_cast<Instruction>(V);
7904   assert(I && "bundle member must be an instruction");
7905   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7906          !doesNotNeedToBeScheduled(I) &&
7907          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7908          "be scheduled");
7909   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7910     ScheduleData *ISD = getScheduleData(I);
7911     if (!ISD)
7912       return false;
7913     assert(isInSchedulingRegion(ISD) &&
7914            "ScheduleData not in scheduling region");
7915     ScheduleData *SD = allocateScheduleDataChunks();
7916     SD->Inst = I;
7917     SD->init(SchedulingRegionID, S.OpValue);
7918     ExtraScheduleDataMap[I][S.OpValue] = SD;
7919     return true;
7920   };
7921   if (CheckScheduleForI(I))
7922     return true;
7923   if (!ScheduleStart) {
7924     // It's the first instruction in the new region.
7925     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7926     ScheduleStart = I;
7927     ScheduleEnd = I->getNextNode();
7928     if (isOneOf(S, I) != I)
7929       CheckScheduleForI(I);
7930     assert(ScheduleEnd && "tried to vectorize a terminator?");
7931     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7932     return true;
7933   }
7934   // Search up and down at the same time, because we don't know if the new
7935   // instruction is above or below the existing scheduling region.
7936   BasicBlock::reverse_iterator UpIter =
7937       ++ScheduleStart->getIterator().getReverse();
7938   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7939   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7940   BasicBlock::iterator LowerEnd = BB->end();
7941   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7942          &*DownIter != I) {
7943     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7944       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7945       return false;
7946     }
7947 
7948     ++UpIter;
7949     ++DownIter;
7950   }
7951   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7952     assert(I->getParent() == ScheduleStart->getParent() &&
7953            "Instruction is in wrong basic block.");
7954     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7955     ScheduleStart = I;
7956     if (isOneOf(S, I) != I)
7957       CheckScheduleForI(I);
7958     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7959                       << "\n");
7960     return true;
7961   }
7962   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7963          "Expected to reach top of the basic block or instruction down the "
7964          "lower end.");
7965   assert(I->getParent() == ScheduleEnd->getParent() &&
7966          "Instruction is in wrong basic block.");
7967   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7968                    nullptr);
7969   ScheduleEnd = I->getNextNode();
7970   if (isOneOf(S, I) != I)
7971     CheckScheduleForI(I);
7972   assert(ScheduleEnd && "tried to vectorize a terminator?");
7973   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7974   return true;
7975 }
7976 
7977 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7978                                                 Instruction *ToI,
7979                                                 ScheduleData *PrevLoadStore,
7980                                                 ScheduleData *NextLoadStore) {
7981   ScheduleData *CurrentLoadStore = PrevLoadStore;
7982   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7983     // No need to allocate data for non-schedulable instructions.
7984     if (doesNotNeedToBeScheduled(I))
7985       continue;
7986     ScheduleData *SD = ScheduleDataMap.lookup(I);
7987     if (!SD) {
7988       SD = allocateScheduleDataChunks();
7989       ScheduleDataMap[I] = SD;
7990       SD->Inst = I;
7991     }
7992     assert(!isInSchedulingRegion(SD) &&
7993            "new ScheduleData already in scheduling region");
7994     SD->init(SchedulingRegionID, I);
7995 
7996     if (I->mayReadOrWriteMemory() &&
7997         (!isa<IntrinsicInst>(I) ||
7998          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
7999           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8000               Intrinsic::pseudoprobe))) {
8001       // Update the linked list of memory accessing instructions.
8002       if (CurrentLoadStore) {
8003         CurrentLoadStore->NextLoadStore = SD;
8004       } else {
8005         FirstLoadStoreInRegion = SD;
8006       }
8007       CurrentLoadStore = SD;
8008     }
8009 
8010     if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8011         match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8012       RegionHasStackSave = true;
8013   }
8014   if (NextLoadStore) {
8015     if (CurrentLoadStore)
8016       CurrentLoadStore->NextLoadStore = NextLoadStore;
8017   } else {
8018     LastLoadStoreInRegion = CurrentLoadStore;
8019   }
8020 }
8021 
8022 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8023                                                      bool InsertInReadyList,
8024                                                      BoUpSLP *SLP) {
8025   assert(SD->isSchedulingEntity());
8026 
8027   SmallVector<ScheduleData *, 10> WorkList;
8028   WorkList.push_back(SD);
8029 
8030   while (!WorkList.empty()) {
8031     ScheduleData *SD = WorkList.pop_back_val();
8032     for (ScheduleData *BundleMember = SD; BundleMember;
8033          BundleMember = BundleMember->NextInBundle) {
8034       assert(isInSchedulingRegion(BundleMember));
8035       if (BundleMember->hasValidDependencies())
8036         continue;
8037 
8038       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8039                  << "\n");
8040       BundleMember->Dependencies = 0;
8041       BundleMember->resetUnscheduledDeps();
8042 
8043       // Handle def-use chain dependencies.
8044       if (BundleMember->OpValue != BundleMember->Inst) {
8045         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8046           BundleMember->Dependencies++;
8047           ScheduleData *DestBundle = UseSD->FirstInBundle;
8048           if (!DestBundle->IsScheduled)
8049             BundleMember->incrementUnscheduledDeps(1);
8050           if (!DestBundle->hasValidDependencies())
8051             WorkList.push_back(DestBundle);
8052         }
8053       } else {
8054         for (User *U : BundleMember->Inst->users()) {
8055           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8056             BundleMember->Dependencies++;
8057             ScheduleData *DestBundle = UseSD->FirstInBundle;
8058             if (!DestBundle->IsScheduled)
8059               BundleMember->incrementUnscheduledDeps(1);
8060             if (!DestBundle->hasValidDependencies())
8061               WorkList.push_back(DestBundle);
8062           }
8063         }
8064       }
8065 
8066       auto makeControlDependent = [&](Instruction *I) {
8067         auto *DepDest = getScheduleData(I);
8068         assert(DepDest && "must be in schedule window");
8069         DepDest->ControlDependencies.push_back(BundleMember);
8070         BundleMember->Dependencies++;
8071         ScheduleData *DestBundle = DepDest->FirstInBundle;
8072         if (!DestBundle->IsScheduled)
8073           BundleMember->incrementUnscheduledDeps(1);
8074         if (!DestBundle->hasValidDependencies())
8075           WorkList.push_back(DestBundle);
8076       };
8077 
8078       // Any instruction which isn't safe to speculate at the begining of the
8079       // block is control dependend on any early exit or non-willreturn call
8080       // which proceeds it.
8081       if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
8082         for (Instruction *I = BundleMember->Inst->getNextNode();
8083              I != ScheduleEnd; I = I->getNextNode()) {
8084           if (isSafeToSpeculativelyExecute(I, &*BB->begin()))
8085             continue;
8086 
8087           // Add the dependency
8088           makeControlDependent(I);
8089 
8090           if (!isGuaranteedToTransferExecutionToSuccessor(I))
8091             // Everything past here must be control dependent on I.
8092             break;
8093         }
8094       }
8095 
8096       if (RegionHasStackSave) {
8097         // If we have an inalloc alloca instruction, it needs to be scheduled
8098         // after any preceeding stacksave.  We also need to prevent any alloca
8099         // from reordering above a preceeding stackrestore.
8100         if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
8101             match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
8102           for (Instruction *I = BundleMember->Inst->getNextNode();
8103                I != ScheduleEnd; I = I->getNextNode()) {
8104             if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
8105                 match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8106               // Any allocas past here must be control dependent on I, and I
8107               // must be memory dependend on BundleMember->Inst.
8108               break;
8109 
8110             if (!isa<AllocaInst>(I))
8111               continue;
8112 
8113             // Add the dependency
8114             makeControlDependent(I);
8115           }
8116         }
8117 
8118         // In addition to the cases handle just above, we need to prevent
8119         // allocas from moving below a stacksave.  The stackrestore case
8120         // is currently thought to be conservatism.
8121         if (isa<AllocaInst>(BundleMember->Inst)) {
8122           for (Instruction *I = BundleMember->Inst->getNextNode();
8123                I != ScheduleEnd; I = I->getNextNode()) {
8124             if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
8125                 !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
8126               continue;
8127 
8128             // Add the dependency
8129             makeControlDependent(I);
8130             break;
8131           }
8132         }
8133       }
8134 
8135       // Handle the memory dependencies (if any).
8136       ScheduleData *DepDest = BundleMember->NextLoadStore;
8137       if (!DepDest)
8138         continue;
8139       Instruction *SrcInst = BundleMember->Inst;
8140       assert(SrcInst->mayReadOrWriteMemory() &&
8141              "NextLoadStore list for non memory effecting bundle?");
8142       MemoryLocation SrcLoc = getLocation(SrcInst);
8143       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8144       unsigned numAliased = 0;
8145       unsigned DistToSrc = 1;
8146 
8147       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8148         assert(isInSchedulingRegion(DepDest));
8149 
8150         // We have two limits to reduce the complexity:
8151         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8152         //    SLP->isAliased (which is the expensive part in this loop).
8153         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8154         //    the whole loop (even if the loop is fast, it's quadratic).
8155         //    It's important for the loop break condition (see below) to
8156         //    check this limit even between two read-only instructions.
8157         if (DistToSrc >= MaxMemDepDistance ||
8158             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8159              (numAliased >= AliasedCheckLimit ||
8160               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8161 
8162           // We increment the counter only if the locations are aliased
8163           // (instead of counting all alias checks). This gives a better
8164           // balance between reduced runtime and accurate dependencies.
8165           numAliased++;
8166 
8167           DepDest->MemoryDependencies.push_back(BundleMember);
8168           BundleMember->Dependencies++;
8169           ScheduleData *DestBundle = DepDest->FirstInBundle;
8170           if (!DestBundle->IsScheduled) {
8171             BundleMember->incrementUnscheduledDeps(1);
8172           }
8173           if (!DestBundle->hasValidDependencies()) {
8174             WorkList.push_back(DestBundle);
8175           }
8176         }
8177 
8178         // Example, explaining the loop break condition: Let's assume our
8179         // starting instruction is i0 and MaxMemDepDistance = 3.
8180         //
8181         //                      +--------v--v--v
8182         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8183         //             +--------^--^--^
8184         //
8185         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8186         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8187         // Previously we already added dependencies from i3 to i6,i7,i8
8188         // (because of MaxMemDepDistance). As we added a dependency from
8189         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8190         // and we can abort this loop at i6.
8191         if (DistToSrc >= 2 * MaxMemDepDistance)
8192           break;
8193         DistToSrc++;
8194       }
8195     }
8196     if (InsertInReadyList && SD->isReady()) {
8197       ReadyInsts.insert(SD);
8198       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8199                         << "\n");
8200     }
8201   }
8202 }
8203 
8204 void BoUpSLP::BlockScheduling::resetSchedule() {
8205   assert(ScheduleStart &&
8206          "tried to reset schedule on block which has not been scheduled");
8207   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8208     doForAllOpcodes(I, [&](ScheduleData *SD) {
8209       assert(isInSchedulingRegion(SD) &&
8210              "ScheduleData not in scheduling region");
8211       SD->IsScheduled = false;
8212       SD->resetUnscheduledDeps();
8213     });
8214   }
8215   ReadyInsts.clear();
8216 }
8217 
8218 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8219   if (!BS->ScheduleStart)
8220     return;
8221 
8222   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8223 
8224   // A key point - if we got here, pre-scheduling was able to find a valid
8225   // scheduling of the sub-graph of the scheduling window which consists
8226   // of all vector bundles and their transitive users.  As such, we do not
8227   // need to reschedule anything *outside of* that subgraph.
8228 
8229   BS->resetSchedule();
8230 
8231   // For the real scheduling we use a more sophisticated ready-list: it is
8232   // sorted by the original instruction location. This lets the final schedule
8233   // be as  close as possible to the original instruction order.
8234   // WARNING: If changing this order causes a correctness issue, that means
8235   // there is some missing dependence edge in the schedule data graph.
8236   struct ScheduleDataCompare {
8237     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8238       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8239     }
8240   };
8241   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8242 
8243   // Ensure that all dependency data is updated (for nodes in the sub-graph)
8244   // and fill the ready-list with initial instructions.
8245   int Idx = 0;
8246   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8247        I = I->getNextNode()) {
8248     BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
8249       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8250       (void)SDTE;
8251       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8252               SD->isPartOfBundle() ==
8253                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8254              "scheduler and vectorizer bundle mismatch");
8255       SD->FirstInBundle->SchedulingPriority = Idx++;
8256 
8257       if (SD->isSchedulingEntity() && SD->isPartOfBundle())
8258         BS->calculateDependencies(SD, false, this);
8259     });
8260   }
8261   BS->initialFillReadyList(ReadyInsts);
8262 
8263   Instruction *LastScheduledInst = BS->ScheduleEnd;
8264 
8265   // Do the "real" scheduling.
8266   while (!ReadyInsts.empty()) {
8267     ScheduleData *picked = *ReadyInsts.begin();
8268     ReadyInsts.erase(ReadyInsts.begin());
8269 
8270     // Move the scheduled instruction(s) to their dedicated places, if not
8271     // there yet.
8272     for (ScheduleData *BundleMember = picked; BundleMember;
8273          BundleMember = BundleMember->NextInBundle) {
8274       Instruction *pickedInst = BundleMember->Inst;
8275       if (pickedInst->getNextNode() != LastScheduledInst)
8276         pickedInst->moveBefore(LastScheduledInst);
8277       LastScheduledInst = pickedInst;
8278     }
8279 
8280     BS->schedule(picked, ReadyInsts);
8281   }
8282 
8283   // Check that we didn't break any of our invariants.
8284 #ifdef EXPENSIVE_CHECKS
8285   BS->verify();
8286 #endif
8287 
8288 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8289   // Check that all schedulable entities got scheduled
8290   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8291     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8292       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8293         assert(SD->IsScheduled && "must be scheduled at this point");
8294       }
8295     });
8296   }
8297 #endif
8298 
8299   // Avoid duplicate scheduling of the block.
8300   BS->ScheduleStart = nullptr;
8301 }
8302 
8303 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8304   // If V is a store, just return the width of the stored value (or value
8305   // truncated just before storing) without traversing the expression tree.
8306   // This is the common case.
8307   if (auto *Store = dyn_cast<StoreInst>(V)) {
8308     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8309       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8310     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8311   }
8312 
8313   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8314     return getVectorElementSize(IEI->getOperand(1));
8315 
8316   auto E = InstrElementSize.find(V);
8317   if (E != InstrElementSize.end())
8318     return E->second;
8319 
8320   // If V is not a store, we can traverse the expression tree to find loads
8321   // that feed it. The type of the loaded value may indicate a more suitable
8322   // width than V's type. We want to base the vector element size on the width
8323   // of memory operations where possible.
8324   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8325   SmallPtrSet<Instruction *, 16> Visited;
8326   if (auto *I = dyn_cast<Instruction>(V)) {
8327     Worklist.emplace_back(I, I->getParent());
8328     Visited.insert(I);
8329   }
8330 
8331   // Traverse the expression tree in bottom-up order looking for loads. If we
8332   // encounter an instruction we don't yet handle, we give up.
8333   auto Width = 0u;
8334   while (!Worklist.empty()) {
8335     Instruction *I;
8336     BasicBlock *Parent;
8337     std::tie(I, Parent) = Worklist.pop_back_val();
8338 
8339     // We should only be looking at scalar instructions here. If the current
8340     // instruction has a vector type, skip.
8341     auto *Ty = I->getType();
8342     if (isa<VectorType>(Ty))
8343       continue;
8344 
8345     // If the current instruction is a load, update MaxWidth to reflect the
8346     // width of the loaded value.
8347     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8348         isa<ExtractValueInst>(I))
8349       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8350 
8351     // Otherwise, we need to visit the operands of the instruction. We only
8352     // handle the interesting cases from buildTree here. If an operand is an
8353     // instruction we haven't yet visited and from the same basic block as the
8354     // user or the use is a PHI node, we add it to the worklist.
8355     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8356              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8357              isa<UnaryOperator>(I)) {
8358       for (Use &U : I->operands())
8359         if (auto *J = dyn_cast<Instruction>(U.get()))
8360           if (Visited.insert(J).second &&
8361               (isa<PHINode>(I) || J->getParent() == Parent))
8362             Worklist.emplace_back(J, J->getParent());
8363     } else {
8364       break;
8365     }
8366   }
8367 
8368   // If we didn't encounter a memory access in the expression tree, or if we
8369   // gave up for some reason, just return the width of V. Otherwise, return the
8370   // maximum width we found.
8371   if (!Width) {
8372     if (auto *CI = dyn_cast<CmpInst>(V))
8373       V = CI->getOperand(0);
8374     Width = DL->getTypeSizeInBits(V->getType());
8375   }
8376 
8377   for (Instruction *I : Visited)
8378     InstrElementSize[I] = Width;
8379 
8380   return Width;
8381 }
8382 
8383 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8384 // smaller type with a truncation. We collect the values that will be demoted
8385 // in ToDemote and additional roots that require investigating in Roots.
8386 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8387                                   SmallVectorImpl<Value *> &ToDemote,
8388                                   SmallVectorImpl<Value *> &Roots) {
8389   // We can always demote constants.
8390   if (isa<Constant>(V)) {
8391     ToDemote.push_back(V);
8392     return true;
8393   }
8394 
8395   // If the value is not an instruction in the expression with only one use, it
8396   // cannot be demoted.
8397   auto *I = dyn_cast<Instruction>(V);
8398   if (!I || !I->hasOneUse() || !Expr.count(I))
8399     return false;
8400 
8401   switch (I->getOpcode()) {
8402 
8403   // We can always demote truncations and extensions. Since truncations can
8404   // seed additional demotion, we save the truncated value.
8405   case Instruction::Trunc:
8406     Roots.push_back(I->getOperand(0));
8407     break;
8408   case Instruction::ZExt:
8409   case Instruction::SExt:
8410     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8411         isa<InsertElementInst>(I->getOperand(0)))
8412       return false;
8413     break;
8414 
8415   // We can demote certain binary operations if we can demote both of their
8416   // operands.
8417   case Instruction::Add:
8418   case Instruction::Sub:
8419   case Instruction::Mul:
8420   case Instruction::And:
8421   case Instruction::Or:
8422   case Instruction::Xor:
8423     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8424         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8425       return false;
8426     break;
8427 
8428   // We can demote selects if we can demote their true and false values.
8429   case Instruction::Select: {
8430     SelectInst *SI = cast<SelectInst>(I);
8431     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8432         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8433       return false;
8434     break;
8435   }
8436 
8437   // We can demote phis if we can demote all their incoming operands. Note that
8438   // we don't need to worry about cycles since we ensure single use above.
8439   case Instruction::PHI: {
8440     PHINode *PN = cast<PHINode>(I);
8441     for (Value *IncValue : PN->incoming_values())
8442       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8443         return false;
8444     break;
8445   }
8446 
8447   // Otherwise, conservatively give up.
8448   default:
8449     return false;
8450   }
8451 
8452   // Record the value that we can demote.
8453   ToDemote.push_back(V);
8454   return true;
8455 }
8456 
8457 void BoUpSLP::computeMinimumValueSizes() {
8458   // If there are no external uses, the expression tree must be rooted by a
8459   // store. We can't demote in-memory values, so there is nothing to do here.
8460   if (ExternalUses.empty())
8461     return;
8462 
8463   // We only attempt to truncate integer expressions.
8464   auto &TreeRoot = VectorizableTree[0]->Scalars;
8465   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8466   if (!TreeRootIT)
8467     return;
8468 
8469   // If the expression is not rooted by a store, these roots should have
8470   // external uses. We will rely on InstCombine to rewrite the expression in
8471   // the narrower type. However, InstCombine only rewrites single-use values.
8472   // This means that if a tree entry other than a root is used externally, it
8473   // must have multiple uses and InstCombine will not rewrite it. The code
8474   // below ensures that only the roots are used externally.
8475   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8476   for (auto &EU : ExternalUses)
8477     if (!Expr.erase(EU.Scalar))
8478       return;
8479   if (!Expr.empty())
8480     return;
8481 
8482   // Collect the scalar values of the vectorizable expression. We will use this
8483   // context to determine which values can be demoted. If we see a truncation,
8484   // we mark it as seeding another demotion.
8485   for (auto &EntryPtr : VectorizableTree)
8486     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8487 
8488   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8489   // have a single external user that is not in the vectorizable tree.
8490   for (auto *Root : TreeRoot)
8491     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8492       return;
8493 
8494   // Conservatively determine if we can actually truncate the roots of the
8495   // expression. Collect the values that can be demoted in ToDemote and
8496   // additional roots that require investigating in Roots.
8497   SmallVector<Value *, 32> ToDemote;
8498   SmallVector<Value *, 4> Roots;
8499   for (auto *Root : TreeRoot)
8500     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8501       return;
8502 
8503   // The maximum bit width required to represent all the values that can be
8504   // demoted without loss of precision. It would be safe to truncate the roots
8505   // of the expression to this width.
8506   auto MaxBitWidth = 8u;
8507 
8508   // We first check if all the bits of the roots are demanded. If they're not,
8509   // we can truncate the roots to this narrower type.
8510   for (auto *Root : TreeRoot) {
8511     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8512     MaxBitWidth = std::max<unsigned>(
8513         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8514   }
8515 
8516   // True if the roots can be zero-extended back to their original type, rather
8517   // than sign-extended. We know that if the leading bits are not demanded, we
8518   // can safely zero-extend. So we initialize IsKnownPositive to True.
8519   bool IsKnownPositive = true;
8520 
8521   // If all the bits of the roots are demanded, we can try a little harder to
8522   // compute a narrower type. This can happen, for example, if the roots are
8523   // getelementptr indices. InstCombine promotes these indices to the pointer
8524   // width. Thus, all their bits are technically demanded even though the
8525   // address computation might be vectorized in a smaller type.
8526   //
8527   // We start by looking at each entry that can be demoted. We compute the
8528   // maximum bit width required to store the scalar by using ValueTracking to
8529   // compute the number of high-order bits we can truncate.
8530   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8531       llvm::all_of(TreeRoot, [](Value *R) {
8532         assert(R->hasOneUse() && "Root should have only one use!");
8533         return isa<GetElementPtrInst>(R->user_back());
8534       })) {
8535     MaxBitWidth = 8u;
8536 
8537     // Determine if the sign bit of all the roots is known to be zero. If not,
8538     // IsKnownPositive is set to False.
8539     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8540       KnownBits Known = computeKnownBits(R, *DL);
8541       return Known.isNonNegative();
8542     });
8543 
8544     // Determine the maximum number of bits required to store the scalar
8545     // values.
8546     for (auto *Scalar : ToDemote) {
8547       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8548       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8549       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8550     }
8551 
8552     // If we can't prove that the sign bit is zero, we must add one to the
8553     // maximum bit width to account for the unknown sign bit. This preserves
8554     // the existing sign bit so we can safely sign-extend the root back to the
8555     // original type. Otherwise, if we know the sign bit is zero, we will
8556     // zero-extend the root instead.
8557     //
8558     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8559     //        one to the maximum bit width will yield a larger-than-necessary
8560     //        type. In general, we need to add an extra bit only if we can't
8561     //        prove that the upper bit of the original type is equal to the
8562     //        upper bit of the proposed smaller type. If these two bits are the
8563     //        same (either zero or one) we know that sign-extending from the
8564     //        smaller type will result in the same value. Here, since we can't
8565     //        yet prove this, we are just making the proposed smaller type
8566     //        larger to ensure correctness.
8567     if (!IsKnownPositive)
8568       ++MaxBitWidth;
8569   }
8570 
8571   // Round MaxBitWidth up to the next power-of-two.
8572   if (!isPowerOf2_64(MaxBitWidth))
8573     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8574 
8575   // If the maximum bit width we compute is less than the with of the roots'
8576   // type, we can proceed with the narrowing. Otherwise, do nothing.
8577   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8578     return;
8579 
8580   // If we can truncate the root, we must collect additional values that might
8581   // be demoted as a result. That is, those seeded by truncations we will
8582   // modify.
8583   while (!Roots.empty())
8584     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8585 
8586   // Finally, map the values we can demote to the maximum bit with we computed.
8587   for (auto *Scalar : ToDemote)
8588     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8589 }
8590 
8591 namespace {
8592 
8593 /// The SLPVectorizer Pass.
8594 struct SLPVectorizer : public FunctionPass {
8595   SLPVectorizerPass Impl;
8596 
8597   /// Pass identification, replacement for typeid
8598   static char ID;
8599 
8600   explicit SLPVectorizer() : FunctionPass(ID) {
8601     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8602   }
8603 
8604   bool doInitialization(Module &M) override { return false; }
8605 
8606   bool runOnFunction(Function &F) override {
8607     if (skipFunction(F))
8608       return false;
8609 
8610     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8611     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8612     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8613     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8614     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8615     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8616     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8617     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8618     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8619     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8620 
8621     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8622   }
8623 
8624   void getAnalysisUsage(AnalysisUsage &AU) const override {
8625     FunctionPass::getAnalysisUsage(AU);
8626     AU.addRequired<AssumptionCacheTracker>();
8627     AU.addRequired<ScalarEvolutionWrapperPass>();
8628     AU.addRequired<AAResultsWrapperPass>();
8629     AU.addRequired<TargetTransformInfoWrapperPass>();
8630     AU.addRequired<LoopInfoWrapperPass>();
8631     AU.addRequired<DominatorTreeWrapperPass>();
8632     AU.addRequired<DemandedBitsWrapperPass>();
8633     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8634     AU.addRequired<InjectTLIMappingsLegacy>();
8635     AU.addPreserved<LoopInfoWrapperPass>();
8636     AU.addPreserved<DominatorTreeWrapperPass>();
8637     AU.addPreserved<AAResultsWrapperPass>();
8638     AU.addPreserved<GlobalsAAWrapperPass>();
8639     AU.setPreservesCFG();
8640   }
8641 };
8642 
8643 } // end anonymous namespace
8644 
8645 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8646   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8647   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8648   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8649   auto *AA = &AM.getResult<AAManager>(F);
8650   auto *LI = &AM.getResult<LoopAnalysis>(F);
8651   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8652   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8653   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8654   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8655 
8656   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
8657   if (!Changed)
8658     return PreservedAnalyses::all();
8659 
8660   PreservedAnalyses PA;
8661   PA.preserveSet<CFGAnalyses>();
8662   return PA;
8663 }
8664 
8665 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8666                                 TargetTransformInfo *TTI_,
8667                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8668                                 LoopInfo *LI_, DominatorTree *DT_,
8669                                 AssumptionCache *AC_, DemandedBits *DB_,
8670                                 OptimizationRemarkEmitter *ORE_) {
8671   if (!RunSLPVectorization)
8672     return false;
8673   SE = SE_;
8674   TTI = TTI_;
8675   TLI = TLI_;
8676   AA = AA_;
8677   LI = LI_;
8678   DT = DT_;
8679   AC = AC_;
8680   DB = DB_;
8681   DL = &F.getParent()->getDataLayout();
8682 
8683   Stores.clear();
8684   GEPs.clear();
8685   bool Changed = false;
8686 
8687   // If the target claims to have no vector registers don't attempt
8688   // vectorization.
8689   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8690     LLVM_DEBUG(
8691         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8692     return false;
8693   }
8694 
8695   // Don't vectorize when the attribute NoImplicitFloat is used.
8696   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8697     return false;
8698 
8699   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8700 
8701   // Use the bottom up slp vectorizer to construct chains that start with
8702   // store instructions.
8703   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
8704 
8705   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8706   // delete instructions.
8707 
8708   // Update DFS numbers now so that we can use them for ordering.
8709   DT->updateDFSNumbers();
8710 
8711   // Scan the blocks in the function in post order.
8712   for (auto BB : post_order(&F.getEntryBlock())) {
8713     collectSeedInstructions(BB);
8714 
8715     // Vectorize trees that end at stores.
8716     if (!Stores.empty()) {
8717       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8718                         << " underlying objects.\n");
8719       Changed |= vectorizeStoreChains(R);
8720     }
8721 
8722     // Vectorize trees that end at reductions.
8723     Changed |= vectorizeChainsInBlock(BB, R);
8724 
8725     // Vectorize the index computations of getelementptr instructions. This
8726     // is primarily intended to catch gather-like idioms ending at
8727     // non-consecutive loads.
8728     if (!GEPs.empty()) {
8729       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8730                         << " underlying objects.\n");
8731       Changed |= vectorizeGEPIndices(BB, R);
8732     }
8733   }
8734 
8735   if (Changed) {
8736     R.optimizeGatherSequence();
8737     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8738   }
8739   return Changed;
8740 }
8741 
8742 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8743                                             unsigned Idx) {
8744   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8745                     << "\n");
8746   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8747   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8748   unsigned VF = Chain.size();
8749 
8750   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8751     return false;
8752 
8753   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8754                     << "\n");
8755 
8756   R.buildTree(Chain);
8757   if (R.isTreeTinyAndNotFullyVectorizable())
8758     return false;
8759   if (R.isLoadCombineCandidate())
8760     return false;
8761   R.reorderTopToBottom();
8762   R.reorderBottomToTop();
8763   R.buildExternalUses();
8764 
8765   R.computeMinimumValueSizes();
8766 
8767   InstructionCost Cost = R.getTreeCost();
8768 
8769   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8770   if (Cost < -SLPCostThreshold) {
8771     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8772 
8773     using namespace ore;
8774 
8775     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8776                                         cast<StoreInst>(Chain[0]))
8777                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8778                      << " and with tree size "
8779                      << NV("TreeSize", R.getTreeSize()));
8780 
8781     R.vectorizeTree();
8782     return true;
8783   }
8784 
8785   return false;
8786 }
8787 
8788 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8789                                         BoUpSLP &R) {
8790   // We may run into multiple chains that merge into a single chain. We mark the
8791   // stores that we vectorized so that we don't visit the same store twice.
8792   BoUpSLP::ValueSet VectorizedStores;
8793   bool Changed = false;
8794 
8795   int E = Stores.size();
8796   SmallBitVector Tails(E, false);
8797   int MaxIter = MaxStoreLookup.getValue();
8798   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8799       E, std::make_pair(E, INT_MAX));
8800   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8801   int IterCnt;
8802   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8803                                   &CheckedPairs,
8804                                   &ConsecutiveChain](int K, int Idx) {
8805     if (IterCnt >= MaxIter)
8806       return true;
8807     if (CheckedPairs[Idx].test(K))
8808       return ConsecutiveChain[K].second == 1 &&
8809              ConsecutiveChain[K].first == Idx;
8810     ++IterCnt;
8811     CheckedPairs[Idx].set(K);
8812     CheckedPairs[K].set(Idx);
8813     Optional<int> Diff = getPointersDiff(
8814         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8815         Stores[Idx]->getValueOperand()->getType(),
8816         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8817     if (!Diff || *Diff == 0)
8818       return false;
8819     int Val = *Diff;
8820     if (Val < 0) {
8821       if (ConsecutiveChain[Idx].second > -Val) {
8822         Tails.set(K);
8823         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8824       }
8825       return false;
8826     }
8827     if (ConsecutiveChain[K].second <= Val)
8828       return false;
8829 
8830     Tails.set(Idx);
8831     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8832     return Val == 1;
8833   };
8834   // Do a quadratic search on all of the given stores in reverse order and find
8835   // all of the pairs of stores that follow each other.
8836   for (int Idx = E - 1; Idx >= 0; --Idx) {
8837     // If a store has multiple consecutive store candidates, search according
8838     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8839     // This is because usually pairing with immediate succeeding or preceding
8840     // candidate create the best chance to find slp vectorization opportunity.
8841     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8842     IterCnt = 0;
8843     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8844       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8845           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8846         break;
8847   }
8848 
8849   // Tracks if we tried to vectorize stores starting from the given tail
8850   // already.
8851   SmallBitVector TriedTails(E, false);
8852   // For stores that start but don't end a link in the chain:
8853   for (int Cnt = E; Cnt > 0; --Cnt) {
8854     int I = Cnt - 1;
8855     if (ConsecutiveChain[I].first == E || Tails.test(I))
8856       continue;
8857     // We found a store instr that starts a chain. Now follow the chain and try
8858     // to vectorize it.
8859     BoUpSLP::ValueList Operands;
8860     // Collect the chain into a list.
8861     while (I != E && !VectorizedStores.count(Stores[I])) {
8862       Operands.push_back(Stores[I]);
8863       Tails.set(I);
8864       if (ConsecutiveChain[I].second != 1) {
8865         // Mark the new end in the chain and go back, if required. It might be
8866         // required if the original stores come in reversed order, for example.
8867         if (ConsecutiveChain[I].first != E &&
8868             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8869             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8870           TriedTails.set(I);
8871           Tails.reset(ConsecutiveChain[I].first);
8872           if (Cnt < ConsecutiveChain[I].first + 2)
8873             Cnt = ConsecutiveChain[I].first + 2;
8874         }
8875         break;
8876       }
8877       // Move to the next value in the chain.
8878       I = ConsecutiveChain[I].first;
8879     }
8880     assert(!Operands.empty() && "Expected non-empty list of stores.");
8881 
8882     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8883     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8884     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8885 
8886     unsigned MinVF = R.getMinVF(EltSize);
8887     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8888                               MaxElts);
8889 
8890     // FIXME: Is division-by-2 the correct step? Should we assert that the
8891     // register size is a power-of-2?
8892     unsigned StartIdx = 0;
8893     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8894       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8895         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8896         if (!VectorizedStores.count(Slice.front()) &&
8897             !VectorizedStores.count(Slice.back()) &&
8898             vectorizeStoreChain(Slice, R, Cnt)) {
8899           // Mark the vectorized stores so that we don't vectorize them again.
8900           VectorizedStores.insert(Slice.begin(), Slice.end());
8901           Changed = true;
8902           // If we vectorized initial block, no need to try to vectorize it
8903           // again.
8904           if (Cnt == StartIdx)
8905             StartIdx += Size;
8906           Cnt += Size;
8907           continue;
8908         }
8909         ++Cnt;
8910       }
8911       // Check if the whole array was vectorized already - exit.
8912       if (StartIdx >= Operands.size())
8913         break;
8914     }
8915   }
8916 
8917   return Changed;
8918 }
8919 
8920 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8921   // Initialize the collections. We will make a single pass over the block.
8922   Stores.clear();
8923   GEPs.clear();
8924 
8925   // Visit the store and getelementptr instructions in BB and organize them in
8926   // Stores and GEPs according to the underlying objects of their pointer
8927   // operands.
8928   for (Instruction &I : *BB) {
8929     // Ignore store instructions that are volatile or have a pointer operand
8930     // that doesn't point to a scalar type.
8931     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8932       if (!SI->isSimple())
8933         continue;
8934       if (!isValidElementType(SI->getValueOperand()->getType()))
8935         continue;
8936       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8937     }
8938 
8939     // Ignore getelementptr instructions that have more than one index, a
8940     // constant index, or a pointer operand that doesn't point to a scalar
8941     // type.
8942     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8943       auto Idx = GEP->idx_begin()->get();
8944       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8945         continue;
8946       if (!isValidElementType(Idx->getType()))
8947         continue;
8948       if (GEP->getType()->isVectorTy())
8949         continue;
8950       GEPs[GEP->getPointerOperand()].push_back(GEP);
8951     }
8952   }
8953 }
8954 
8955 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8956   if (!A || !B)
8957     return false;
8958   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8959     return false;
8960   Value *VL[] = {A, B};
8961   return tryToVectorizeList(VL, R);
8962 }
8963 
8964 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8965                                            bool LimitForRegisterSize) {
8966   if (VL.size() < 2)
8967     return false;
8968 
8969   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8970                     << VL.size() << ".\n");
8971 
8972   // Check that all of the parts are instructions of the same type,
8973   // we permit an alternate opcode via InstructionsState.
8974   InstructionsState S = getSameOpcode(VL);
8975   if (!S.getOpcode())
8976     return false;
8977 
8978   Instruction *I0 = cast<Instruction>(S.OpValue);
8979   // Make sure invalid types (including vector type) are rejected before
8980   // determining vectorization factor for scalar instructions.
8981   for (Value *V : VL) {
8982     Type *Ty = V->getType();
8983     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8984       // NOTE: the following will give user internal llvm type name, which may
8985       // not be useful.
8986       R.getORE()->emit([&]() {
8987         std::string type_str;
8988         llvm::raw_string_ostream rso(type_str);
8989         Ty->print(rso);
8990         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8991                << "Cannot SLP vectorize list: type "
8992                << rso.str() + " is unsupported by vectorizer";
8993       });
8994       return false;
8995     }
8996   }
8997 
8998   unsigned Sz = R.getVectorElementSize(I0);
8999   unsigned MinVF = R.getMinVF(Sz);
9000   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
9001   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
9002   if (MaxVF < 2) {
9003     R.getORE()->emit([&]() {
9004       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
9005              << "Cannot SLP vectorize list: vectorization factor "
9006              << "less than 2 is not supported";
9007     });
9008     return false;
9009   }
9010 
9011   bool Changed = false;
9012   bool CandidateFound = false;
9013   InstructionCost MinCost = SLPCostThreshold.getValue();
9014   Type *ScalarTy = VL[0]->getType();
9015   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
9016     ScalarTy = IE->getOperand(1)->getType();
9017 
9018   unsigned NextInst = 0, MaxInst = VL.size();
9019   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
9020     // No actual vectorization should happen, if number of parts is the same as
9021     // provided vectorization factor (i.e. the scalar type is used for vector
9022     // code during codegen).
9023     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
9024     if (TTI->getNumberOfParts(VecTy) == VF)
9025       continue;
9026     for (unsigned I = NextInst; I < MaxInst; ++I) {
9027       unsigned OpsWidth = 0;
9028 
9029       if (I + VF > MaxInst)
9030         OpsWidth = MaxInst - I;
9031       else
9032         OpsWidth = VF;
9033 
9034       if (!isPowerOf2_32(OpsWidth))
9035         continue;
9036 
9037       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9038           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9039         break;
9040 
9041       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9042       // Check that a previous iteration of this loop did not delete the Value.
9043       if (llvm::any_of(Ops, [&R](Value *V) {
9044             auto *I = dyn_cast<Instruction>(V);
9045             return I && R.isDeleted(I);
9046           }))
9047         continue;
9048 
9049       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9050                         << "\n");
9051 
9052       R.buildTree(Ops);
9053       if (R.isTreeTinyAndNotFullyVectorizable())
9054         continue;
9055       R.reorderTopToBottom();
9056       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9057       R.buildExternalUses();
9058 
9059       R.computeMinimumValueSizes();
9060       InstructionCost Cost = R.getTreeCost();
9061       CandidateFound = true;
9062       MinCost = std::min(MinCost, Cost);
9063 
9064       if (Cost < -SLPCostThreshold) {
9065         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9066         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9067                                                     cast<Instruction>(Ops[0]))
9068                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9069                                  << " and with tree size "
9070                                  << ore::NV("TreeSize", R.getTreeSize()));
9071 
9072         R.vectorizeTree();
9073         // Move to the next bundle.
9074         I += VF - 1;
9075         NextInst = I + 1;
9076         Changed = true;
9077       }
9078     }
9079   }
9080 
9081   if (!Changed && CandidateFound) {
9082     R.getORE()->emit([&]() {
9083       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9084              << "List vectorization was possible but not beneficial with cost "
9085              << ore::NV("Cost", MinCost) << " >= "
9086              << ore::NV("Treshold", -SLPCostThreshold);
9087     });
9088   } else if (!Changed) {
9089     R.getORE()->emit([&]() {
9090       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9091              << "Cannot SLP vectorize list: vectorization was impossible"
9092              << " with available vectorization factors";
9093     });
9094   }
9095   return Changed;
9096 }
9097 
9098 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9099   if (!I)
9100     return false;
9101 
9102   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9103     return false;
9104 
9105   Value *P = I->getParent();
9106 
9107   // Vectorize in current basic block only.
9108   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9109   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9110   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9111     return false;
9112 
9113   // Try to vectorize V.
9114   if (tryToVectorizePair(Op0, Op1, R))
9115     return true;
9116 
9117   auto *A = dyn_cast<BinaryOperator>(Op0);
9118   auto *B = dyn_cast<BinaryOperator>(Op1);
9119   // Try to skip B.
9120   if (B && B->hasOneUse()) {
9121     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9122     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9123     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9124       return true;
9125     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9126       return true;
9127   }
9128 
9129   // Try to skip A.
9130   if (A && A->hasOneUse()) {
9131     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9132     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9133     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9134       return true;
9135     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9136       return true;
9137   }
9138   return false;
9139 }
9140 
9141 namespace {
9142 
9143 /// Model horizontal reductions.
9144 ///
9145 /// A horizontal reduction is a tree of reduction instructions that has values
9146 /// that can be put into a vector as its leaves. For example:
9147 ///
9148 /// mul mul mul mul
9149 ///  \  /    \  /
9150 ///   +       +
9151 ///    \     /
9152 ///       +
9153 /// This tree has "mul" as its leaf values and "+" as its reduction
9154 /// instructions. A reduction can feed into a store or a binary operation
9155 /// feeding a phi.
9156 ///    ...
9157 ///    \  /
9158 ///     +
9159 ///     |
9160 ///  phi +=
9161 ///
9162 ///  Or:
9163 ///    ...
9164 ///    \  /
9165 ///     +
9166 ///     |
9167 ///   *p =
9168 ///
9169 class HorizontalReduction {
9170   using ReductionOpsType = SmallVector<Value *, 16>;
9171   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9172   ReductionOpsListType ReductionOps;
9173   SmallVector<Value *, 32> ReducedVals;
9174   // Use map vector to make stable output.
9175   MapVector<Instruction *, Value *> ExtraArgs;
9176   WeakTrackingVH ReductionRoot;
9177   /// The type of reduction operation.
9178   RecurKind RdxKind;
9179 
9180   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9181 
9182   static bool isCmpSelMinMax(Instruction *I) {
9183     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9184            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9185   }
9186 
9187   // And/or are potentially poison-safe logical patterns like:
9188   // select x, y, false
9189   // select x, true, y
9190   static bool isBoolLogicOp(Instruction *I) {
9191     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9192            match(I, m_LogicalOr(m_Value(), m_Value()));
9193   }
9194 
9195   /// Checks if instruction is associative and can be vectorized.
9196   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9197     if (Kind == RecurKind::None)
9198       return false;
9199 
9200     // Integer ops that map to select instructions or intrinsics are fine.
9201     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9202         isBoolLogicOp(I))
9203       return true;
9204 
9205     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9206       // FP min/max are associative except for NaN and -0.0. We do not
9207       // have to rule out -0.0 here because the intrinsic semantics do not
9208       // specify a fixed result for it.
9209       return I->getFastMathFlags().noNaNs();
9210     }
9211 
9212     return I->isAssociative();
9213   }
9214 
9215   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9216     // Poison-safe 'or' takes the form: select X, true, Y
9217     // To make that work with the normal operand processing, we skip the
9218     // true value operand.
9219     // TODO: Change the code and data structures to handle this without a hack.
9220     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9221       return I->getOperand(2);
9222     return I->getOperand(Index);
9223   }
9224 
9225   /// Checks if the ParentStackElem.first should be marked as a reduction
9226   /// operation with an extra argument or as extra argument itself.
9227   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9228                     Value *ExtraArg) {
9229     if (ExtraArgs.count(ParentStackElem.first)) {
9230       ExtraArgs[ParentStackElem.first] = nullptr;
9231       // We ran into something like:
9232       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9233       // The whole ParentStackElem.first should be considered as an extra value
9234       // in this case.
9235       // Do not perform analysis of remaining operands of ParentStackElem.first
9236       // instruction, this whole instruction is an extra argument.
9237       ParentStackElem.second = INVALID_OPERAND_INDEX;
9238     } else {
9239       // We ran into something like:
9240       // ParentStackElem.first += ... + ExtraArg + ...
9241       ExtraArgs[ParentStackElem.first] = ExtraArg;
9242     }
9243   }
9244 
9245   /// Creates reduction operation with the current opcode.
9246   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9247                          Value *RHS, const Twine &Name, bool UseSelect) {
9248     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9249     switch (Kind) {
9250     case RecurKind::Or:
9251       if (UseSelect &&
9252           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9253         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9254       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9255                                  Name);
9256     case RecurKind::And:
9257       if (UseSelect &&
9258           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9259         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9260       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9261                                  Name);
9262     case RecurKind::Add:
9263     case RecurKind::Mul:
9264     case RecurKind::Xor:
9265     case RecurKind::FAdd:
9266     case RecurKind::FMul:
9267       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9268                                  Name);
9269     case RecurKind::FMax:
9270       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9271     case RecurKind::FMin:
9272       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9273     case RecurKind::SMax:
9274       if (UseSelect) {
9275         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9276         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9277       }
9278       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9279     case RecurKind::SMin:
9280       if (UseSelect) {
9281         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9282         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9283       }
9284       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9285     case RecurKind::UMax:
9286       if (UseSelect) {
9287         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9288         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9289       }
9290       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9291     case RecurKind::UMin:
9292       if (UseSelect) {
9293         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9294         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9295       }
9296       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9297     default:
9298       llvm_unreachable("Unknown reduction operation.");
9299     }
9300   }
9301 
9302   /// Creates reduction operation with the current opcode with the IR flags
9303   /// from \p ReductionOps.
9304   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9305                          Value *RHS, const Twine &Name,
9306                          const ReductionOpsListType &ReductionOps) {
9307     bool UseSelect = ReductionOps.size() == 2 ||
9308                      // Logical or/and.
9309                      (ReductionOps.size() == 1 &&
9310                       isa<SelectInst>(ReductionOps.front().front()));
9311     assert((!UseSelect || ReductionOps.size() != 2 ||
9312             isa<SelectInst>(ReductionOps[1][0])) &&
9313            "Expected cmp + select pairs for reduction");
9314     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9315     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9316       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9317         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9318         propagateIRFlags(Op, ReductionOps[1]);
9319         return Op;
9320       }
9321     }
9322     propagateIRFlags(Op, ReductionOps[0]);
9323     return Op;
9324   }
9325 
9326   /// Creates reduction operation with the current opcode with the IR flags
9327   /// from \p I.
9328   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9329                          Value *RHS, const Twine &Name, Instruction *I) {
9330     auto *SelI = dyn_cast<SelectInst>(I);
9331     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9332     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9333       if (auto *Sel = dyn_cast<SelectInst>(Op))
9334         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9335     }
9336     propagateIRFlags(Op, I);
9337     return Op;
9338   }
9339 
9340   static RecurKind getRdxKind(Instruction *I) {
9341     assert(I && "Expected instruction for reduction matching");
9342     if (match(I, m_Add(m_Value(), m_Value())))
9343       return RecurKind::Add;
9344     if (match(I, m_Mul(m_Value(), m_Value())))
9345       return RecurKind::Mul;
9346     if (match(I, m_And(m_Value(), m_Value())) ||
9347         match(I, m_LogicalAnd(m_Value(), m_Value())))
9348       return RecurKind::And;
9349     if (match(I, m_Or(m_Value(), m_Value())) ||
9350         match(I, m_LogicalOr(m_Value(), m_Value())))
9351       return RecurKind::Or;
9352     if (match(I, m_Xor(m_Value(), m_Value())))
9353       return RecurKind::Xor;
9354     if (match(I, m_FAdd(m_Value(), m_Value())))
9355       return RecurKind::FAdd;
9356     if (match(I, m_FMul(m_Value(), m_Value())))
9357       return RecurKind::FMul;
9358 
9359     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9360       return RecurKind::FMax;
9361     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9362       return RecurKind::FMin;
9363 
9364     // This matches either cmp+select or intrinsics. SLP is expected to handle
9365     // either form.
9366     // TODO: If we are canonicalizing to intrinsics, we can remove several
9367     //       special-case paths that deal with selects.
9368     if (match(I, m_SMax(m_Value(), m_Value())))
9369       return RecurKind::SMax;
9370     if (match(I, m_SMin(m_Value(), m_Value())))
9371       return RecurKind::SMin;
9372     if (match(I, m_UMax(m_Value(), m_Value())))
9373       return RecurKind::UMax;
9374     if (match(I, m_UMin(m_Value(), m_Value())))
9375       return RecurKind::UMin;
9376 
9377     if (auto *Select = dyn_cast<SelectInst>(I)) {
9378       // Try harder: look for min/max pattern based on instructions producing
9379       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9380       // During the intermediate stages of SLP, it's very common to have
9381       // pattern like this (since optimizeGatherSequence is run only once
9382       // at the end):
9383       // %1 = extractelement <2 x i32> %a, i32 0
9384       // %2 = extractelement <2 x i32> %a, i32 1
9385       // %cond = icmp sgt i32 %1, %2
9386       // %3 = extractelement <2 x i32> %a, i32 0
9387       // %4 = extractelement <2 x i32> %a, i32 1
9388       // %select = select i1 %cond, i32 %3, i32 %4
9389       CmpInst::Predicate Pred;
9390       Instruction *L1;
9391       Instruction *L2;
9392 
9393       Value *LHS = Select->getTrueValue();
9394       Value *RHS = Select->getFalseValue();
9395       Value *Cond = Select->getCondition();
9396 
9397       // TODO: Support inverse predicates.
9398       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9399         if (!isa<ExtractElementInst>(RHS) ||
9400             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9401           return RecurKind::None;
9402       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9403         if (!isa<ExtractElementInst>(LHS) ||
9404             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9405           return RecurKind::None;
9406       } else {
9407         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9408           return RecurKind::None;
9409         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9410             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9411             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9412           return RecurKind::None;
9413       }
9414 
9415       switch (Pred) {
9416       default:
9417         return RecurKind::None;
9418       case CmpInst::ICMP_SGT:
9419       case CmpInst::ICMP_SGE:
9420         return RecurKind::SMax;
9421       case CmpInst::ICMP_SLT:
9422       case CmpInst::ICMP_SLE:
9423         return RecurKind::SMin;
9424       case CmpInst::ICMP_UGT:
9425       case CmpInst::ICMP_UGE:
9426         return RecurKind::UMax;
9427       case CmpInst::ICMP_ULT:
9428       case CmpInst::ICMP_ULE:
9429         return RecurKind::UMin;
9430       }
9431     }
9432     return RecurKind::None;
9433   }
9434 
9435   /// Get the index of the first operand.
9436   static unsigned getFirstOperandIndex(Instruction *I) {
9437     return isCmpSelMinMax(I) ? 1 : 0;
9438   }
9439 
9440   /// Total number of operands in the reduction operation.
9441   static unsigned getNumberOfOperands(Instruction *I) {
9442     return isCmpSelMinMax(I) ? 3 : 2;
9443   }
9444 
9445   /// Checks if the instruction is in basic block \p BB.
9446   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9447   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9448     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9449       auto *Sel = cast<SelectInst>(I);
9450       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9451       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9452     }
9453     return I->getParent() == BB;
9454   }
9455 
9456   /// Expected number of uses for reduction operations/reduced values.
9457   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9458     if (IsCmpSelMinMax) {
9459       // SelectInst must be used twice while the condition op must have single
9460       // use only.
9461       if (auto *Sel = dyn_cast<SelectInst>(I))
9462         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9463       return I->hasNUses(2);
9464     }
9465 
9466     // Arithmetic reduction operation must be used once only.
9467     return I->hasOneUse();
9468   }
9469 
9470   /// Initializes the list of reduction operations.
9471   void initReductionOps(Instruction *I) {
9472     if (isCmpSelMinMax(I))
9473       ReductionOps.assign(2, ReductionOpsType());
9474     else
9475       ReductionOps.assign(1, ReductionOpsType());
9476   }
9477 
9478   /// Add all reduction operations for the reduction instruction \p I.
9479   void addReductionOps(Instruction *I) {
9480     if (isCmpSelMinMax(I)) {
9481       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9482       ReductionOps[1].emplace_back(I);
9483     } else {
9484       ReductionOps[0].emplace_back(I);
9485     }
9486   }
9487 
9488   static Value *getLHS(RecurKind Kind, Instruction *I) {
9489     if (Kind == RecurKind::None)
9490       return nullptr;
9491     return I->getOperand(getFirstOperandIndex(I));
9492   }
9493   static Value *getRHS(RecurKind Kind, Instruction *I) {
9494     if (Kind == RecurKind::None)
9495       return nullptr;
9496     return I->getOperand(getFirstOperandIndex(I) + 1);
9497   }
9498 
9499 public:
9500   HorizontalReduction() = default;
9501 
9502   /// Try to find a reduction tree.
9503   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9504     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9505            "Phi needs to use the binary operator");
9506     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9507             isa<IntrinsicInst>(Inst)) &&
9508            "Expected binop, select, or intrinsic for reduction matching");
9509     RdxKind = getRdxKind(Inst);
9510 
9511     // We could have a initial reductions that is not an add.
9512     //  r *= v1 + v2 + v3 + v4
9513     // In such a case start looking for a tree rooted in the first '+'.
9514     if (Phi) {
9515       if (getLHS(RdxKind, Inst) == Phi) {
9516         Phi = nullptr;
9517         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9518         if (!Inst)
9519           return false;
9520         RdxKind = getRdxKind(Inst);
9521       } else if (getRHS(RdxKind, Inst) == Phi) {
9522         Phi = nullptr;
9523         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9524         if (!Inst)
9525           return false;
9526         RdxKind = getRdxKind(Inst);
9527       }
9528     }
9529 
9530     if (!isVectorizable(RdxKind, Inst))
9531       return false;
9532 
9533     // Analyze "regular" integer/FP types for reductions - no target-specific
9534     // types or pointers.
9535     Type *Ty = Inst->getType();
9536     if (!isValidElementType(Ty) || Ty->isPointerTy())
9537       return false;
9538 
9539     // Though the ultimate reduction may have multiple uses, its condition must
9540     // have only single use.
9541     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9542       if (!Sel->getCondition()->hasOneUse())
9543         return false;
9544 
9545     ReductionRoot = Inst;
9546 
9547     // The opcode for leaf values that we perform a reduction on.
9548     // For example: load(x) + load(y) + load(z) + fptoui(w)
9549     // The leaf opcode for 'w' does not match, so we don't include it as a
9550     // potential candidate for the reduction.
9551     unsigned LeafOpcode = 0;
9552 
9553     // Post-order traverse the reduction tree starting at Inst. We only handle
9554     // true trees containing binary operators or selects.
9555     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9556     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9557     initReductionOps(Inst);
9558     while (!Stack.empty()) {
9559       Instruction *TreeN = Stack.back().first;
9560       unsigned EdgeToVisit = Stack.back().second++;
9561       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9562       bool IsReducedValue = TreeRdxKind != RdxKind;
9563 
9564       // Postorder visit.
9565       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9566         if (IsReducedValue)
9567           ReducedVals.push_back(TreeN);
9568         else {
9569           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9570           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9571             // Check if TreeN is an extra argument of its parent operation.
9572             if (Stack.size() <= 1) {
9573               // TreeN can't be an extra argument as it is a root reduction
9574               // operation.
9575               return false;
9576             }
9577             // Yes, TreeN is an extra argument, do not add it to a list of
9578             // reduction operations.
9579             // Stack[Stack.size() - 2] always points to the parent operation.
9580             markExtraArg(Stack[Stack.size() - 2], TreeN);
9581             ExtraArgs.erase(TreeN);
9582           } else
9583             addReductionOps(TreeN);
9584         }
9585         // Retract.
9586         Stack.pop_back();
9587         continue;
9588       }
9589 
9590       // Visit operands.
9591       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9592       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9593       if (!EdgeInst) {
9594         // Edge value is not a reduction instruction or a leaf instruction.
9595         // (It may be a constant, function argument, or something else.)
9596         markExtraArg(Stack.back(), EdgeVal);
9597         continue;
9598       }
9599       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9600       // Continue analysis if the next operand is a reduction operation or
9601       // (possibly) a leaf value. If the leaf value opcode is not set,
9602       // the first met operation != reduction operation is considered as the
9603       // leaf opcode.
9604       // Only handle trees in the current basic block.
9605       // Each tree node needs to have minimal number of users except for the
9606       // ultimate reduction.
9607       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9608       if (EdgeInst != Phi && EdgeInst != Inst &&
9609           hasSameParent(EdgeInst, Inst->getParent()) &&
9610           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9611           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9612         if (IsRdxInst) {
9613           // We need to be able to reassociate the reduction operations.
9614           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9615             // I is an extra argument for TreeN (its parent operation).
9616             markExtraArg(Stack.back(), EdgeInst);
9617             continue;
9618           }
9619         } else if (!LeafOpcode) {
9620           LeafOpcode = EdgeInst->getOpcode();
9621         }
9622         Stack.push_back(
9623             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9624         continue;
9625       }
9626       // I is an extra argument for TreeN (its parent operation).
9627       markExtraArg(Stack.back(), EdgeInst);
9628     }
9629     return true;
9630   }
9631 
9632   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9633   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9634     // If there are a sufficient number of reduction values, reduce
9635     // to a nearby power-of-2. We can safely generate oversized
9636     // vectors and rely on the backend to split them to legal sizes.
9637     unsigned NumReducedVals = ReducedVals.size();
9638     if (NumReducedVals < 4)
9639       return nullptr;
9640 
9641     // Intersect the fast-math-flags from all reduction operations.
9642     FastMathFlags RdxFMF;
9643     RdxFMF.set();
9644     for (ReductionOpsType &RdxOp : ReductionOps) {
9645       for (Value *RdxVal : RdxOp) {
9646         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9647           RdxFMF &= FPMO->getFastMathFlags();
9648       }
9649     }
9650 
9651     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9652     Builder.setFastMathFlags(RdxFMF);
9653 
9654     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9655     // The same extra argument may be used several times, so log each attempt
9656     // to use it.
9657     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9658       assert(Pair.first && "DebugLoc must be set.");
9659       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9660     }
9661 
9662     // The compare instruction of a min/max is the insertion point for new
9663     // instructions and may be replaced with a new compare instruction.
9664     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9665       assert(isa<SelectInst>(RdxRootInst) &&
9666              "Expected min/max reduction to have select root instruction");
9667       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9668       assert(isa<Instruction>(ScalarCond) &&
9669              "Expected min/max reduction to have compare condition");
9670       return cast<Instruction>(ScalarCond);
9671     };
9672 
9673     // The reduction root is used as the insertion point for new instructions,
9674     // so set it as externally used to prevent it from being deleted.
9675     ExternallyUsedValues[ReductionRoot];
9676     SmallVector<Value *, 16> IgnoreList;
9677     for (ReductionOpsType &RdxOp : ReductionOps)
9678       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9679 
9680     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9681     if (NumReducedVals > ReduxWidth) {
9682       // In the loop below, we are building a tree based on a window of
9683       // 'ReduxWidth' values.
9684       // If the operands of those values have common traits (compare predicate,
9685       // constant operand, etc), then we want to group those together to
9686       // minimize the cost of the reduction.
9687 
9688       // TODO: This should be extended to count common operands for
9689       //       compares and binops.
9690 
9691       // Step 1: Count the number of times each compare predicate occurs.
9692       SmallDenseMap<unsigned, unsigned> PredCountMap;
9693       for (Value *RdxVal : ReducedVals) {
9694         CmpInst::Predicate Pred;
9695         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9696           ++PredCountMap[Pred];
9697       }
9698       // Step 2: Sort the values so the most common predicates come first.
9699       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9700         CmpInst::Predicate PredA, PredB;
9701         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9702             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9703           return PredCountMap[PredA] > PredCountMap[PredB];
9704         }
9705         return false;
9706       });
9707     }
9708 
9709     Value *VectorizedTree = nullptr;
9710     unsigned i = 0;
9711     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9712       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9713       V.buildTree(VL, IgnoreList);
9714       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9715         break;
9716       if (V.isLoadCombineReductionCandidate(RdxKind))
9717         break;
9718       V.reorderTopToBottom();
9719       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9720       V.buildExternalUses(ExternallyUsedValues);
9721 
9722       // For a poison-safe boolean logic reduction, do not replace select
9723       // instructions with logic ops. All reduced values will be frozen (see
9724       // below) to prevent leaking poison.
9725       if (isa<SelectInst>(ReductionRoot) &&
9726           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9727           NumReducedVals != ReduxWidth)
9728         break;
9729 
9730       V.computeMinimumValueSizes();
9731 
9732       // Estimate cost.
9733       InstructionCost TreeCost =
9734           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9735       InstructionCost ReductionCost =
9736           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9737       InstructionCost Cost = TreeCost + ReductionCost;
9738       if (!Cost.isValid()) {
9739         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9740         return nullptr;
9741       }
9742       if (Cost >= -SLPCostThreshold) {
9743         V.getORE()->emit([&]() {
9744           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9745                                           cast<Instruction>(VL[0]))
9746                  << "Vectorizing horizontal reduction is possible"
9747                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9748                  << " and threshold "
9749                  << ore::NV("Threshold", -SLPCostThreshold);
9750         });
9751         break;
9752       }
9753 
9754       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9755                         << Cost << ". (HorRdx)\n");
9756       V.getORE()->emit([&]() {
9757         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9758                                   cast<Instruction>(VL[0]))
9759                << "Vectorized horizontal reduction with cost "
9760                << ore::NV("Cost", Cost) << " and with tree size "
9761                << ore::NV("TreeSize", V.getTreeSize());
9762       });
9763 
9764       // Vectorize a tree.
9765       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9766       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9767 
9768       // Emit a reduction. If the root is a select (min/max idiom), the insert
9769       // point is the compare condition of that select.
9770       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9771       if (isCmpSelMinMax(RdxRootInst))
9772         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9773       else
9774         Builder.SetInsertPoint(RdxRootInst);
9775 
9776       // To prevent poison from leaking across what used to be sequential, safe,
9777       // scalar boolean logic operations, the reduction operand must be frozen.
9778       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9779         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9780 
9781       Value *ReducedSubTree =
9782           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9783 
9784       if (!VectorizedTree) {
9785         // Initialize the final value in the reduction.
9786         VectorizedTree = ReducedSubTree;
9787       } else {
9788         // Update the final value in the reduction.
9789         Builder.SetCurrentDebugLocation(Loc);
9790         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9791                                   ReducedSubTree, "op.rdx", ReductionOps);
9792       }
9793       i += ReduxWidth;
9794       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9795     }
9796 
9797     if (VectorizedTree) {
9798       // Finish the reduction.
9799       for (; i < NumReducedVals; ++i) {
9800         auto *I = cast<Instruction>(ReducedVals[i]);
9801         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9802         VectorizedTree =
9803             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9804       }
9805       for (auto &Pair : ExternallyUsedValues) {
9806         // Add each externally used value to the final reduction.
9807         for (auto *I : Pair.second) {
9808           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9809           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9810                                     Pair.first, "op.extra", I);
9811         }
9812       }
9813 
9814       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9815 
9816       // The original scalar reduction is expected to have no remaining
9817       // uses outside the reduction tree itself.  Assert that we got this
9818       // correct, replace internal uses with undef, and mark for eventual
9819       // deletion.
9820 #ifndef NDEBUG
9821       SmallSet<Value *, 4> IgnoreSet;
9822       IgnoreSet.insert(IgnoreList.begin(), IgnoreList.end());
9823 #endif
9824       for (auto *Ignore : IgnoreList) {
9825 #ifndef NDEBUG
9826         for (auto *U : Ignore->users()) {
9827           assert(IgnoreSet.count(U));
9828         }
9829 #endif
9830         if (!Ignore->use_empty()) {
9831           Value *Undef = UndefValue::get(Ignore->getType());
9832           Ignore->replaceAllUsesWith(Undef);
9833         }
9834         V.eraseInstruction(cast<Instruction>(Ignore));
9835       }
9836     }
9837     return VectorizedTree;
9838   }
9839 
9840   unsigned numReductionValues() const { return ReducedVals.size(); }
9841 
9842 private:
9843   /// Calculate the cost of a reduction.
9844   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9845                                    Value *FirstReducedVal, unsigned ReduxWidth,
9846                                    FastMathFlags FMF) {
9847     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9848     Type *ScalarTy = FirstReducedVal->getType();
9849     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9850     InstructionCost VectorCost, ScalarCost;
9851     switch (RdxKind) {
9852     case RecurKind::Add:
9853     case RecurKind::Mul:
9854     case RecurKind::Or:
9855     case RecurKind::And:
9856     case RecurKind::Xor:
9857     case RecurKind::FAdd:
9858     case RecurKind::FMul: {
9859       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9860       VectorCost =
9861           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9862       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9863       break;
9864     }
9865     case RecurKind::FMax:
9866     case RecurKind::FMin: {
9867       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9868       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9869       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9870                                                /*IsUnsigned=*/false, CostKind);
9871       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9872       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9873                                            SclCondTy, RdxPred, CostKind) +
9874                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9875                                            SclCondTy, RdxPred, CostKind);
9876       break;
9877     }
9878     case RecurKind::SMax:
9879     case RecurKind::SMin:
9880     case RecurKind::UMax:
9881     case RecurKind::UMin: {
9882       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9883       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9884       bool IsUnsigned =
9885           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9886       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9887                                                CostKind);
9888       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9889       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9890                                            SclCondTy, RdxPred, CostKind) +
9891                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9892                                            SclCondTy, RdxPred, CostKind);
9893       break;
9894     }
9895     default:
9896       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9897     }
9898 
9899     // Scalar cost is repeated for N-1 elements.
9900     ScalarCost *= (ReduxWidth - 1);
9901     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9902                       << " for reduction that starts with " << *FirstReducedVal
9903                       << " (It is a splitting reduction)\n");
9904     return VectorCost - ScalarCost;
9905   }
9906 
9907   /// Emit a horizontal reduction of the vectorized value.
9908   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9909                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9910     assert(VectorizedValue && "Need to have a vectorized tree node");
9911     assert(isPowerOf2_32(ReduxWidth) &&
9912            "We only handle power-of-two reductions for now");
9913     assert(RdxKind != RecurKind::FMulAdd &&
9914            "A call to the llvm.fmuladd intrinsic is not handled yet");
9915 
9916     ++NumVectorInstructions;
9917     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9918   }
9919 };
9920 
9921 } // end anonymous namespace
9922 
9923 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9924   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9925     return cast<FixedVectorType>(IE->getType())->getNumElements();
9926 
9927   unsigned AggregateSize = 1;
9928   auto *IV = cast<InsertValueInst>(InsertInst);
9929   Type *CurrentType = IV->getType();
9930   do {
9931     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9932       for (auto *Elt : ST->elements())
9933         if (Elt != ST->getElementType(0)) // check homogeneity
9934           return None;
9935       AggregateSize *= ST->getNumElements();
9936       CurrentType = ST->getElementType(0);
9937     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9938       AggregateSize *= AT->getNumElements();
9939       CurrentType = AT->getElementType();
9940     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9941       AggregateSize *= VT->getNumElements();
9942       return AggregateSize;
9943     } else if (CurrentType->isSingleValueType()) {
9944       return AggregateSize;
9945     } else {
9946       return None;
9947     }
9948   } while (true);
9949 }
9950 
9951 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9952                                    TargetTransformInfo *TTI,
9953                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9954                                    SmallVectorImpl<Value *> &InsertElts,
9955                                    unsigned OperandOffset) {
9956   do {
9957     Value *InsertedOperand = LastInsertInst->getOperand(1);
9958     Optional<unsigned> OperandIndex =
9959         getInsertIndex(LastInsertInst, OperandOffset);
9960     if (!OperandIndex)
9961       return;
9962     if (isa<InsertElementInst>(InsertedOperand) ||
9963         isa<InsertValueInst>(InsertedOperand)) {
9964       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9965                              BuildVectorOpds, InsertElts, *OperandIndex);
9966 
9967     } else {
9968       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9969       InsertElts[*OperandIndex] = LastInsertInst;
9970     }
9971     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9972   } while (LastInsertInst != nullptr &&
9973            (isa<InsertValueInst>(LastInsertInst) ||
9974             isa<InsertElementInst>(LastInsertInst)) &&
9975            LastInsertInst->hasOneUse());
9976 }
9977 
9978 /// Recognize construction of vectors like
9979 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9980 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9981 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9982 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9983 ///  starting from the last insertelement or insertvalue instruction.
9984 ///
9985 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9986 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9987 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9988 ///
9989 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9990 ///
9991 /// \return true if it matches.
9992 static bool findBuildAggregate(Instruction *LastInsertInst,
9993                                TargetTransformInfo *TTI,
9994                                SmallVectorImpl<Value *> &BuildVectorOpds,
9995                                SmallVectorImpl<Value *> &InsertElts) {
9996 
9997   assert((isa<InsertElementInst>(LastInsertInst) ||
9998           isa<InsertValueInst>(LastInsertInst)) &&
9999          "Expected insertelement or insertvalue instruction!");
10000 
10001   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
10002          "Expected empty result vectors!");
10003 
10004   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
10005   if (!AggregateSize)
10006     return false;
10007   BuildVectorOpds.resize(*AggregateSize);
10008   InsertElts.resize(*AggregateSize);
10009 
10010   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
10011   llvm::erase_value(BuildVectorOpds, nullptr);
10012   llvm::erase_value(InsertElts, nullptr);
10013   if (BuildVectorOpds.size() >= 2)
10014     return true;
10015 
10016   return false;
10017 }
10018 
10019 /// Try and get a reduction value from a phi node.
10020 ///
10021 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
10022 /// if they come from either \p ParentBB or a containing loop latch.
10023 ///
10024 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
10025 /// if not possible.
10026 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
10027                                 BasicBlock *ParentBB, LoopInfo *LI) {
10028   // There are situations where the reduction value is not dominated by the
10029   // reduction phi. Vectorizing such cases has been reported to cause
10030   // miscompiles. See PR25787.
10031   auto DominatedReduxValue = [&](Value *R) {
10032     return isa<Instruction>(R) &&
10033            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
10034   };
10035 
10036   Value *Rdx = nullptr;
10037 
10038   // Return the incoming value if it comes from the same BB as the phi node.
10039   if (P->getIncomingBlock(0) == ParentBB) {
10040     Rdx = P->getIncomingValue(0);
10041   } else if (P->getIncomingBlock(1) == ParentBB) {
10042     Rdx = P->getIncomingValue(1);
10043   }
10044 
10045   if (Rdx && DominatedReduxValue(Rdx))
10046     return Rdx;
10047 
10048   // Otherwise, check whether we have a loop latch to look at.
10049   Loop *BBL = LI->getLoopFor(ParentBB);
10050   if (!BBL)
10051     return nullptr;
10052   BasicBlock *BBLatch = BBL->getLoopLatch();
10053   if (!BBLatch)
10054     return nullptr;
10055 
10056   // There is a loop latch, return the incoming value if it comes from
10057   // that. This reduction pattern occasionally turns up.
10058   if (P->getIncomingBlock(0) == BBLatch) {
10059     Rdx = P->getIncomingValue(0);
10060   } else if (P->getIncomingBlock(1) == BBLatch) {
10061     Rdx = P->getIncomingValue(1);
10062   }
10063 
10064   if (Rdx && DominatedReduxValue(Rdx))
10065     return Rdx;
10066 
10067   return nullptr;
10068 }
10069 
10070 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10071   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10072     return true;
10073   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10074     return true;
10075   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10076     return true;
10077   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10078     return true;
10079   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10080     return true;
10081   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10082     return true;
10083   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10084     return true;
10085   return false;
10086 }
10087 
10088 /// Attempt to reduce a horizontal reduction.
10089 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10090 /// with reduction operators \a Root (or one of its operands) in a basic block
10091 /// \a BB, then check if it can be done. If horizontal reduction is not found
10092 /// and root instruction is a binary operation, vectorization of the operands is
10093 /// attempted.
10094 /// \returns true if a horizontal reduction was matched and reduced or operands
10095 /// of one of the binary instruction were vectorized.
10096 /// \returns false if a horizontal reduction was not matched (or not possible)
10097 /// or no vectorization of any binary operation feeding \a Root instruction was
10098 /// performed.
10099 static bool tryToVectorizeHorReductionOrInstOperands(
10100     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10101     TargetTransformInfo *TTI,
10102     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10103   if (!ShouldVectorizeHor)
10104     return false;
10105 
10106   if (!Root)
10107     return false;
10108 
10109   if (Root->getParent() != BB || isa<PHINode>(Root))
10110     return false;
10111   // Start analysis starting from Root instruction. If horizontal reduction is
10112   // found, try to vectorize it. If it is not a horizontal reduction or
10113   // vectorization is not possible or not effective, and currently analyzed
10114   // instruction is a binary operation, try to vectorize the operands, using
10115   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10116   // the same procedure considering each operand as a possible root of the
10117   // horizontal reduction.
10118   // Interrupt the process if the Root instruction itself was vectorized or all
10119   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10120   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10121   // CmpInsts so we can skip extra attempts in
10122   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10123   std::queue<std::pair<Instruction *, unsigned>> Stack;
10124   Stack.emplace(Root, 0);
10125   SmallPtrSet<Value *, 8> VisitedInstrs;
10126   SmallVector<WeakTrackingVH> PostponedInsts;
10127   bool Res = false;
10128   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
10129                                      Value *&B1) -> Value * {
10130     bool IsBinop = matchRdxBop(Inst, B0, B1);
10131     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10132     if (IsBinop || IsSelect) {
10133       HorizontalReduction HorRdx;
10134       if (HorRdx.matchAssociativeReduction(P, Inst))
10135         return HorRdx.tryToReduce(R, TTI);
10136     }
10137     return nullptr;
10138   };
10139   while (!Stack.empty()) {
10140     Instruction *Inst;
10141     unsigned Level;
10142     std::tie(Inst, Level) = Stack.front();
10143     Stack.pop();
10144     // Do not try to analyze instruction that has already been vectorized.
10145     // This may happen when we vectorize instruction operands on a previous
10146     // iteration while stack was populated before that happened.
10147     if (R.isDeleted(Inst))
10148       continue;
10149     Value *B0 = nullptr, *B1 = nullptr;
10150     if (Value *V = TryToReduce(Inst, B0, B1)) {
10151       Res = true;
10152       // Set P to nullptr to avoid re-analysis of phi node in
10153       // matchAssociativeReduction function unless this is the root node.
10154       P = nullptr;
10155       if (auto *I = dyn_cast<Instruction>(V)) {
10156         // Try to find another reduction.
10157         Stack.emplace(I, Level);
10158         continue;
10159       }
10160     } else {
10161       bool IsBinop = B0 && B1;
10162       if (P && IsBinop) {
10163         Inst = dyn_cast<Instruction>(B0);
10164         if (Inst == P)
10165           Inst = dyn_cast<Instruction>(B1);
10166         if (!Inst) {
10167           // Set P to nullptr to avoid re-analysis of phi node in
10168           // matchAssociativeReduction function unless this is the root node.
10169           P = nullptr;
10170           continue;
10171         }
10172       }
10173       // Set P to nullptr to avoid re-analysis of phi node in
10174       // matchAssociativeReduction function unless this is the root node.
10175       P = nullptr;
10176       // Do not try to vectorize CmpInst operands, this is done separately.
10177       // Final attempt for binop args vectorization should happen after the loop
10178       // to try to find reductions.
10179       if (!isa<CmpInst>(Inst))
10180         PostponedInsts.push_back(Inst);
10181     }
10182 
10183     // Try to vectorize operands.
10184     // Continue analysis for the instruction from the same basic block only to
10185     // save compile time.
10186     if (++Level < RecursionMaxDepth)
10187       for (auto *Op : Inst->operand_values())
10188         if (VisitedInstrs.insert(Op).second)
10189           if (auto *I = dyn_cast<Instruction>(Op))
10190             // Do not try to vectorize CmpInst operands,  this is done
10191             // separately.
10192             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10193                 I->getParent() == BB)
10194               Stack.emplace(I, Level);
10195   }
10196   // Try to vectorized binops where reductions were not found.
10197   for (Value *V : PostponedInsts)
10198     if (auto *Inst = dyn_cast<Instruction>(V))
10199       if (!R.isDeleted(Inst))
10200         Res |= Vectorize(Inst, R);
10201   return Res;
10202 }
10203 
10204 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10205                                                  BasicBlock *BB, BoUpSLP &R,
10206                                                  TargetTransformInfo *TTI) {
10207   auto *I = dyn_cast_or_null<Instruction>(V);
10208   if (!I)
10209     return false;
10210 
10211   if (!isa<BinaryOperator>(I))
10212     P = nullptr;
10213   // Try to match and vectorize a horizontal reduction.
10214   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10215     return tryToVectorize(I, R);
10216   };
10217   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10218                                                   ExtraVectorization);
10219 }
10220 
10221 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10222                                                  BasicBlock *BB, BoUpSLP &R) {
10223   const DataLayout &DL = BB->getModule()->getDataLayout();
10224   if (!R.canMapToVector(IVI->getType(), DL))
10225     return false;
10226 
10227   SmallVector<Value *, 16> BuildVectorOpds;
10228   SmallVector<Value *, 16> BuildVectorInsts;
10229   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10230     return false;
10231 
10232   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10233   // Aggregate value is unlikely to be processed in vector register.
10234   return tryToVectorizeList(BuildVectorOpds, R);
10235 }
10236 
10237 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10238                                                    BasicBlock *BB, BoUpSLP &R) {
10239   SmallVector<Value *, 16> BuildVectorInsts;
10240   SmallVector<Value *, 16> BuildVectorOpds;
10241   SmallVector<int> Mask;
10242   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10243       (llvm::all_of(
10244            BuildVectorOpds,
10245            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10246        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10247     return false;
10248 
10249   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10250   return tryToVectorizeList(BuildVectorInsts, R);
10251 }
10252 
10253 template <typename T>
10254 static bool
10255 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10256                        function_ref<unsigned(T *)> Limit,
10257                        function_ref<bool(T *, T *)> Comparator,
10258                        function_ref<bool(T *, T *)> AreCompatible,
10259                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10260                        bool LimitForRegisterSize) {
10261   bool Changed = false;
10262   // Sort by type, parent, operands.
10263   stable_sort(Incoming, Comparator);
10264 
10265   // Try to vectorize elements base on their type.
10266   SmallVector<T *> Candidates;
10267   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10268     // Look for the next elements with the same type, parent and operand
10269     // kinds.
10270     auto *SameTypeIt = IncIt;
10271     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10272       ++SameTypeIt;
10273 
10274     // Try to vectorize them.
10275     unsigned NumElts = (SameTypeIt - IncIt);
10276     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10277                       << NumElts << ")\n");
10278     // The vectorization is a 3-state attempt:
10279     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10280     // size of maximal register at first.
10281     // 2. Try to vectorize remaining instructions with the same type, if
10282     // possible. This may result in the better vectorization results rather than
10283     // if we try just to vectorize instructions with the same/alternate opcodes.
10284     // 3. Final attempt to try to vectorize all instructions with the
10285     // same/alternate ops only, this may result in some extra final
10286     // vectorization.
10287     if (NumElts > 1 &&
10288         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10289       // Success start over because instructions might have been changed.
10290       Changed = true;
10291     } else if (NumElts < Limit(*IncIt) &&
10292                (Candidates.empty() ||
10293                 Candidates.front()->getType() == (*IncIt)->getType())) {
10294       Candidates.append(IncIt, std::next(IncIt, NumElts));
10295     }
10296     // Final attempt to vectorize instructions with the same types.
10297     if (Candidates.size() > 1 &&
10298         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10299       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10300         // Success start over because instructions might have been changed.
10301         Changed = true;
10302       } else if (LimitForRegisterSize) {
10303         // Try to vectorize using small vectors.
10304         for (auto *It = Candidates.begin(), *End = Candidates.end();
10305              It != End;) {
10306           auto *SameTypeIt = It;
10307           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10308             ++SameTypeIt;
10309           unsigned NumElts = (SameTypeIt - It);
10310           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10311                                             /*LimitForRegisterSize=*/false))
10312             Changed = true;
10313           It = SameTypeIt;
10314         }
10315       }
10316       Candidates.clear();
10317     }
10318 
10319     // Start over at the next instruction of a different type (or the end).
10320     IncIt = SameTypeIt;
10321   }
10322   return Changed;
10323 }
10324 
10325 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10326 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10327 /// operands. If IsCompatibility is false, function implements strict weak
10328 /// ordering relation between two cmp instructions, returning true if the first
10329 /// instruction is "less" than the second, i.e. its predicate is less than the
10330 /// predicate of the second or the operands IDs are less than the operands IDs
10331 /// of the second cmp instruction.
10332 template <bool IsCompatibility>
10333 static bool compareCmp(Value *V, Value *V2,
10334                        function_ref<bool(Instruction *)> IsDeleted) {
10335   auto *CI1 = cast<CmpInst>(V);
10336   auto *CI2 = cast<CmpInst>(V2);
10337   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10338     return false;
10339   if (CI1->getOperand(0)->getType()->getTypeID() <
10340       CI2->getOperand(0)->getType()->getTypeID())
10341     return !IsCompatibility;
10342   if (CI1->getOperand(0)->getType()->getTypeID() >
10343       CI2->getOperand(0)->getType()->getTypeID())
10344     return false;
10345   CmpInst::Predicate Pred1 = CI1->getPredicate();
10346   CmpInst::Predicate Pred2 = CI2->getPredicate();
10347   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10348   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10349   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10350   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10351   if (BasePred1 < BasePred2)
10352     return !IsCompatibility;
10353   if (BasePred1 > BasePred2)
10354     return false;
10355   // Compare operands.
10356   bool LEPreds = Pred1 <= Pred2;
10357   bool GEPreds = Pred1 >= Pred2;
10358   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10359     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10360     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10361     if (Op1->getValueID() < Op2->getValueID())
10362       return !IsCompatibility;
10363     if (Op1->getValueID() > Op2->getValueID())
10364       return false;
10365     if (auto *I1 = dyn_cast<Instruction>(Op1))
10366       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10367         if (I1->getParent() != I2->getParent())
10368           return false;
10369         InstructionsState S = getSameOpcode({I1, I2});
10370         if (S.getOpcode())
10371           continue;
10372         return false;
10373       }
10374   }
10375   return IsCompatibility;
10376 }
10377 
10378 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10379     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10380     bool AtTerminator) {
10381   bool OpsChanged = false;
10382   SmallVector<Instruction *, 4> PostponedCmps;
10383   for (auto *I : reverse(Instructions)) {
10384     if (R.isDeleted(I))
10385       continue;
10386     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10387       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10388     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10389       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10390     else if (isa<CmpInst>(I))
10391       PostponedCmps.push_back(I);
10392   }
10393   if (AtTerminator) {
10394     // Try to find reductions first.
10395     for (Instruction *I : PostponedCmps) {
10396       if (R.isDeleted(I))
10397         continue;
10398       for (Value *Op : I->operands())
10399         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10400     }
10401     // Try to vectorize operands as vector bundles.
10402     for (Instruction *I : PostponedCmps) {
10403       if (R.isDeleted(I))
10404         continue;
10405       OpsChanged |= tryToVectorize(I, R);
10406     }
10407     // Try to vectorize list of compares.
10408     // Sort by type, compare predicate, etc.
10409     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10410       return compareCmp<false>(V, V2,
10411                                [&R](Instruction *I) { return R.isDeleted(I); });
10412     };
10413 
10414     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10415       if (V1 == V2)
10416         return true;
10417       return compareCmp<true>(V1, V2,
10418                               [&R](Instruction *I) { return R.isDeleted(I); });
10419     };
10420     auto Limit = [&R](Value *V) {
10421       unsigned EltSize = R.getVectorElementSize(V);
10422       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10423     };
10424 
10425     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10426     OpsChanged |= tryToVectorizeSequence<Value>(
10427         Vals, Limit, CompareSorter, AreCompatibleCompares,
10428         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10429           // Exclude possible reductions from other blocks.
10430           bool ArePossiblyReducedInOtherBlock =
10431               any_of(Candidates, [](Value *V) {
10432                 return any_of(V->users(), [V](User *U) {
10433                   return isa<SelectInst>(U) &&
10434                          cast<SelectInst>(U)->getParent() !=
10435                              cast<Instruction>(V)->getParent();
10436                 });
10437               });
10438           if (ArePossiblyReducedInOtherBlock)
10439             return false;
10440           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10441         },
10442         /*LimitForRegisterSize=*/true);
10443     Instructions.clear();
10444   } else {
10445     // Insert in reverse order since the PostponedCmps vector was filled in
10446     // reverse order.
10447     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10448   }
10449   return OpsChanged;
10450 }
10451 
10452 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10453   bool Changed = false;
10454   SmallVector<Value *, 4> Incoming;
10455   SmallPtrSet<Value *, 16> VisitedInstrs;
10456   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10457   // node. Allows better to identify the chains that can be vectorized in the
10458   // better way.
10459   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10460   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10461     assert(isValidElementType(V1->getType()) &&
10462            isValidElementType(V2->getType()) &&
10463            "Expected vectorizable types only.");
10464     // It is fine to compare type IDs here, since we expect only vectorizable
10465     // types, like ints, floats and pointers, we don't care about other type.
10466     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10467       return true;
10468     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10469       return false;
10470     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10471     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10472     if (Opcodes1.size() < Opcodes2.size())
10473       return true;
10474     if (Opcodes1.size() > Opcodes2.size())
10475       return false;
10476     Optional<bool> ConstOrder;
10477     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10478       // Undefs are compatible with any other value.
10479       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10480         if (!ConstOrder)
10481           ConstOrder =
10482               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10483         continue;
10484       }
10485       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10486         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10487           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10488           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10489           if (!NodeI1)
10490             return NodeI2 != nullptr;
10491           if (!NodeI2)
10492             return false;
10493           assert((NodeI1 == NodeI2) ==
10494                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10495                  "Different nodes should have different DFS numbers");
10496           if (NodeI1 != NodeI2)
10497             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10498           InstructionsState S = getSameOpcode({I1, I2});
10499           if (S.getOpcode())
10500             continue;
10501           return I1->getOpcode() < I2->getOpcode();
10502         }
10503       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10504         if (!ConstOrder)
10505           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10506         continue;
10507       }
10508       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10509         return true;
10510       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10511         return false;
10512     }
10513     return ConstOrder && *ConstOrder;
10514   };
10515   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10516     if (V1 == V2)
10517       return true;
10518     if (V1->getType() != V2->getType())
10519       return false;
10520     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10521     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10522     if (Opcodes1.size() != Opcodes2.size())
10523       return false;
10524     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10525       // Undefs are compatible with any other value.
10526       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10527         continue;
10528       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10529         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10530           if (I1->getParent() != I2->getParent())
10531             return false;
10532           InstructionsState S = getSameOpcode({I1, I2});
10533           if (S.getOpcode())
10534             continue;
10535           return false;
10536         }
10537       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10538         continue;
10539       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10540         return false;
10541     }
10542     return true;
10543   };
10544   auto Limit = [&R](Value *V) {
10545     unsigned EltSize = R.getVectorElementSize(V);
10546     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10547   };
10548 
10549   bool HaveVectorizedPhiNodes = false;
10550   do {
10551     // Collect the incoming values from the PHIs.
10552     Incoming.clear();
10553     for (Instruction &I : *BB) {
10554       PHINode *P = dyn_cast<PHINode>(&I);
10555       if (!P)
10556         break;
10557 
10558       // No need to analyze deleted, vectorized and non-vectorizable
10559       // instructions.
10560       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10561           isValidElementType(P->getType()))
10562         Incoming.push_back(P);
10563     }
10564 
10565     // Find the corresponding non-phi nodes for better matching when trying to
10566     // build the tree.
10567     for (Value *V : Incoming) {
10568       SmallVectorImpl<Value *> &Opcodes =
10569           PHIToOpcodes.try_emplace(V).first->getSecond();
10570       if (!Opcodes.empty())
10571         continue;
10572       SmallVector<Value *, 4> Nodes(1, V);
10573       SmallPtrSet<Value *, 4> Visited;
10574       while (!Nodes.empty()) {
10575         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10576         if (!Visited.insert(PHI).second)
10577           continue;
10578         for (Value *V : PHI->incoming_values()) {
10579           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10580             Nodes.push_back(PHI1);
10581             continue;
10582           }
10583           Opcodes.emplace_back(V);
10584         }
10585       }
10586     }
10587 
10588     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10589         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10590         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10591           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10592         },
10593         /*LimitForRegisterSize=*/true);
10594     Changed |= HaveVectorizedPhiNodes;
10595     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10596   } while (HaveVectorizedPhiNodes);
10597 
10598   VisitedInstrs.clear();
10599 
10600   SmallVector<Instruction *, 8> PostProcessInstructions;
10601   SmallDenseSet<Instruction *, 4> KeyNodes;
10602   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10603     // Skip instructions with scalable type. The num of elements is unknown at
10604     // compile-time for scalable type.
10605     if (isa<ScalableVectorType>(it->getType()))
10606       continue;
10607 
10608     // Skip instructions marked for the deletion.
10609     if (R.isDeleted(&*it))
10610       continue;
10611     // We may go through BB multiple times so skip the one we have checked.
10612     if (!VisitedInstrs.insert(&*it).second) {
10613       if (it->use_empty() && KeyNodes.contains(&*it) &&
10614           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10615                                       it->isTerminator())) {
10616         // We would like to start over since some instructions are deleted
10617         // and the iterator may become invalid value.
10618         Changed = true;
10619         it = BB->begin();
10620         e = BB->end();
10621       }
10622       continue;
10623     }
10624 
10625     if (isa<DbgInfoIntrinsic>(it))
10626       continue;
10627 
10628     // Try to vectorize reductions that use PHINodes.
10629     if (PHINode *P = dyn_cast<PHINode>(it)) {
10630       // Check that the PHI is a reduction PHI.
10631       if (P->getNumIncomingValues() == 2) {
10632         // Try to match and vectorize a horizontal reduction.
10633         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10634                                      TTI)) {
10635           Changed = true;
10636           it = BB->begin();
10637           e = BB->end();
10638           continue;
10639         }
10640       }
10641       // Try to vectorize the incoming values of the PHI, to catch reductions
10642       // that feed into PHIs.
10643       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10644         // Skip if the incoming block is the current BB for now. Also, bypass
10645         // unreachable IR for efficiency and to avoid crashing.
10646         // TODO: Collect the skipped incoming values and try to vectorize them
10647         // after processing BB.
10648         if (BB == P->getIncomingBlock(I) ||
10649             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10650           continue;
10651 
10652         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10653                                             P->getIncomingBlock(I), R, TTI);
10654       }
10655       continue;
10656     }
10657 
10658     // Ran into an instruction without users, like terminator, or function call
10659     // with ignored return value, store. Ignore unused instructions (basing on
10660     // instruction type, except for CallInst and InvokeInst).
10661     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10662                             isa<InvokeInst>(it))) {
10663       KeyNodes.insert(&*it);
10664       bool OpsChanged = false;
10665       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10666         for (auto *V : it->operand_values()) {
10667           // Try to match and vectorize a horizontal reduction.
10668           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10669         }
10670       }
10671       // Start vectorization of post-process list of instructions from the
10672       // top-tree instructions to try to vectorize as many instructions as
10673       // possible.
10674       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10675                                                 it->isTerminator());
10676       if (OpsChanged) {
10677         // We would like to start over since some instructions are deleted
10678         // and the iterator may become invalid value.
10679         Changed = true;
10680         it = BB->begin();
10681         e = BB->end();
10682         continue;
10683       }
10684     }
10685 
10686     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10687         isa<InsertValueInst>(it))
10688       PostProcessInstructions.push_back(&*it);
10689   }
10690 
10691   return Changed;
10692 }
10693 
10694 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10695   auto Changed = false;
10696   for (auto &Entry : GEPs) {
10697     // If the getelementptr list has fewer than two elements, there's nothing
10698     // to do.
10699     if (Entry.second.size() < 2)
10700       continue;
10701 
10702     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10703                       << Entry.second.size() << ".\n");
10704 
10705     // Process the GEP list in chunks suitable for the target's supported
10706     // vector size. If a vector register can't hold 1 element, we are done. We
10707     // are trying to vectorize the index computations, so the maximum number of
10708     // elements is based on the size of the index expression, rather than the
10709     // size of the GEP itself (the target's pointer size).
10710     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10711     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10712     if (MaxVecRegSize < EltSize)
10713       continue;
10714 
10715     unsigned MaxElts = MaxVecRegSize / EltSize;
10716     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10717       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10718       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10719 
10720       // Initialize a set a candidate getelementptrs. Note that we use a
10721       // SetVector here to preserve program order. If the index computations
10722       // are vectorizable and begin with loads, we want to minimize the chance
10723       // of having to reorder them later.
10724       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10725 
10726       // Some of the candidates may have already been vectorized after we
10727       // initially collected them. If so, they are marked as deleted, so remove
10728       // them from the set of candidates.
10729       Candidates.remove_if(
10730           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10731 
10732       // Remove from the set of candidates all pairs of getelementptrs with
10733       // constant differences. Such getelementptrs are likely not good
10734       // candidates for vectorization in a bottom-up phase since one can be
10735       // computed from the other. We also ensure all candidate getelementptr
10736       // indices are unique.
10737       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10738         auto *GEPI = GEPList[I];
10739         if (!Candidates.count(GEPI))
10740           continue;
10741         auto *SCEVI = SE->getSCEV(GEPList[I]);
10742         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10743           auto *GEPJ = GEPList[J];
10744           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10745           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10746             Candidates.remove(GEPI);
10747             Candidates.remove(GEPJ);
10748           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10749             Candidates.remove(GEPJ);
10750           }
10751         }
10752       }
10753 
10754       // We break out of the above computation as soon as we know there are
10755       // fewer than two candidates remaining.
10756       if (Candidates.size() < 2)
10757         continue;
10758 
10759       // Add the single, non-constant index of each candidate to the bundle. We
10760       // ensured the indices met these constraints when we originally collected
10761       // the getelementptrs.
10762       SmallVector<Value *, 16> Bundle(Candidates.size());
10763       auto BundleIndex = 0u;
10764       for (auto *V : Candidates) {
10765         auto *GEP = cast<GetElementPtrInst>(V);
10766         auto *GEPIdx = GEP->idx_begin()->get();
10767         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10768         Bundle[BundleIndex++] = GEPIdx;
10769       }
10770 
10771       // Try and vectorize the indices. We are currently only interested in
10772       // gather-like cases of the form:
10773       //
10774       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10775       //
10776       // where the loads of "a", the loads of "b", and the subtractions can be
10777       // performed in parallel. It's likely that detecting this pattern in a
10778       // bottom-up phase will be simpler and less costly than building a
10779       // full-blown top-down phase beginning at the consecutive loads.
10780       Changed |= tryToVectorizeList(Bundle, R);
10781     }
10782   }
10783   return Changed;
10784 }
10785 
10786 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10787   bool Changed = false;
10788   // Sort by type, base pointers and values operand. Value operands must be
10789   // compatible (have the same opcode, same parent), otherwise it is
10790   // definitely not profitable to try to vectorize them.
10791   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10792     if (V->getPointerOperandType()->getTypeID() <
10793         V2->getPointerOperandType()->getTypeID())
10794       return true;
10795     if (V->getPointerOperandType()->getTypeID() >
10796         V2->getPointerOperandType()->getTypeID())
10797       return false;
10798     // UndefValues are compatible with all other values.
10799     if (isa<UndefValue>(V->getValueOperand()) ||
10800         isa<UndefValue>(V2->getValueOperand()))
10801       return false;
10802     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10803       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10804         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10805             DT->getNode(I1->getParent());
10806         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10807             DT->getNode(I2->getParent());
10808         assert(NodeI1 && "Should only process reachable instructions");
10809         assert(NodeI1 && "Should only process reachable instructions");
10810         assert((NodeI1 == NodeI2) ==
10811                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10812                "Different nodes should have different DFS numbers");
10813         if (NodeI1 != NodeI2)
10814           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10815         InstructionsState S = getSameOpcode({I1, I2});
10816         if (S.getOpcode())
10817           return false;
10818         return I1->getOpcode() < I2->getOpcode();
10819       }
10820     if (isa<Constant>(V->getValueOperand()) &&
10821         isa<Constant>(V2->getValueOperand()))
10822       return false;
10823     return V->getValueOperand()->getValueID() <
10824            V2->getValueOperand()->getValueID();
10825   };
10826 
10827   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10828     if (V1 == V2)
10829       return true;
10830     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10831       return false;
10832     // Undefs are compatible with any other value.
10833     if (isa<UndefValue>(V1->getValueOperand()) ||
10834         isa<UndefValue>(V2->getValueOperand()))
10835       return true;
10836     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10837       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10838         if (I1->getParent() != I2->getParent())
10839           return false;
10840         InstructionsState S = getSameOpcode({I1, I2});
10841         return S.getOpcode() > 0;
10842       }
10843     if (isa<Constant>(V1->getValueOperand()) &&
10844         isa<Constant>(V2->getValueOperand()))
10845       return true;
10846     return V1->getValueOperand()->getValueID() ==
10847            V2->getValueOperand()->getValueID();
10848   };
10849   auto Limit = [&R, this](StoreInst *SI) {
10850     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10851     return R.getMinVF(EltSize);
10852   };
10853 
10854   // Attempt to sort and vectorize each of the store-groups.
10855   for (auto &Pair : Stores) {
10856     if (Pair.second.size() < 2)
10857       continue;
10858 
10859     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10860                       << Pair.second.size() << ".\n");
10861 
10862     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10863       continue;
10864 
10865     Changed |= tryToVectorizeSequence<StoreInst>(
10866         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10867         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10868           return vectorizeStores(Candidates, R);
10869         },
10870         /*LimitForRegisterSize=*/false);
10871   }
10872   return Changed;
10873 }
10874 
10875 char SLPVectorizer::ID = 0;
10876 
10877 static const char lv_name[] = "SLP Vectorizer";
10878 
10879 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10880 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10881 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10882 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10883 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10884 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10885 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10886 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10887 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10888 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10889 
10890 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10891