1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/MemorySSA.h"
45 #include "llvm/Analysis/MemorySSAUpdater.h"
46 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
47 #include "llvm/Analysis/ScalarEvolution.h"
48 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
49 #include "llvm/Analysis/TargetLibraryInfo.h"
50 #include "llvm/Analysis/TargetTransformInfo.h"
51 #include "llvm/Analysis/ValueTracking.h"
52 #include "llvm/Analysis/VectorUtils.h"
53 #include "llvm/IR/Attributes.h"
54 #include "llvm/IR/BasicBlock.h"
55 #include "llvm/IR/Constant.h"
56 #include "llvm/IR/Constants.h"
57 #include "llvm/IR/DataLayout.h"
58 #include "llvm/IR/DebugLoc.h"
59 #include "llvm/IR/DerivedTypes.h"
60 #include "llvm/IR/Dominators.h"
61 #include "llvm/IR/Function.h"
62 #include "llvm/IR/IRBuilder.h"
63 #include "llvm/IR/InstrTypes.h"
64 #include "llvm/IR/Instruction.h"
65 #include "llvm/IR/Instructions.h"
66 #include "llvm/IR/IntrinsicInst.h"
67 #include "llvm/IR/Intrinsics.h"
68 #include "llvm/IR/Module.h"
69 #include "llvm/IR/Operator.h"
70 #include "llvm/IR/PatternMatch.h"
71 #include "llvm/IR/Type.h"
72 #include "llvm/IR/Use.h"
73 #include "llvm/IR/User.h"
74 #include "llvm/IR/Value.h"
75 #include "llvm/IR/ValueHandle.h"
76 #include "llvm/IR/Verifier.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 static cl::opt<bool>
168     ViewSLPTree("view-slp-tree", cl::Hidden,
169                 cl::desc("Display the SLP trees with Graphviz"));
170 
171 static cl::opt<bool> EnableMSSAInSLPVectorizer(
172     "enable-mssa-in-slp-vectorizer", cl::Hidden, cl::init(false),
173     cl::desc("Enable MemorySSA for SLPVectorizer in new pass manager"));
174 
175 // Limit the number of alias checks. The limit is chosen so that
176 // it has no negative effect on the llvm benchmarks.
177 static const unsigned AliasedCheckLimit = 10;
178 
179 // Another limit for the alias checks: The maximum distance between load/store
180 // instructions where alias checks are done.
181 // This limit is useful for very large basic blocks.
182 static const unsigned MaxMemDepDistance = 160;
183 
184 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
185 /// regions to be handled.
186 static const int MinScheduleRegionSize = 16;
187 
188 /// Predicate for the element types that the SLP vectorizer supports.
189 ///
190 /// The most important thing to filter here are types which are invalid in LLVM
191 /// vectors. We also filter target specific types which have absolutely no
192 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
193 /// avoids spending time checking the cost model and realizing that they will
194 /// be inevitably scalarized.
195 static bool isValidElementType(Type *Ty) {
196   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
197          !Ty->isPPC_FP128Ty();
198 }
199 
200 /// \returns True if the value is a constant (but not globals/constant
201 /// expressions).
202 static bool isConstant(Value *V) {
203   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
204 }
205 
206 /// Checks if \p V is one of vector-like instructions, i.e. undef,
207 /// insertelement/extractelement with constant indices for fixed vector type or
208 /// extractvalue instruction.
209 static bool isVectorLikeInstWithConstOps(Value *V) {
210   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
211       !isa<ExtractValueInst, UndefValue>(V))
212     return false;
213   auto *I = dyn_cast<Instruction>(V);
214   if (!I || isa<ExtractValueInst>(I))
215     return true;
216   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
217     return false;
218   if (isa<ExtractElementInst>(I))
219     return isConstant(I->getOperand(1));
220   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
221   return isConstant(I->getOperand(2));
222 }
223 
224 /// \returns true if all of the instructions in \p VL are in the same block or
225 /// false otherwise.
226 static bool allSameBlock(ArrayRef<Value *> VL) {
227   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
228   if (!I0)
229     return false;
230   if (all_of(VL, isVectorLikeInstWithConstOps))
231     return true;
232 
233   BasicBlock *BB = I0->getParent();
234   for (int I = 1, E = VL.size(); I < E; I++) {
235     auto *II = dyn_cast<Instruction>(VL[I]);
236     if (!II)
237       return false;
238 
239     if (BB != II->getParent())
240       return false;
241   }
242   return true;
243 }
244 
245 /// \returns True if all of the values in \p VL are constants (but not
246 /// globals/constant expressions).
247 static bool allConstant(ArrayRef<Value *> VL) {
248   // Constant expressions and globals can't be vectorized like normal integer/FP
249   // constants.
250   return all_of(VL, isConstant);
251 }
252 
253 /// \returns True if all of the values in \p VL are identical or some of them
254 /// are UndefValue.
255 static bool isSplat(ArrayRef<Value *> VL) {
256   Value *FirstNonUndef = nullptr;
257   for (Value *V : VL) {
258     if (isa<UndefValue>(V))
259       continue;
260     if (!FirstNonUndef) {
261       FirstNonUndef = V;
262       continue;
263     }
264     if (V != FirstNonUndef)
265       return false;
266   }
267   return FirstNonUndef != nullptr;
268 }
269 
270 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
271 static bool isCommutative(Instruction *I) {
272   if (auto *Cmp = dyn_cast<CmpInst>(I))
273     return Cmp->isCommutative();
274   if (auto *BO = dyn_cast<BinaryOperator>(I))
275     return BO->isCommutative();
276   // TODO: This should check for generic Instruction::isCommutative(), but
277   //       we need to confirm that the caller code correctly handles Intrinsics
278   //       for example (does not have 2 operands).
279   return false;
280 }
281 
282 /// Checks if the given value is actually an undefined constant vector.
283 static bool isUndefVector(const Value *V) {
284   if (isa<UndefValue>(V))
285     return true;
286   auto *C = dyn_cast<Constant>(V);
287   if (!C)
288     return false;
289   if (!C->containsUndefOrPoisonElement())
290     return false;
291   auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
292   if (!VecTy)
293     return false;
294   for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
295     if (Constant *Elem = C->getAggregateElement(I))
296       if (!isa<UndefValue>(Elem))
297         return false;
298   }
299   return true;
300 }
301 
302 /// Checks if the vector of instructions can be represented as a shuffle, like:
303 /// %x0 = extractelement <4 x i8> %x, i32 0
304 /// %x3 = extractelement <4 x i8> %x, i32 3
305 /// %y1 = extractelement <4 x i8> %y, i32 1
306 /// %y2 = extractelement <4 x i8> %y, i32 2
307 /// %x0x0 = mul i8 %x0, %x0
308 /// %x3x3 = mul i8 %x3, %x3
309 /// %y1y1 = mul i8 %y1, %y1
310 /// %y2y2 = mul i8 %y2, %y2
311 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
312 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
313 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
314 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
315 /// ret <4 x i8> %ins4
316 /// can be transformed into:
317 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
318 ///                                                         i32 6>
319 /// %2 = mul <4 x i8> %1, %1
320 /// ret <4 x i8> %2
321 /// We convert this initially to something like:
322 /// %x0 = extractelement <4 x i8> %x, i32 0
323 /// %x3 = extractelement <4 x i8> %x, i32 3
324 /// %y1 = extractelement <4 x i8> %y, i32 1
325 /// %y2 = extractelement <4 x i8> %y, i32 2
326 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
327 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
328 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
329 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
330 /// %5 = mul <4 x i8> %4, %4
331 /// %6 = extractelement <4 x i8> %5, i32 0
332 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
333 /// %7 = extractelement <4 x i8> %5, i32 1
334 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
335 /// %8 = extractelement <4 x i8> %5, i32 2
336 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
337 /// %9 = extractelement <4 x i8> %5, i32 3
338 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
339 /// ret <4 x i8> %ins4
340 /// InstCombiner transforms this into a shuffle and vector mul
341 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
342 /// TODO: Can we split off and reuse the shuffle mask detection from
343 /// TargetTransformInfo::getInstructionThroughput?
344 static Optional<TargetTransformInfo::ShuffleKind>
345 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
346   const auto *It =
347       find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
348   if (It == VL.end())
349     return None;
350   auto *EI0 = cast<ExtractElementInst>(*It);
351   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
352     return None;
353   unsigned Size =
354       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
355   Value *Vec1 = nullptr;
356   Value *Vec2 = nullptr;
357   enum ShuffleMode { Unknown, Select, Permute };
358   ShuffleMode CommonShuffleMode = Unknown;
359   Mask.assign(VL.size(), UndefMaskElem);
360   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
361     // Undef can be represented as an undef element in a vector.
362     if (isa<UndefValue>(VL[I]))
363       continue;
364     auto *EI = cast<ExtractElementInst>(VL[I]);
365     if (isa<ScalableVectorType>(EI->getVectorOperandType()))
366       return None;
367     auto *Vec = EI->getVectorOperand();
368     // We can extractelement from undef or poison vector.
369     if (isUndefVector(Vec))
370       continue;
371     // All vector operands must have the same number of vector elements.
372     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
373       return None;
374     if (isa<UndefValue>(EI->getIndexOperand()))
375       continue;
376     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
377     if (!Idx)
378       return None;
379     // Undefined behavior if Idx is negative or >= Size.
380     if (Idx->getValue().uge(Size))
381       continue;
382     unsigned IntIdx = Idx->getValue().getZExtValue();
383     Mask[I] = IntIdx;
384     // For correct shuffling we have to have at most 2 different vector operands
385     // in all extractelement instructions.
386     if (!Vec1 || Vec1 == Vec) {
387       Vec1 = Vec;
388     } else if (!Vec2 || Vec2 == Vec) {
389       Vec2 = Vec;
390       Mask[I] += Size;
391     } else {
392       return None;
393     }
394     if (CommonShuffleMode == Permute)
395       continue;
396     // If the extract index is not the same as the operation number, it is a
397     // permutation.
398     if (IntIdx != I) {
399       CommonShuffleMode = Permute;
400       continue;
401     }
402     CommonShuffleMode = Select;
403   }
404   // If we're not crossing lanes in different vectors, consider it as blending.
405   if (CommonShuffleMode == Select && Vec2)
406     return TargetTransformInfo::SK_Select;
407   // If Vec2 was never used, we have a permutation of a single vector, otherwise
408   // we have permutation of 2 vectors.
409   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
410               : TargetTransformInfo::SK_PermuteSingleSrc;
411 }
412 
413 namespace {
414 
415 /// Main data required for vectorization of instructions.
416 struct InstructionsState {
417   /// The very first instruction in the list with the main opcode.
418   Value *OpValue = nullptr;
419 
420   /// The main/alternate instruction.
421   Instruction *MainOp = nullptr;
422   Instruction *AltOp = nullptr;
423 
424   /// The main/alternate opcodes for the list of instructions.
425   unsigned getOpcode() const {
426     return MainOp ? MainOp->getOpcode() : 0;
427   }
428 
429   unsigned getAltOpcode() const {
430     return AltOp ? AltOp->getOpcode() : 0;
431   }
432 
433   /// Some of the instructions in the list have alternate opcodes.
434   bool isAltShuffle() const { return AltOp != MainOp; }
435 
436   bool isOpcodeOrAlt(Instruction *I) const {
437     unsigned CheckedOpcode = I->getOpcode();
438     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
439   }
440 
441   InstructionsState() = delete;
442   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
443       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
444 };
445 
446 } // end anonymous namespace
447 
448 /// Chooses the correct key for scheduling data. If \p Op has the same (or
449 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
450 /// OpValue.
451 static Value *isOneOf(const InstructionsState &S, Value *Op) {
452   auto *I = dyn_cast<Instruction>(Op);
453   if (I && S.isOpcodeOrAlt(I))
454     return Op;
455   return S.OpValue;
456 }
457 
458 /// \returns true if \p Opcode is allowed as part of of the main/alternate
459 /// instruction for SLP vectorization.
460 ///
461 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
462 /// "shuffled out" lane would result in division by zero.
463 static bool isValidForAlternation(unsigned Opcode) {
464   if (Instruction::isIntDivRem(Opcode))
465     return false;
466 
467   return true;
468 }
469 
470 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
471                                        unsigned BaseIndex = 0);
472 
473 /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
474 /// compatible instructions or constants, or just some other regular values.
475 static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
476                                 Value *Op1) {
477   return (isConstant(BaseOp0) && isConstant(Op0)) ||
478          (isConstant(BaseOp1) && isConstant(Op1)) ||
479          (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
480           !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
481          getSameOpcode({BaseOp0, Op0}).getOpcode() ||
482          getSameOpcode({BaseOp1, Op1}).getOpcode();
483 }
484 
485 /// \returns analysis of the Instructions in \p VL described in
486 /// InstructionsState, the Opcode that we suppose the whole list
487 /// could be vectorized even if its structure is diverse.
488 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
489                                        unsigned BaseIndex) {
490   // Make sure these are all Instructions.
491   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
492     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
493 
494   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
495   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
496   bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
497   CmpInst::Predicate BasePred =
498       IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
499               : CmpInst::BAD_ICMP_PREDICATE;
500   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
501   unsigned AltOpcode = Opcode;
502   unsigned AltIndex = BaseIndex;
503 
504   // Check for one alternate opcode from another BinaryOperator.
505   // TODO - generalize to support all operators (types, calls etc.).
506   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
507     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
508     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
509       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
510         continue;
511       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
512           isValidForAlternation(Opcode)) {
513         AltOpcode = InstOpcode;
514         AltIndex = Cnt;
515         continue;
516       }
517     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
518       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
519       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
520       if (Ty0 == Ty1) {
521         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
522           continue;
523         if (Opcode == AltOpcode) {
524           assert(isValidForAlternation(Opcode) &&
525                  isValidForAlternation(InstOpcode) &&
526                  "Cast isn't safe for alternation, logic needs to be updated!");
527           AltOpcode = InstOpcode;
528           AltIndex = Cnt;
529           continue;
530         }
531       }
532     } else if (IsCmpOp && isa<CmpInst>(VL[Cnt])) {
533       auto *BaseInst = cast<Instruction>(VL[BaseIndex]);
534       auto *Inst = cast<Instruction>(VL[Cnt]);
535       Type *Ty0 = BaseInst->getOperand(0)->getType();
536       Type *Ty1 = Inst->getOperand(0)->getType();
537       if (Ty0 == Ty1) {
538         Value *BaseOp0 = BaseInst->getOperand(0);
539         Value *BaseOp1 = BaseInst->getOperand(1);
540         Value *Op0 = Inst->getOperand(0);
541         Value *Op1 = Inst->getOperand(1);
542         CmpInst::Predicate CurrentPred =
543             cast<CmpInst>(VL[Cnt])->getPredicate();
544         CmpInst::Predicate SwappedCurrentPred =
545             CmpInst::getSwappedPredicate(CurrentPred);
546         // Check for compatible operands. If the corresponding operands are not
547         // compatible - need to perform alternate vectorization.
548         if (InstOpcode == Opcode) {
549           if (BasePred == CurrentPred &&
550               areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1))
551             continue;
552           if (BasePred == SwappedCurrentPred &&
553               areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0))
554             continue;
555           if (E == 2 &&
556               (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
557             continue;
558           auto *AltInst = cast<CmpInst>(VL[AltIndex]);
559           CmpInst::Predicate AltPred = AltInst->getPredicate();
560           Value *AltOp0 = AltInst->getOperand(0);
561           Value *AltOp1 = AltInst->getOperand(1);
562           // Check if operands are compatible with alternate operands.
563           if (AltPred == CurrentPred &&
564               areCompatibleCmpOps(AltOp0, AltOp1, Op0, Op1))
565             continue;
566           if (AltPred == SwappedCurrentPred &&
567               areCompatibleCmpOps(AltOp0, AltOp1, Op1, Op0))
568             continue;
569         }
570         if (BaseIndex == AltIndex && BasePred != CurrentPred) {
571           assert(isValidForAlternation(Opcode) &&
572                  isValidForAlternation(InstOpcode) &&
573                  "Cast isn't safe for alternation, logic needs to be updated!");
574           AltIndex = Cnt;
575           continue;
576         }
577         auto *AltInst = cast<CmpInst>(VL[AltIndex]);
578         CmpInst::Predicate AltPred = AltInst->getPredicate();
579         if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
580             AltPred == CurrentPred || AltPred == SwappedCurrentPred)
581           continue;
582       }
583     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
584       continue;
585     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
586   }
587 
588   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
589                            cast<Instruction>(VL[AltIndex]));
590 }
591 
592 /// \returns true if all of the values in \p VL have the same type or false
593 /// otherwise.
594 static bool allSameType(ArrayRef<Value *> VL) {
595   Type *Ty = VL[0]->getType();
596   for (int i = 1, e = VL.size(); i < e; i++)
597     if (VL[i]->getType() != Ty)
598       return false;
599 
600   return true;
601 }
602 
603 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
604 static Optional<unsigned> getExtractIndex(Instruction *E) {
605   unsigned Opcode = E->getOpcode();
606   assert((Opcode == Instruction::ExtractElement ||
607           Opcode == Instruction::ExtractValue) &&
608          "Expected extractelement or extractvalue instruction.");
609   if (Opcode == Instruction::ExtractElement) {
610     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
611     if (!CI)
612       return None;
613     return CI->getZExtValue();
614   }
615   ExtractValueInst *EI = cast<ExtractValueInst>(E);
616   if (EI->getNumIndices() != 1)
617     return None;
618   return *EI->idx_begin();
619 }
620 
621 /// \returns True if in-tree use also needs extract. This refers to
622 /// possible scalar operand in vectorized instruction.
623 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
624                                     TargetLibraryInfo *TLI) {
625   unsigned Opcode = UserInst->getOpcode();
626   switch (Opcode) {
627   case Instruction::Load: {
628     LoadInst *LI = cast<LoadInst>(UserInst);
629     return (LI->getPointerOperand() == Scalar);
630   }
631   case Instruction::Store: {
632     StoreInst *SI = cast<StoreInst>(UserInst);
633     return (SI->getPointerOperand() == Scalar);
634   }
635   case Instruction::Call: {
636     CallInst *CI = cast<CallInst>(UserInst);
637     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
638     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
639       if (hasVectorInstrinsicScalarOpd(ID, i))
640         return (CI->getArgOperand(i) == Scalar);
641     }
642     LLVM_FALLTHROUGH;
643   }
644   default:
645     return false;
646   }
647 }
648 
649 /// \returns the AA location that is being access by the instruction.
650 static MemoryLocation getLocation(Instruction *I) {
651   if (StoreInst *SI = dyn_cast<StoreInst>(I))
652     return MemoryLocation::get(SI);
653   if (LoadInst *LI = dyn_cast<LoadInst>(I))
654     return MemoryLocation::get(LI);
655   return MemoryLocation();
656 }
657 
658 /// \returns True if the instruction is not a volatile or atomic load/store.
659 static bool isSimple(Instruction *I) {
660   if (LoadInst *LI = dyn_cast<LoadInst>(I))
661     return LI->isSimple();
662   if (StoreInst *SI = dyn_cast<StoreInst>(I))
663     return SI->isSimple();
664   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
665     return !MI->isVolatile();
666   return true;
667 }
668 
669 /// Shuffles \p Mask in accordance with the given \p SubMask.
670 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
671   if (SubMask.empty())
672     return;
673   if (Mask.empty()) {
674     Mask.append(SubMask.begin(), SubMask.end());
675     return;
676   }
677   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
678   int TermValue = std::min(Mask.size(), SubMask.size());
679   for (int I = 0, E = SubMask.size(); I < E; ++I) {
680     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
681         Mask[SubMask[I]] >= TermValue)
682       continue;
683     NewMask[I] = Mask[SubMask[I]];
684   }
685   Mask.swap(NewMask);
686 }
687 
688 /// Order may have elements assigned special value (size) which is out of
689 /// bounds. Such indices only appear on places which correspond to undef values
690 /// (see canReuseExtract for details) and used in order to avoid undef values
691 /// have effect on operands ordering.
692 /// The first loop below simply finds all unused indices and then the next loop
693 /// nest assigns these indices for undef values positions.
694 /// As an example below Order has two undef positions and they have assigned
695 /// values 3 and 7 respectively:
696 /// before:  6 9 5 4 9 2 1 0
697 /// after:   6 3 5 4 7 2 1 0
698 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
699   const unsigned Sz = Order.size();
700   SmallBitVector UnusedIndices(Sz, /*t=*/true);
701   SmallBitVector MaskedIndices(Sz);
702   for (unsigned I = 0; I < Sz; ++I) {
703     if (Order[I] < Sz)
704       UnusedIndices.reset(Order[I]);
705     else
706       MaskedIndices.set(I);
707   }
708   if (MaskedIndices.none())
709     return;
710   assert(UnusedIndices.count() == MaskedIndices.count() &&
711          "Non-synced masked/available indices.");
712   int Idx = UnusedIndices.find_first();
713   int MIdx = MaskedIndices.find_first();
714   while (MIdx >= 0) {
715     assert(Idx >= 0 && "Indices must be synced.");
716     Order[MIdx] = Idx;
717     Idx = UnusedIndices.find_next(Idx);
718     MIdx = MaskedIndices.find_next(MIdx);
719   }
720 }
721 
722 namespace llvm {
723 
724 static void inversePermutation(ArrayRef<unsigned> Indices,
725                                SmallVectorImpl<int> &Mask) {
726   Mask.clear();
727   const unsigned E = Indices.size();
728   Mask.resize(E, UndefMaskElem);
729   for (unsigned I = 0; I < E; ++I)
730     Mask[Indices[I]] = I;
731 }
732 
733 /// \returns inserting index of InsertElement or InsertValue instruction,
734 /// using Offset as base offset for index.
735 static Optional<unsigned> getInsertIndex(Value *InsertInst,
736                                          unsigned Offset = 0) {
737   int Index = Offset;
738   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
739     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
740       auto *VT = cast<FixedVectorType>(IE->getType());
741       if (CI->getValue().uge(VT->getNumElements()))
742         return None;
743       Index *= VT->getNumElements();
744       Index += CI->getZExtValue();
745       return Index;
746     }
747     return None;
748   }
749 
750   auto *IV = cast<InsertValueInst>(InsertInst);
751   Type *CurrentType = IV->getType();
752   for (unsigned I : IV->indices()) {
753     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
754       Index *= ST->getNumElements();
755       CurrentType = ST->getElementType(I);
756     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
757       Index *= AT->getNumElements();
758       CurrentType = AT->getElementType();
759     } else {
760       return None;
761     }
762     Index += I;
763   }
764   return Index;
765 }
766 
767 /// Reorders the list of scalars in accordance with the given \p Mask.
768 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
769                            ArrayRef<int> Mask) {
770   assert(!Mask.empty() && "Expected non-empty mask.");
771   SmallVector<Value *> Prev(Scalars.size(),
772                             UndefValue::get(Scalars.front()->getType()));
773   Prev.swap(Scalars);
774   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
775     if (Mask[I] != UndefMaskElem)
776       Scalars[Mask[I]] = Prev[I];
777 }
778 
779 /// Checks if the provided value does not require scheduling. It does not
780 /// require scheduling if this is not an instruction or it is an instruction
781 /// that does not read/write memory and all operands are either not instructions
782 /// or phi nodes or instructions from different blocks.
783 static bool areAllOperandsNonInsts(Value *V) {
784   auto *I = dyn_cast<Instruction>(V);
785   if (!I)
786     return true;
787   return !I->mayReadOrWriteMemory() && all_of(I->operands(), [I](Value *V) {
788     auto *IO = dyn_cast<Instruction>(V);
789     if (!IO)
790       return true;
791     return isa<PHINode>(IO) || IO->getParent() != I->getParent();
792   });
793 }
794 
795 /// Checks if the provided value does not require scheduling. It does not
796 /// require scheduling if this is not an instruction or it is an instruction
797 /// that does not read/write memory and all users are phi nodes or instructions
798 /// from the different blocks.
799 static bool isUsedOutsideBlock(Value *V) {
800   auto *I = dyn_cast<Instruction>(V);
801   if (!I)
802     return true;
803   // Limits the number of uses to save compile time.
804   constexpr int UsesLimit = 8;
805   return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
806          all_of(I->users(), [I](User *U) {
807            auto *IU = dyn_cast<Instruction>(U);
808            if (!IU)
809              return true;
810            return IU->getParent() != I->getParent() || isa<PHINode>(IU);
811          });
812 }
813 
814 /// Checks if the specified value does not require scheduling. It does not
815 /// require scheduling if all operands and all users do not need to be scheduled
816 /// in the current basic block.
817 static bool doesNotNeedToBeScheduled(Value *V) {
818   return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
819 }
820 
821 /// Checks if the specified array of instructions does not require scheduling.
822 /// It is so if all either instructions have operands that do not require
823 /// scheduling or their users do not require scheduling since they are phis or
824 /// in other basic blocks.
825 static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
826   return !VL.empty() &&
827          (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
828 }
829 
830 namespace slpvectorizer {
831 
832 /// Bottom Up SLP Vectorizer.
833 class BoUpSLP {
834   struct TreeEntry;
835   struct ScheduleData;
836 
837 public:
838   using ValueList = SmallVector<Value *, 8>;
839   using InstrList = SmallVector<Instruction *, 16>;
840   using ValueSet = SmallPtrSet<Value *, 16>;
841   using StoreList = SmallVector<StoreInst *, 8>;
842   using ExtraValueToDebugLocsMap =
843       MapVector<Value *, SmallVector<Instruction *, 2>>;
844   using OrdersType = SmallVector<unsigned, 4>;
845 
846   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
847           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
848           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
849           MemorySSA *MSSA, const DataLayout *DL, OptimizationRemarkEmitter *ORE)
850       : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
851         DT(Dt), AC(AC), DB(DB), MSSA(MSSA), DL(DL), ORE(ORE),
852         Builder(Se->getContext()) {
853     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
854     // Use the vector register size specified by the target unless overridden
855     // by a command-line option.
856     // TODO: It would be better to limit the vectorization factor based on
857     //       data type rather than just register size. For example, x86 AVX has
858     //       256-bit registers, but it does not support integer operations
859     //       at that width (that requires AVX2).
860     if (MaxVectorRegSizeOption.getNumOccurrences())
861       MaxVecRegSize = MaxVectorRegSizeOption;
862     else
863       MaxVecRegSize =
864           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
865               .getFixedSize();
866 
867     if (MinVectorRegSizeOption.getNumOccurrences())
868       MinVecRegSize = MinVectorRegSizeOption;
869     else
870       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
871   }
872 
873   /// Vectorize the tree that starts with the elements in \p VL.
874   /// Returns the vectorized root.
875   Value *vectorizeTree();
876 
877   /// Vectorize the tree but with the list of externally used values \p
878   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
879   /// generated extractvalue instructions.
880   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
881 
882   /// \returns the cost incurred by unwanted spills and fills, caused by
883   /// holding live values over call sites.
884   InstructionCost getSpillCost() const;
885 
886   /// \returns the vectorization cost of the subtree that starts at \p VL.
887   /// A negative number means that this is profitable.
888   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
889 
890   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
891   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
892   void buildTree(ArrayRef<Value *> Roots,
893                  ArrayRef<Value *> UserIgnoreLst = None);
894 
895   /// Builds external uses of the vectorized scalars, i.e. the list of
896   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
897   /// ExternallyUsedValues contains additional list of external uses to handle
898   /// vectorization of reductions.
899   void
900   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
901 
902   /// Clear the internal data structures that are created by 'buildTree'.
903   void deleteTree() {
904     VectorizableTree.clear();
905     ScalarToTreeEntry.clear();
906     MustGather.clear();
907     ExternalUses.clear();
908     for (auto &Iter : BlocksSchedules) {
909       BlockScheduling *BS = Iter.second.get();
910       BS->clear();
911     }
912     MinBWs.clear();
913     InstrElementSize.clear();
914   }
915 
916   unsigned getTreeSize() const { return VectorizableTree.size(); }
917 
918   /// Perform LICM and CSE on the newly generated gather sequences.
919   void optimizeGatherSequence();
920 
921   /// Checks if the specified gather tree entry \p TE can be represented as a
922   /// shuffled vector entry + (possibly) permutation with other gathers. It
923   /// implements the checks only for possibly ordered scalars (Loads,
924   /// ExtractElement, ExtractValue), which can be part of the graph.
925   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
926 
927   /// Gets reordering data for the given tree entry. If the entry is vectorized
928   /// - just return ReorderIndices, otherwise check if the scalars can be
929   /// reordered and return the most optimal order.
930   /// \param TopToBottom If true, include the order of vectorized stores and
931   /// insertelement nodes, otherwise skip them.
932   Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
933 
934   /// Reorders the current graph to the most profitable order starting from the
935   /// root node to the leaf nodes. The best order is chosen only from the nodes
936   /// of the same size (vectorization factor). Smaller nodes are considered
937   /// parts of subgraph with smaller VF and they are reordered independently. We
938   /// can make it because we still need to extend smaller nodes to the wider VF
939   /// and we can merge reordering shuffles with the widening shuffles.
940   void reorderTopToBottom();
941 
942   /// Reorders the current graph to the most profitable order starting from
943   /// leaves to the root. It allows to rotate small subgraphs and reduce the
944   /// number of reshuffles if the leaf nodes use the same order. In this case we
945   /// can merge the orders and just shuffle user node instead of shuffling its
946   /// operands. Plus, even the leaf nodes have different orders, it allows to
947   /// sink reordering in the graph closer to the root node and merge it later
948   /// during analysis.
949   void reorderBottomToTop(bool IgnoreReorder = false);
950 
951   /// \return The vector element size in bits to use when vectorizing the
952   /// expression tree ending at \p V. If V is a store, the size is the width of
953   /// the stored value. Otherwise, the size is the width of the largest loaded
954   /// value reaching V. This method is used by the vectorizer to calculate
955   /// vectorization factors.
956   unsigned getVectorElementSize(Value *V);
957 
958   /// Compute the minimum type sizes required to represent the entries in a
959   /// vectorizable tree.
960   void computeMinimumValueSizes();
961 
962   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
963   unsigned getMaxVecRegSize() const {
964     return MaxVecRegSize;
965   }
966 
967   // \returns minimum vector register size as set by cl::opt.
968   unsigned getMinVecRegSize() const {
969     return MinVecRegSize;
970   }
971 
972   unsigned getMinVF(unsigned Sz) const {
973     return std::max(2U, getMinVecRegSize() / Sz);
974   }
975 
976   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
977     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
978       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
979     return MaxVF ? MaxVF : UINT_MAX;
980   }
981 
982   /// Check if homogeneous aggregate is isomorphic to some VectorType.
983   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
984   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
985   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
986   ///
987   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
988   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
989 
990   /// \returns True if the VectorizableTree is both tiny and not fully
991   /// vectorizable. We do not vectorize such trees.
992   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
993 
994   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
995   /// can be load combined in the backend. Load combining may not be allowed in
996   /// the IR optimizer, so we do not want to alter the pattern. For example,
997   /// partially transforming a scalar bswap() pattern into vector code is
998   /// effectively impossible for the backend to undo.
999   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1000   ///       may not be necessary.
1001   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1002 
1003   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1004   /// can be load combined in the backend. Load combining may not be allowed in
1005   /// the IR optimizer, so we do not want to alter the pattern. For example,
1006   /// partially transforming a scalar bswap() pattern into vector code is
1007   /// effectively impossible for the backend to undo.
1008   /// TODO: If load combining is allowed in the IR optimizer, this analysis
1009   ///       may not be necessary.
1010   bool isLoadCombineCandidate() const;
1011 
1012   OptimizationRemarkEmitter *getORE() { return ORE; }
1013 
1014   /// This structure holds any data we need about the edges being traversed
1015   /// during buildTree_rec(). We keep track of:
1016   /// (i) the user TreeEntry index, and
1017   /// (ii) the index of the edge.
1018   struct EdgeInfo {
1019     EdgeInfo() = default;
1020     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1021         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
1022     /// The user TreeEntry.
1023     TreeEntry *UserTE = nullptr;
1024     /// The operand index of the use.
1025     unsigned EdgeIdx = UINT_MAX;
1026 #ifndef NDEBUG
1027     friend inline raw_ostream &operator<<(raw_ostream &OS,
1028                                           const BoUpSLP::EdgeInfo &EI) {
1029       EI.dump(OS);
1030       return OS;
1031     }
1032     /// Debug print.
1033     void dump(raw_ostream &OS) const {
1034       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1035          << " EdgeIdx:" << EdgeIdx << "}";
1036     }
1037     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1038 #endif
1039   };
1040 
1041   /// A helper data structure to hold the operands of a vector of instructions.
1042   /// This supports a fixed vector length for all operand vectors.
1043   class VLOperands {
1044     /// For each operand we need (i) the value, and (ii) the opcode that it
1045     /// would be attached to if the expression was in a left-linearized form.
1046     /// This is required to avoid illegal operand reordering.
1047     /// For example:
1048     /// \verbatim
1049     ///                         0 Op1
1050     ///                         |/
1051     /// Op1 Op2   Linearized    + Op2
1052     ///   \ /     ---------->   |/
1053     ///    -                    -
1054     ///
1055     /// Op1 - Op2            (0 + Op1) - Op2
1056     /// \endverbatim
1057     ///
1058     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1059     ///
1060     /// Another way to think of this is to track all the operations across the
1061     /// path from the operand all the way to the root of the tree and to
1062     /// calculate the operation that corresponds to this path. For example, the
1063     /// path from Op2 to the root crosses the RHS of the '-', therefore the
1064     /// corresponding operation is a '-' (which matches the one in the
1065     /// linearized tree, as shown above).
1066     ///
1067     /// For lack of a better term, we refer to this operation as Accumulated
1068     /// Path Operation (APO).
1069     struct OperandData {
1070       OperandData() = default;
1071       OperandData(Value *V, bool APO, bool IsUsed)
1072           : V(V), APO(APO), IsUsed(IsUsed) {}
1073       /// The operand value.
1074       Value *V = nullptr;
1075       /// TreeEntries only allow a single opcode, or an alternate sequence of
1076       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1077       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1078       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1079       /// (e.g., Add/Mul)
1080       bool APO = false;
1081       /// Helper data for the reordering function.
1082       bool IsUsed = false;
1083     };
1084 
1085     /// During operand reordering, we are trying to select the operand at lane
1086     /// that matches best with the operand at the neighboring lane. Our
1087     /// selection is based on the type of value we are looking for. For example,
1088     /// if the neighboring lane has a load, we need to look for a load that is
1089     /// accessing a consecutive address. These strategies are summarized in the
1090     /// 'ReorderingMode' enumerator.
1091     enum class ReorderingMode {
1092       Load,     ///< Matching loads to consecutive memory addresses
1093       Opcode,   ///< Matching instructions based on opcode (same or alternate)
1094       Constant, ///< Matching constants
1095       Splat,    ///< Matching the same instruction multiple times (broadcast)
1096       Failed,   ///< We failed to create a vectorizable group
1097     };
1098 
1099     using OperandDataVec = SmallVector<OperandData, 2>;
1100 
1101     /// A vector of operand vectors.
1102     SmallVector<OperandDataVec, 4> OpsVec;
1103 
1104     const DataLayout &DL;
1105     ScalarEvolution &SE;
1106     const BoUpSLP &R;
1107 
1108     /// \returns the operand data at \p OpIdx and \p Lane.
1109     OperandData &getData(unsigned OpIdx, unsigned Lane) {
1110       return OpsVec[OpIdx][Lane];
1111     }
1112 
1113     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1114     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1115       return OpsVec[OpIdx][Lane];
1116     }
1117 
1118     /// Clears the used flag for all entries.
1119     void clearUsed() {
1120       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1121            OpIdx != NumOperands; ++OpIdx)
1122         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1123              ++Lane)
1124           OpsVec[OpIdx][Lane].IsUsed = false;
1125     }
1126 
1127     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1128     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1129       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1130     }
1131 
1132     // The hard-coded scores listed here are not very important, though it shall
1133     // be higher for better matches to improve the resulting cost. When
1134     // computing the scores of matching one sub-tree with another, we are
1135     // basically counting the number of values that are matching. So even if all
1136     // scores are set to 1, we would still get a decent matching result.
1137     // However, sometimes we have to break ties. For example we may have to
1138     // choose between matching loads vs matching opcodes. This is what these
1139     // scores are helping us with: they provide the order of preference. Also,
1140     // this is important if the scalar is externally used or used in another
1141     // tree entry node in the different lane.
1142 
1143     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1144     static const int ScoreConsecutiveLoads = 4;
1145     /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1146     static const int ScoreReversedLoads = 3;
1147     /// ExtractElementInst from same vector and consecutive indexes.
1148     static const int ScoreConsecutiveExtracts = 4;
1149     /// ExtractElementInst from same vector and reversed indices.
1150     static const int ScoreReversedExtracts = 3;
1151     /// Constants.
1152     static const int ScoreConstants = 2;
1153     /// Instructions with the same opcode.
1154     static const int ScoreSameOpcode = 2;
1155     /// Instructions with alt opcodes (e.g, add + sub).
1156     static const int ScoreAltOpcodes = 1;
1157     /// Identical instructions (a.k.a. splat or broadcast).
1158     static const int ScoreSplat = 1;
1159     /// Matching with an undef is preferable to failing.
1160     static const int ScoreUndef = 1;
1161     /// Score for failing to find a decent match.
1162     static const int ScoreFail = 0;
1163     /// Score if all users are vectorized.
1164     static const int ScoreAllUserVectorized = 1;
1165 
1166     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1167     /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1168     /// MainAltOps.
1169     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1170                                ScalarEvolution &SE, int NumLanes,
1171                                ArrayRef<Value *> MainAltOps) {
1172       if (V1 == V2)
1173         return VLOperands::ScoreSplat;
1174 
1175       auto *LI1 = dyn_cast<LoadInst>(V1);
1176       auto *LI2 = dyn_cast<LoadInst>(V2);
1177       if (LI1 && LI2) {
1178         if (LI1->getParent() != LI2->getParent())
1179           return VLOperands::ScoreFail;
1180 
1181         Optional<int> Dist = getPointersDiff(
1182             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1183             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1184         if (!Dist || *Dist == 0)
1185           return VLOperands::ScoreFail;
1186         // The distance is too large - still may be profitable to use masked
1187         // loads/gathers.
1188         if (std::abs(*Dist) > NumLanes / 2)
1189           return VLOperands::ScoreAltOpcodes;
1190         // This still will detect consecutive loads, but we might have "holes"
1191         // in some cases. It is ok for non-power-2 vectorization and may produce
1192         // better results. It should not affect current vectorization.
1193         return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
1194                            : VLOperands::ScoreReversedLoads;
1195       }
1196 
1197       auto *C1 = dyn_cast<Constant>(V1);
1198       auto *C2 = dyn_cast<Constant>(V2);
1199       if (C1 && C2)
1200         return VLOperands::ScoreConstants;
1201 
1202       // Extracts from consecutive indexes of the same vector better score as
1203       // the extracts could be optimized away.
1204       Value *EV1;
1205       ConstantInt *Ex1Idx;
1206       if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1207         // Undefs are always profitable for extractelements.
1208         if (isa<UndefValue>(V2))
1209           return VLOperands::ScoreConsecutiveExtracts;
1210         Value *EV2 = nullptr;
1211         ConstantInt *Ex2Idx = nullptr;
1212         if (match(V2,
1213                   m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
1214                                                          m_Undef())))) {
1215           // Undefs are always profitable for extractelements.
1216           if (!Ex2Idx)
1217             return VLOperands::ScoreConsecutiveExtracts;
1218           if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
1219             return VLOperands::ScoreConsecutiveExtracts;
1220           if (EV2 == EV1) {
1221             int Idx1 = Ex1Idx->getZExtValue();
1222             int Idx2 = Ex2Idx->getZExtValue();
1223             int Dist = Idx2 - Idx1;
1224             // The distance is too large - still may be profitable to use
1225             // shuffles.
1226             if (std::abs(Dist) == 0)
1227               return VLOperands::ScoreSplat;
1228             if (std::abs(Dist) > NumLanes / 2)
1229               return VLOperands::ScoreSameOpcode;
1230             return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
1231                               : VLOperands::ScoreReversedExtracts;
1232           }
1233           return VLOperands::ScoreAltOpcodes;
1234         }
1235         return VLOperands::ScoreFail;
1236       }
1237 
1238       auto *I1 = dyn_cast<Instruction>(V1);
1239       auto *I2 = dyn_cast<Instruction>(V2);
1240       if (I1 && I2) {
1241         if (I1->getParent() != I2->getParent())
1242           return VLOperands::ScoreFail;
1243         SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1244         Ops.push_back(I1);
1245         Ops.push_back(I2);
1246         InstructionsState S = getSameOpcode(Ops);
1247         // Note: Only consider instructions with <= 2 operands to avoid
1248         // complexity explosion.
1249         if (S.getOpcode() &&
1250             (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1251              !S.isAltShuffle()) &&
1252             all_of(Ops, [&S](Value *V) {
1253               return cast<Instruction>(V)->getNumOperands() ==
1254                      S.MainOp->getNumOperands();
1255             }))
1256           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1257                                   : VLOperands::ScoreSameOpcode;
1258       }
1259 
1260       if (isa<UndefValue>(V2))
1261         return VLOperands::ScoreUndef;
1262 
1263       return VLOperands::ScoreFail;
1264     }
1265 
1266     /// \param Lane lane of the operands under analysis.
1267     /// \param OpIdx operand index in \p Lane lane we're looking the best
1268     /// candidate for.
1269     /// \param Idx operand index of the current candidate value.
1270     /// \returns The additional score due to possible broadcasting of the
1271     /// elements in the lane. It is more profitable to have power-of-2 unique
1272     /// elements in the lane, it will be vectorized with higher probability
1273     /// after removing duplicates. Currently the SLP vectorizer supports only
1274     /// vectorization of the power-of-2 number of unique scalars.
1275     int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1276       Value *IdxLaneV = getData(Idx, Lane).V;
1277       if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1278         return 0;
1279       SmallPtrSet<Value *, 4> Uniques;
1280       for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1281         if (Ln == Lane)
1282           continue;
1283         Value *OpIdxLnV = getData(OpIdx, Ln).V;
1284         if (!isa<Instruction>(OpIdxLnV))
1285           return 0;
1286         Uniques.insert(OpIdxLnV);
1287       }
1288       int UniquesCount = Uniques.size();
1289       int UniquesCntWithIdxLaneV =
1290           Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1291       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1292       int UniquesCntWithOpIdxLaneV =
1293           Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1294       if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1295         return 0;
1296       return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1297               UniquesCntWithOpIdxLaneV) -
1298              (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1299     }
1300 
1301     /// \param Lane lane of the operands under analysis.
1302     /// \param OpIdx operand index in \p Lane lane we're looking the best
1303     /// candidate for.
1304     /// \param Idx operand index of the current candidate value.
1305     /// \returns The additional score for the scalar which users are all
1306     /// vectorized.
1307     int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1308       Value *IdxLaneV = getData(Idx, Lane).V;
1309       Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1310       // Do not care about number of uses for vector-like instructions
1311       // (extractelement/extractvalue with constant indices), they are extracts
1312       // themselves and already externally used. Vectorization of such
1313       // instructions does not add extra extractelement instruction, just may
1314       // remove it.
1315       if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1316           isVectorLikeInstWithConstOps(OpIdxLaneV))
1317         return VLOperands::ScoreAllUserVectorized;
1318       auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1319       if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1320         return 0;
1321       return R.areAllUsersVectorized(IdxLaneI, None)
1322                  ? VLOperands::ScoreAllUserVectorized
1323                  : 0;
1324     }
1325 
1326     /// Go through the operands of \p LHS and \p RHS recursively until \p
1327     /// MaxLevel, and return the cummulative score. For example:
1328     /// \verbatim
1329     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1330     ///     \ /         \ /         \ /        \ /
1331     ///      +           +           +          +
1332     ///     G1          G2          G3         G4
1333     /// \endverbatim
1334     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1335     /// each level recursively, accumulating the score. It starts from matching
1336     /// the additions at level 0, then moves on to the loads (level 1). The
1337     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1338     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1339     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1340     /// Please note that the order of the operands does not matter, as we
1341     /// evaluate the score of all profitable combinations of operands. In
1342     /// other words the score of G1 and G4 is the same as G1 and G2. This
1343     /// heuristic is based on ideas described in:
1344     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1345     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1346     ///   Luís F. W. Góes
1347     int getScoreAtLevelRec(Value *LHS, Value *RHS, int CurrLevel, int MaxLevel,
1348                            ArrayRef<Value *> MainAltOps) {
1349 
1350       // Get the shallow score of V1 and V2.
1351       int ShallowScoreAtThisLevel =
1352           getShallowScore(LHS, RHS, DL, SE, getNumLanes(), MainAltOps);
1353 
1354       // If reached MaxLevel,
1355       //  or if V1 and V2 are not instructions,
1356       //  or if they are SPLAT,
1357       //  or if they are not consecutive,
1358       //  or if profitable to vectorize loads or extractelements, early return
1359       //  the current cost.
1360       auto *I1 = dyn_cast<Instruction>(LHS);
1361       auto *I2 = dyn_cast<Instruction>(RHS);
1362       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1363           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1364           (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1365             (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1366             (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1367            ShallowScoreAtThisLevel))
1368         return ShallowScoreAtThisLevel;
1369       assert(I1 && I2 && "Should have early exited.");
1370 
1371       // Contains the I2 operand indexes that got matched with I1 operands.
1372       SmallSet<unsigned, 4> Op2Used;
1373 
1374       // Recursion towards the operands of I1 and I2. We are trying all possible
1375       // operand pairs, and keeping track of the best score.
1376       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1377            OpIdx1 != NumOperands1; ++OpIdx1) {
1378         // Try to pair op1I with the best operand of I2.
1379         int MaxTmpScore = 0;
1380         unsigned MaxOpIdx2 = 0;
1381         bool FoundBest = false;
1382         // If I2 is commutative try all combinations.
1383         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1384         unsigned ToIdx = isCommutative(I2)
1385                              ? I2->getNumOperands()
1386                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1387         assert(FromIdx <= ToIdx && "Bad index");
1388         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1389           // Skip operands already paired with OpIdx1.
1390           if (Op2Used.count(OpIdx2))
1391             continue;
1392           // Recursively calculate the cost at each level
1393           int TmpScore =
1394               getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1395                                  CurrLevel + 1, MaxLevel, None);
1396           // Look for the best score.
1397           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1398             MaxTmpScore = TmpScore;
1399             MaxOpIdx2 = OpIdx2;
1400             FoundBest = true;
1401           }
1402         }
1403         if (FoundBest) {
1404           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1405           Op2Used.insert(MaxOpIdx2);
1406           ShallowScoreAtThisLevel += MaxTmpScore;
1407         }
1408       }
1409       return ShallowScoreAtThisLevel;
1410     }
1411 
1412     /// Score scaling factor for fully compatible instructions but with
1413     /// different number of external uses. Allows better selection of the
1414     /// instructions with less external uses.
1415     static const int ScoreScaleFactor = 10;
1416 
1417     /// \Returns the look-ahead score, which tells us how much the sub-trees
1418     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1419     /// score. This helps break ties in an informed way when we cannot decide on
1420     /// the order of the operands by just considering the immediate
1421     /// predecessors.
1422     int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1423                           int Lane, unsigned OpIdx, unsigned Idx,
1424                           bool &IsUsed) {
1425       int Score =
1426           getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth, MainAltOps);
1427       if (Score) {
1428         int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1429         if (Score <= -SplatScore) {
1430           // Set the minimum score for splat-like sequence to avoid setting
1431           // failed state.
1432           Score = 1;
1433         } else {
1434           Score += SplatScore;
1435           // Scale score to see the difference between different operands
1436           // and similar operands but all vectorized/not all vectorized
1437           // uses. It does not affect actual selection of the best
1438           // compatible operand in general, just allows to select the
1439           // operand with all vectorized uses.
1440           Score *= ScoreScaleFactor;
1441           Score += getExternalUseScore(Lane, OpIdx, Idx);
1442           IsUsed = true;
1443         }
1444       }
1445       return Score;
1446     }
1447 
1448     /// Best defined scores per lanes between the passes. Used to choose the
1449     /// best operand (with the highest score) between the passes.
1450     /// The key - {Operand Index, Lane}.
1451     /// The value - the best score between the passes for the lane and the
1452     /// operand.
1453     SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
1454         BestScoresPerLanes;
1455 
1456     // Search all operands in Ops[*][Lane] for the one that matches best
1457     // Ops[OpIdx][LastLane] and return its opreand index.
1458     // If no good match can be found, return None.
1459     Optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1460                                       ArrayRef<ReorderingMode> ReorderingModes,
1461                                       ArrayRef<Value *> MainAltOps) {
1462       unsigned NumOperands = getNumOperands();
1463 
1464       // The operand of the previous lane at OpIdx.
1465       Value *OpLastLane = getData(OpIdx, LastLane).V;
1466 
1467       // Our strategy mode for OpIdx.
1468       ReorderingMode RMode = ReorderingModes[OpIdx];
1469       if (RMode == ReorderingMode::Failed)
1470         return None;
1471 
1472       // The linearized opcode of the operand at OpIdx, Lane.
1473       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1474 
1475       // The best operand index and its score.
1476       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1477       // are using the score to differentiate between the two.
1478       struct BestOpData {
1479         Optional<unsigned> Idx = None;
1480         unsigned Score = 0;
1481       } BestOp;
1482       BestOp.Score =
1483           BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1484               .first->second;
1485 
1486       // Track if the operand must be marked as used. If the operand is set to
1487       // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1488       // want to reestimate the operands again on the following iterations).
1489       bool IsUsed =
1490           RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1491       // Iterate through all unused operands and look for the best.
1492       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1493         // Get the operand at Idx and Lane.
1494         OperandData &OpData = getData(Idx, Lane);
1495         Value *Op = OpData.V;
1496         bool OpAPO = OpData.APO;
1497 
1498         // Skip already selected operands.
1499         if (OpData.IsUsed)
1500           continue;
1501 
1502         // Skip if we are trying to move the operand to a position with a
1503         // different opcode in the linearized tree form. This would break the
1504         // semantics.
1505         if (OpAPO != OpIdxAPO)
1506           continue;
1507 
1508         // Look for an operand that matches the current mode.
1509         switch (RMode) {
1510         case ReorderingMode::Load:
1511         case ReorderingMode::Constant:
1512         case ReorderingMode::Opcode: {
1513           bool LeftToRight = Lane > LastLane;
1514           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1515           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1516           int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1517                                         OpIdx, Idx, IsUsed);
1518           if (Score > static_cast<int>(BestOp.Score)) {
1519             BestOp.Idx = Idx;
1520             BestOp.Score = Score;
1521             BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1522           }
1523           break;
1524         }
1525         case ReorderingMode::Splat:
1526           if (Op == OpLastLane)
1527             BestOp.Idx = Idx;
1528           break;
1529         case ReorderingMode::Failed:
1530           llvm_unreachable("Not expected Failed reordering mode.");
1531         }
1532       }
1533 
1534       if (BestOp.Idx) {
1535         getData(BestOp.Idx.getValue(), Lane).IsUsed = IsUsed;
1536         return BestOp.Idx;
1537       }
1538       // If we could not find a good match return None.
1539       return None;
1540     }
1541 
1542     /// Helper for reorderOperandVecs.
1543     /// \returns the lane that we should start reordering from. This is the one
1544     /// which has the least number of operands that can freely move about or
1545     /// less profitable because it already has the most optimal set of operands.
1546     unsigned getBestLaneToStartReordering() const {
1547       unsigned Min = UINT_MAX;
1548       unsigned SameOpNumber = 0;
1549       // std::pair<unsigned, unsigned> is used to implement a simple voting
1550       // algorithm and choose the lane with the least number of operands that
1551       // can freely move about or less profitable because it already has the
1552       // most optimal set of operands. The first unsigned is a counter for
1553       // voting, the second unsigned is the counter of lanes with instructions
1554       // with same/alternate opcodes and same parent basic block.
1555       MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
1556       // Try to be closer to the original results, if we have multiple lanes
1557       // with same cost. If 2 lanes have the same cost, use the one with the
1558       // lowest index.
1559       for (int I = getNumLanes(); I > 0; --I) {
1560         unsigned Lane = I - 1;
1561         OperandsOrderData NumFreeOpsHash =
1562             getMaxNumOperandsThatCanBeReordered(Lane);
1563         // Compare the number of operands that can move and choose the one with
1564         // the least number.
1565         if (NumFreeOpsHash.NumOfAPOs < Min) {
1566           Min = NumFreeOpsHash.NumOfAPOs;
1567           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1568           HashMap.clear();
1569           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1570         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1571                    NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1572           // Select the most optimal lane in terms of number of operands that
1573           // should be moved around.
1574           SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1575           HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1576         } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1577                    NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1578           auto It = HashMap.find(NumFreeOpsHash.Hash);
1579           if (It == HashMap.end())
1580             HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1581           else
1582             ++It->second.first;
1583         }
1584       }
1585       // Select the lane with the minimum counter.
1586       unsigned BestLane = 0;
1587       unsigned CntMin = UINT_MAX;
1588       for (const auto &Data : reverse(HashMap)) {
1589         if (Data.second.first < CntMin) {
1590           CntMin = Data.second.first;
1591           BestLane = Data.second.second;
1592         }
1593       }
1594       return BestLane;
1595     }
1596 
1597     /// Data structure that helps to reorder operands.
1598     struct OperandsOrderData {
1599       /// The best number of operands with the same APOs, which can be
1600       /// reordered.
1601       unsigned NumOfAPOs = UINT_MAX;
1602       /// Number of operands with the same/alternate instruction opcode and
1603       /// parent.
1604       unsigned NumOpsWithSameOpcodeParent = 0;
1605       /// Hash for the actual operands ordering.
1606       /// Used to count operands, actually their position id and opcode
1607       /// value. It is used in the voting mechanism to find the lane with the
1608       /// least number of operands that can freely move about or less profitable
1609       /// because it already has the most optimal set of operands. Can be
1610       /// replaced with SmallVector<unsigned> instead but hash code is faster
1611       /// and requires less memory.
1612       unsigned Hash = 0;
1613     };
1614     /// \returns the maximum number of operands that are allowed to be reordered
1615     /// for \p Lane and the number of compatible instructions(with the same
1616     /// parent/opcode). This is used as a heuristic for selecting the first lane
1617     /// to start operand reordering.
1618     OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1619       unsigned CntTrue = 0;
1620       unsigned NumOperands = getNumOperands();
1621       // Operands with the same APO can be reordered. We therefore need to count
1622       // how many of them we have for each APO, like this: Cnt[APO] = x.
1623       // Since we only have two APOs, namely true and false, we can avoid using
1624       // a map. Instead we can simply count the number of operands that
1625       // correspond to one of them (in this case the 'true' APO), and calculate
1626       // the other by subtracting it from the total number of operands.
1627       // Operands with the same instruction opcode and parent are more
1628       // profitable since we don't need to move them in many cases, with a high
1629       // probability such lane already can be vectorized effectively.
1630       bool AllUndefs = true;
1631       unsigned NumOpsWithSameOpcodeParent = 0;
1632       Instruction *OpcodeI = nullptr;
1633       BasicBlock *Parent = nullptr;
1634       unsigned Hash = 0;
1635       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1636         const OperandData &OpData = getData(OpIdx, Lane);
1637         if (OpData.APO)
1638           ++CntTrue;
1639         // Use Boyer-Moore majority voting for finding the majority opcode and
1640         // the number of times it occurs.
1641         if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1642           if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
1643               I->getParent() != Parent) {
1644             if (NumOpsWithSameOpcodeParent == 0) {
1645               NumOpsWithSameOpcodeParent = 1;
1646               OpcodeI = I;
1647               Parent = I->getParent();
1648             } else {
1649               --NumOpsWithSameOpcodeParent;
1650             }
1651           } else {
1652             ++NumOpsWithSameOpcodeParent;
1653           }
1654         }
1655         Hash = hash_combine(
1656             Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1657         AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1658       }
1659       if (AllUndefs)
1660         return {};
1661       OperandsOrderData Data;
1662       Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1663       Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1664       Data.Hash = Hash;
1665       return Data;
1666     }
1667 
1668     /// Go through the instructions in VL and append their operands.
1669     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1670       assert(!VL.empty() && "Bad VL");
1671       assert((empty() || VL.size() == getNumLanes()) &&
1672              "Expected same number of lanes");
1673       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1674       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1675       OpsVec.resize(NumOperands);
1676       unsigned NumLanes = VL.size();
1677       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1678         OpsVec[OpIdx].resize(NumLanes);
1679         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1680           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1681           // Our tree has just 3 nodes: the root and two operands.
1682           // It is therefore trivial to get the APO. We only need to check the
1683           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1684           // RHS operand. The LHS operand of both add and sub is never attached
1685           // to an inversese operation in the linearized form, therefore its APO
1686           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1687 
1688           // Since operand reordering is performed on groups of commutative
1689           // operations or alternating sequences (e.g., +, -), we can safely
1690           // tell the inverse operations by checking commutativity.
1691           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1692           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1693           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1694                                  APO, false};
1695         }
1696       }
1697     }
1698 
1699     /// \returns the number of operands.
1700     unsigned getNumOperands() const { return OpsVec.size(); }
1701 
1702     /// \returns the number of lanes.
1703     unsigned getNumLanes() const { return OpsVec[0].size(); }
1704 
1705     /// \returns the operand value at \p OpIdx and \p Lane.
1706     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1707       return getData(OpIdx, Lane).V;
1708     }
1709 
1710     /// \returns true if the data structure is empty.
1711     bool empty() const { return OpsVec.empty(); }
1712 
1713     /// Clears the data.
1714     void clear() { OpsVec.clear(); }
1715 
1716     /// \Returns true if there are enough operands identical to \p Op to fill
1717     /// the whole vector.
1718     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1719     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1720       bool OpAPO = getData(OpIdx, Lane).APO;
1721       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1722         if (Ln == Lane)
1723           continue;
1724         // This is set to true if we found a candidate for broadcast at Lane.
1725         bool FoundCandidate = false;
1726         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1727           OperandData &Data = getData(OpI, Ln);
1728           if (Data.APO != OpAPO || Data.IsUsed)
1729             continue;
1730           if (Data.V == Op) {
1731             FoundCandidate = true;
1732             Data.IsUsed = true;
1733             break;
1734           }
1735         }
1736         if (!FoundCandidate)
1737           return false;
1738       }
1739       return true;
1740     }
1741 
1742   public:
1743     /// Initialize with all the operands of the instruction vector \p RootVL.
1744     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1745                ScalarEvolution &SE, const BoUpSLP &R)
1746         : DL(DL), SE(SE), R(R) {
1747       // Append all the operands of RootVL.
1748       appendOperandsOfVL(RootVL);
1749     }
1750 
1751     /// \Returns a value vector with the operands across all lanes for the
1752     /// opearnd at \p OpIdx.
1753     ValueList getVL(unsigned OpIdx) const {
1754       ValueList OpVL(OpsVec[OpIdx].size());
1755       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1756              "Expected same num of lanes across all operands");
1757       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1758         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1759       return OpVL;
1760     }
1761 
1762     // Performs operand reordering for 2 or more operands.
1763     // The original operands are in OrigOps[OpIdx][Lane].
1764     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1765     void reorder() {
1766       unsigned NumOperands = getNumOperands();
1767       unsigned NumLanes = getNumLanes();
1768       // Each operand has its own mode. We are using this mode to help us select
1769       // the instructions for each lane, so that they match best with the ones
1770       // we have selected so far.
1771       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1772 
1773       // This is a greedy single-pass algorithm. We are going over each lane
1774       // once and deciding on the best order right away with no back-tracking.
1775       // However, in order to increase its effectiveness, we start with the lane
1776       // that has operands that can move the least. For example, given the
1777       // following lanes:
1778       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1779       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1780       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1781       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1782       // we will start at Lane 1, since the operands of the subtraction cannot
1783       // be reordered. Then we will visit the rest of the lanes in a circular
1784       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1785 
1786       // Find the first lane that we will start our search from.
1787       unsigned FirstLane = getBestLaneToStartReordering();
1788 
1789       // Initialize the modes.
1790       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1791         Value *OpLane0 = getValue(OpIdx, FirstLane);
1792         // Keep track if we have instructions with all the same opcode on one
1793         // side.
1794         if (isa<LoadInst>(OpLane0))
1795           ReorderingModes[OpIdx] = ReorderingMode::Load;
1796         else if (isa<Instruction>(OpLane0)) {
1797           // Check if OpLane0 should be broadcast.
1798           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1799             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1800           else
1801             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1802         }
1803         else if (isa<Constant>(OpLane0))
1804           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1805         else if (isa<Argument>(OpLane0))
1806           // Our best hope is a Splat. It may save some cost in some cases.
1807           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1808         else
1809           // NOTE: This should be unreachable.
1810           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1811       }
1812 
1813       // Check that we don't have same operands. No need to reorder if operands
1814       // are just perfect diamond or shuffled diamond match. Do not do it only
1815       // for possible broadcasts or non-power of 2 number of scalars (just for
1816       // now).
1817       auto &&SkipReordering = [this]() {
1818         SmallPtrSet<Value *, 4> UniqueValues;
1819         ArrayRef<OperandData> Op0 = OpsVec.front();
1820         for (const OperandData &Data : Op0)
1821           UniqueValues.insert(Data.V);
1822         for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
1823           if (any_of(Op, [&UniqueValues](const OperandData &Data) {
1824                 return !UniqueValues.contains(Data.V);
1825               }))
1826             return false;
1827         }
1828         // TODO: Check if we can remove a check for non-power-2 number of
1829         // scalars after full support of non-power-2 vectorization.
1830         return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
1831       };
1832 
1833       // If the initial strategy fails for any of the operand indexes, then we
1834       // perform reordering again in a second pass. This helps avoid assigning
1835       // high priority to the failed strategy, and should improve reordering for
1836       // the non-failed operand indexes.
1837       for (int Pass = 0; Pass != 2; ++Pass) {
1838         // Check if no need to reorder operands since they're are perfect or
1839         // shuffled diamond match.
1840         // Need to to do it to avoid extra external use cost counting for
1841         // shuffled matches, which may cause regressions.
1842         if (SkipReordering())
1843           break;
1844         // Skip the second pass if the first pass did not fail.
1845         bool StrategyFailed = false;
1846         // Mark all operand data as free to use.
1847         clearUsed();
1848         // We keep the original operand order for the FirstLane, so reorder the
1849         // rest of the lanes. We are visiting the nodes in a circular fashion,
1850         // using FirstLane as the center point and increasing the radius
1851         // distance.
1852         SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
1853         for (unsigned I = 0; I < NumOperands; ++I)
1854           MainAltOps[I].push_back(getData(I, FirstLane).V);
1855 
1856         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1857           // Visit the lane on the right and then the lane on the left.
1858           for (int Direction : {+1, -1}) {
1859             int Lane = FirstLane + Direction * Distance;
1860             if (Lane < 0 || Lane >= (int)NumLanes)
1861               continue;
1862             int LastLane = Lane - Direction;
1863             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1864                    "Out of bounds");
1865             // Look for a good match for each operand.
1866             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1867               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1868               Optional<unsigned> BestIdx = getBestOperand(
1869                   OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
1870               // By not selecting a value, we allow the operands that follow to
1871               // select a better matching value. We will get a non-null value in
1872               // the next run of getBestOperand().
1873               if (BestIdx) {
1874                 // Swap the current operand with the one returned by
1875                 // getBestOperand().
1876                 swap(OpIdx, BestIdx.getValue(), Lane);
1877               } else {
1878                 // We failed to find a best operand, set mode to 'Failed'.
1879                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1880                 // Enable the second pass.
1881                 StrategyFailed = true;
1882               }
1883               // Try to get the alternate opcode and follow it during analysis.
1884               if (MainAltOps[OpIdx].size() != 2) {
1885                 OperandData &AltOp = getData(OpIdx, Lane);
1886                 InstructionsState OpS =
1887                     getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V});
1888                 if (OpS.getOpcode() && OpS.isAltShuffle())
1889                   MainAltOps[OpIdx].push_back(AltOp.V);
1890               }
1891             }
1892           }
1893         }
1894         // Skip second pass if the strategy did not fail.
1895         if (!StrategyFailed)
1896           break;
1897       }
1898     }
1899 
1900 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1901     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1902       switch (RMode) {
1903       case ReorderingMode::Load:
1904         return "Load";
1905       case ReorderingMode::Opcode:
1906         return "Opcode";
1907       case ReorderingMode::Constant:
1908         return "Constant";
1909       case ReorderingMode::Splat:
1910         return "Splat";
1911       case ReorderingMode::Failed:
1912         return "Failed";
1913       }
1914       llvm_unreachable("Unimplemented Reordering Type");
1915     }
1916 
1917     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1918                                                    raw_ostream &OS) {
1919       return OS << getModeStr(RMode);
1920     }
1921 
1922     /// Debug print.
1923     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1924       printMode(RMode, dbgs());
1925     }
1926 
1927     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1928       return printMode(RMode, OS);
1929     }
1930 
1931     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1932       const unsigned Indent = 2;
1933       unsigned Cnt = 0;
1934       for (const OperandDataVec &OpDataVec : OpsVec) {
1935         OS << "Operand " << Cnt++ << "\n";
1936         for (const OperandData &OpData : OpDataVec) {
1937           OS.indent(Indent) << "{";
1938           if (Value *V = OpData.V)
1939             OS << *V;
1940           else
1941             OS << "null";
1942           OS << ", APO:" << OpData.APO << "}\n";
1943         }
1944         OS << "\n";
1945       }
1946       return OS;
1947     }
1948 
1949     /// Debug print.
1950     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1951 #endif
1952   };
1953 
1954   /// Checks if the instruction is marked for deletion.
1955   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1956 
1957   /// Marks values operands for later deletion by replacing them with Undefs.
1958   void eraseInstructions(ArrayRef<Value *> AV);
1959 
1960   ~BoUpSLP();
1961 
1962 private:
1963   /// Check if the operands on the edges \p Edges of the \p UserTE allows
1964   /// reordering (i.e. the operands can be reordered because they have only one
1965   /// user and reordarable).
1966   /// \param NonVectorized List of all gather nodes that require reordering
1967   /// (e.g., gather of extractlements or partially vectorizable loads).
1968   /// \param GatherOps List of gather operand nodes for \p UserTE that require
1969   /// reordering, subset of \p NonVectorized.
1970   bool
1971   canReorderOperands(TreeEntry *UserTE,
1972                      SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
1973                      ArrayRef<TreeEntry *> ReorderableGathers,
1974                      SmallVectorImpl<TreeEntry *> &GatherOps);
1975 
1976   /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
1977   /// if any. If it is not vectorized (gather node), returns nullptr.
1978   TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
1979     ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
1980     TreeEntry *TE = nullptr;
1981     const auto *It = find_if(VL, [this, &TE](Value *V) {
1982       TE = getTreeEntry(V);
1983       return TE;
1984     });
1985     if (It != VL.end() && TE->isSame(VL))
1986       return TE;
1987     return nullptr;
1988   }
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   const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
1993                                         unsigned OpIdx) const {
1994     return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
1995         const_cast<TreeEntry *>(UserTE), OpIdx);
1996   }
1997 
1998   /// Checks if all users of \p I are the part of the vectorization tree.
1999   bool areAllUsersVectorized(Instruction *I,
2000                              ArrayRef<Value *> VectorizedVals) const;
2001 
2002   /// \returns the cost of the vectorizable entry.
2003   InstructionCost getEntryCost(const TreeEntry *E,
2004                                ArrayRef<Value *> VectorizedVals);
2005 
2006   /// This is the recursive part of buildTree.
2007   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2008                      const EdgeInfo &EI);
2009 
2010   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2011   /// be vectorized to use the original vector (or aggregate "bitcast" to a
2012   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2013   /// returns false, setting \p CurrentOrder to either an empty vector or a
2014   /// non-identity permutation that allows to reuse extract instructions.
2015   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2016                        SmallVectorImpl<unsigned> &CurrentOrder) const;
2017 
2018   /// Vectorize a single entry in the tree.
2019   Value *vectorizeTree(TreeEntry *E);
2020 
2021   /// Vectorize a single entry in the tree, starting in \p VL.
2022   Value *vectorizeTree(ArrayRef<Value *> VL);
2023 
2024   /// Create a new vector from a list of scalar values.  Produces a sequence
2025   /// which exploits values reused across lanes, and arranges the inserts
2026   /// for ease of later optimization.
2027   Value *createBuildVector(ArrayRef<Value *> VL);
2028 
2029   /// \returns the scalarization cost for this type. Scalarization in this
2030   /// context means the creation of vectors from a group of scalars. If \p
2031   /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2032   /// vector elements.
2033   InstructionCost getGatherCost(FixedVectorType *Ty,
2034                                 const APInt &ShuffledIndices,
2035                                 bool NeedToShuffle) const;
2036 
2037   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2038   /// tree entries.
2039   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2040   /// previous tree entries. \p Mask is filled with the shuffle mask.
2041   Optional<TargetTransformInfo::ShuffleKind>
2042   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
2043                         SmallVectorImpl<const TreeEntry *> &Entries);
2044 
2045   /// \returns the scalarization cost for this list of values. Assuming that
2046   /// this subtree gets vectorized, we may need to extract the values from the
2047   /// roots. This method calculates the cost of extracting the values.
2048   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2049 
2050   /// Set the Builder insert point to one after the last instruction in
2051   /// the bundle
2052   void setInsertPointAfterBundle(const TreeEntry *E);
2053 
2054   /// \returns a vector from a collection of scalars in \p VL.
2055   Value *gather(ArrayRef<Value *> VL);
2056 
2057   /// \returns whether the VectorizableTree is fully vectorizable and will
2058   /// be beneficial even the tree height is tiny.
2059   bool isFullyVectorizableTinyTree(bool ForReduction) const;
2060 
2061   /// Reorder commutative or alt operands to get better probability of
2062   /// generating vectorized code.
2063   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
2064                                              SmallVectorImpl<Value *> &Left,
2065                                              SmallVectorImpl<Value *> &Right,
2066                                              const DataLayout &DL,
2067                                              ScalarEvolution &SE,
2068                                              const BoUpSLP &R);
2069   struct TreeEntry {
2070     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2071     TreeEntry(VecTreeTy &Container) : Container(Container) {}
2072 
2073     /// \returns true if the scalars in VL are equal to this entry.
2074     bool isSame(ArrayRef<Value *> VL) const {
2075       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2076         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2077           return std::equal(VL.begin(), VL.end(), Scalars.begin());
2078         return VL.size() == Mask.size() &&
2079                std::equal(VL.begin(), VL.end(), Mask.begin(),
2080                           [Scalars](Value *V, int Idx) {
2081                             return (isa<UndefValue>(V) &&
2082                                     Idx == UndefMaskElem) ||
2083                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
2084                           });
2085       };
2086       if (!ReorderIndices.empty()) {
2087         // TODO: implement matching if the nodes are just reordered, still can
2088         // treat the vector as the same if the list of scalars matches VL
2089         // directly, without reordering.
2090         SmallVector<int> Mask;
2091         inversePermutation(ReorderIndices, Mask);
2092         if (VL.size() == Scalars.size())
2093           return IsSame(Scalars, Mask);
2094         if (VL.size() == ReuseShuffleIndices.size()) {
2095           ::addMask(Mask, ReuseShuffleIndices);
2096           return IsSame(Scalars, Mask);
2097         }
2098         return false;
2099       }
2100       return IsSame(Scalars, ReuseShuffleIndices);
2101     }
2102 
2103     /// \returns true if current entry has same operands as \p TE.
2104     bool hasEqualOperands(const TreeEntry &TE) const {
2105       if (TE.getNumOperands() != getNumOperands())
2106         return false;
2107       SmallBitVector Used(getNumOperands());
2108       for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2109         unsigned PrevCount = Used.count();
2110         for (unsigned K = 0; K < E; ++K) {
2111           if (Used.test(K))
2112             continue;
2113           if (getOperand(K) == TE.getOperand(I)) {
2114             Used.set(K);
2115             break;
2116           }
2117         }
2118         // Check if we actually found the matching operand.
2119         if (PrevCount == Used.count())
2120           return false;
2121       }
2122       return true;
2123     }
2124 
2125     /// \return Final vectorization factor for the node. Defined by the total
2126     /// number of vectorized scalars, including those, used several times in the
2127     /// entry and counted in the \a ReuseShuffleIndices, if any.
2128     unsigned getVectorFactor() const {
2129       if (!ReuseShuffleIndices.empty())
2130         return ReuseShuffleIndices.size();
2131       return Scalars.size();
2132     };
2133 
2134     /// A vector of scalars.
2135     ValueList Scalars;
2136 
2137     /// The Scalars are vectorized into this value. It is initialized to Null.
2138     Value *VectorizedValue = nullptr;
2139 
2140     /// Do we need to gather this sequence or vectorize it
2141     /// (either with vector instruction or with scatter/gather
2142     /// intrinsics for store/load)?
2143     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2144     EntryState State;
2145 
2146     /// Does this sequence require some shuffling?
2147     SmallVector<int, 4> ReuseShuffleIndices;
2148 
2149     /// Does this entry require reordering?
2150     SmallVector<unsigned, 4> ReorderIndices;
2151 
2152     /// Points back to the VectorizableTree.
2153     ///
2154     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
2155     /// to be a pointer and needs to be able to initialize the child iterator.
2156     /// Thus we need a reference back to the container to translate the indices
2157     /// to entries.
2158     VecTreeTy &Container;
2159 
2160     /// The TreeEntry index containing the user of this entry.  We can actually
2161     /// have multiple users so the data structure is not truly a tree.
2162     SmallVector<EdgeInfo, 1> UserTreeIndices;
2163 
2164     /// The index of this treeEntry in VectorizableTree.
2165     int Idx = -1;
2166 
2167   private:
2168     /// The operands of each instruction in each lane Operands[op_index][lane].
2169     /// Note: This helps avoid the replication of the code that performs the
2170     /// reordering of operands during buildTree_rec() and vectorizeTree().
2171     SmallVector<ValueList, 2> Operands;
2172 
2173     /// The main/alternate instruction.
2174     Instruction *MainOp = nullptr;
2175     Instruction *AltOp = nullptr;
2176 
2177   public:
2178     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2179     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2180       if (Operands.size() < OpIdx + 1)
2181         Operands.resize(OpIdx + 1);
2182       assert(Operands[OpIdx].empty() && "Already resized?");
2183       assert(OpVL.size() <= Scalars.size() &&
2184              "Number of operands is greater than the number of scalars.");
2185       Operands[OpIdx].resize(OpVL.size());
2186       copy(OpVL, Operands[OpIdx].begin());
2187     }
2188 
2189     /// Set the operands of this bundle in their original order.
2190     void setOperandsInOrder() {
2191       assert(Operands.empty() && "Already initialized?");
2192       auto *I0 = cast<Instruction>(Scalars[0]);
2193       Operands.resize(I0->getNumOperands());
2194       unsigned NumLanes = Scalars.size();
2195       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2196            OpIdx != NumOperands; ++OpIdx) {
2197         Operands[OpIdx].resize(NumLanes);
2198         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2199           auto *I = cast<Instruction>(Scalars[Lane]);
2200           assert(I->getNumOperands() == NumOperands &&
2201                  "Expected same number of operands");
2202           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2203         }
2204       }
2205     }
2206 
2207     /// Reorders operands of the node to the given mask \p Mask.
2208     void reorderOperands(ArrayRef<int> Mask) {
2209       for (ValueList &Operand : Operands)
2210         reorderScalars(Operand, Mask);
2211     }
2212 
2213     /// \returns the \p OpIdx operand of this TreeEntry.
2214     ValueList &getOperand(unsigned OpIdx) {
2215       assert(OpIdx < Operands.size() && "Off bounds");
2216       return Operands[OpIdx];
2217     }
2218 
2219     /// \returns the \p OpIdx operand of this TreeEntry.
2220     ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2221       assert(OpIdx < Operands.size() && "Off bounds");
2222       return Operands[OpIdx];
2223     }
2224 
2225     /// \returns the number of operands.
2226     unsigned getNumOperands() const { return Operands.size(); }
2227 
2228     /// \return the single \p OpIdx operand.
2229     Value *getSingleOperand(unsigned OpIdx) const {
2230       assert(OpIdx < Operands.size() && "Off bounds");
2231       assert(!Operands[OpIdx].empty() && "No operand available");
2232       return Operands[OpIdx][0];
2233     }
2234 
2235     /// Some of the instructions in the list have alternate opcodes.
2236     bool isAltShuffle() const { return MainOp != AltOp; }
2237 
2238     bool isOpcodeOrAlt(Instruction *I) const {
2239       unsigned CheckedOpcode = I->getOpcode();
2240       return (getOpcode() == CheckedOpcode ||
2241               getAltOpcode() == CheckedOpcode);
2242     }
2243 
2244     /// Chooses the correct key for scheduling data. If \p Op has the same (or
2245     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2246     /// \p OpValue.
2247     Value *isOneOf(Value *Op) const {
2248       auto *I = dyn_cast<Instruction>(Op);
2249       if (I && isOpcodeOrAlt(I))
2250         return Op;
2251       return MainOp;
2252     }
2253 
2254     void setOperations(const InstructionsState &S) {
2255       MainOp = S.MainOp;
2256       AltOp = S.AltOp;
2257     }
2258 
2259     Instruction *getMainOp() const {
2260       return MainOp;
2261     }
2262 
2263     Instruction *getAltOp() const {
2264       return AltOp;
2265     }
2266 
2267     /// The main/alternate opcodes for the list of instructions.
2268     unsigned getOpcode() const {
2269       return MainOp ? MainOp->getOpcode() : 0;
2270     }
2271 
2272     unsigned getAltOpcode() const {
2273       return AltOp ? AltOp->getOpcode() : 0;
2274     }
2275 
2276     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2277     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2278     int findLaneForValue(Value *V) const {
2279       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2280       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2281       if (!ReorderIndices.empty())
2282         FoundLane = ReorderIndices[FoundLane];
2283       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2284       if (!ReuseShuffleIndices.empty()) {
2285         FoundLane = std::distance(ReuseShuffleIndices.begin(),
2286                                   find(ReuseShuffleIndices, FoundLane));
2287       }
2288       return FoundLane;
2289     }
2290 
2291 #ifndef NDEBUG
2292     /// Debug printer.
2293     LLVM_DUMP_METHOD void dump() const {
2294       dbgs() << Idx << ".\n";
2295       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2296         dbgs() << "Operand " << OpI << ":\n";
2297         for (const Value *V : Operands[OpI])
2298           dbgs().indent(2) << *V << "\n";
2299       }
2300       dbgs() << "Scalars: \n";
2301       for (Value *V : Scalars)
2302         dbgs().indent(2) << *V << "\n";
2303       dbgs() << "State: ";
2304       switch (State) {
2305       case Vectorize:
2306         dbgs() << "Vectorize\n";
2307         break;
2308       case ScatterVectorize:
2309         dbgs() << "ScatterVectorize\n";
2310         break;
2311       case NeedToGather:
2312         dbgs() << "NeedToGather\n";
2313         break;
2314       }
2315       dbgs() << "MainOp: ";
2316       if (MainOp)
2317         dbgs() << *MainOp << "\n";
2318       else
2319         dbgs() << "NULL\n";
2320       dbgs() << "AltOp: ";
2321       if (AltOp)
2322         dbgs() << *AltOp << "\n";
2323       else
2324         dbgs() << "NULL\n";
2325       dbgs() << "VectorizedValue: ";
2326       if (VectorizedValue)
2327         dbgs() << *VectorizedValue << "\n";
2328       else
2329         dbgs() << "NULL\n";
2330       dbgs() << "ReuseShuffleIndices: ";
2331       if (ReuseShuffleIndices.empty())
2332         dbgs() << "Empty";
2333       else
2334         for (int ReuseIdx : ReuseShuffleIndices)
2335           dbgs() << ReuseIdx << ", ";
2336       dbgs() << "\n";
2337       dbgs() << "ReorderIndices: ";
2338       for (unsigned ReorderIdx : ReorderIndices)
2339         dbgs() << ReorderIdx << ", ";
2340       dbgs() << "\n";
2341       dbgs() << "UserTreeIndices: ";
2342       for (const auto &EInfo : UserTreeIndices)
2343         dbgs() << EInfo << ", ";
2344       dbgs() << "\n";
2345     }
2346 #endif
2347   };
2348 
2349 #ifndef NDEBUG
2350   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2351                      InstructionCost VecCost,
2352                      InstructionCost ScalarCost) const {
2353     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2354     dbgs() << "SLP: Costs:\n";
2355     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2356     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
2357     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
2358     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
2359                ReuseShuffleCost + VecCost - ScalarCost << "\n";
2360   }
2361 #endif
2362 
2363   /// Create a new VectorizableTree entry.
2364   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
2365                           const InstructionsState &S,
2366                           const EdgeInfo &UserTreeIdx,
2367                           ArrayRef<int> ReuseShuffleIndices = None,
2368                           ArrayRef<unsigned> ReorderIndices = None) {
2369     TreeEntry::EntryState EntryState =
2370         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2371     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2372                         ReuseShuffleIndices, ReorderIndices);
2373   }
2374 
2375   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2376                           TreeEntry::EntryState EntryState,
2377                           Optional<ScheduleData *> Bundle,
2378                           const InstructionsState &S,
2379                           const EdgeInfo &UserTreeIdx,
2380                           ArrayRef<int> ReuseShuffleIndices = None,
2381                           ArrayRef<unsigned> ReorderIndices = None) {
2382     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2383             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2384            "Need to vectorize gather entry?");
2385     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2386     TreeEntry *Last = VectorizableTree.back().get();
2387     Last->Idx = VectorizableTree.size() - 1;
2388     Last->State = EntryState;
2389     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2390                                      ReuseShuffleIndices.end());
2391     if (ReorderIndices.empty()) {
2392       Last->Scalars.assign(VL.begin(), VL.end());
2393       Last->setOperations(S);
2394     } else {
2395       // Reorder scalars and build final mask.
2396       Last->Scalars.assign(VL.size(), nullptr);
2397       transform(ReorderIndices, Last->Scalars.begin(),
2398                 [VL](unsigned Idx) -> Value * {
2399                   if (Idx >= VL.size())
2400                     return UndefValue::get(VL.front()->getType());
2401                   return VL[Idx];
2402                 });
2403       InstructionsState S = getSameOpcode(Last->Scalars);
2404       Last->setOperations(S);
2405       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2406     }
2407     if (Last->State != TreeEntry::NeedToGather) {
2408       for (Value *V : VL) {
2409         assert(!getTreeEntry(V) && "Scalar already in tree!");
2410         ScalarToTreeEntry[V] = Last;
2411       }
2412       // Update the scheduler bundle to point to this TreeEntry.
2413       ScheduleData *BundleMember = Bundle.getValue();
2414       assert((BundleMember || isa<PHINode>(S.MainOp) ||
2415               isVectorLikeInstWithConstOps(S.MainOp) ||
2416               doesNotNeedToSchedule(VL)) &&
2417              "Bundle and VL out of sync");
2418       if (BundleMember) {
2419         for (Value *V : VL) {
2420           if (doesNotNeedToBeScheduled(V))
2421             continue;
2422           assert(BundleMember && "Unexpected end of bundle.");
2423           BundleMember->TE = Last;
2424           BundleMember = BundleMember->NextInBundle;
2425         }
2426       }
2427       assert(!BundleMember && "Bundle and VL out of sync");
2428     } else {
2429       MustGather.insert(VL.begin(), VL.end());
2430     }
2431 
2432     if (UserTreeIdx.UserTE)
2433       Last->UserTreeIndices.push_back(UserTreeIdx);
2434 
2435     return Last;
2436   }
2437 
2438   /// -- Vectorization State --
2439   /// Holds all of the tree entries.
2440   TreeEntry::VecTreeTy VectorizableTree;
2441 
2442 #ifndef NDEBUG
2443   /// Debug printer.
2444   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2445     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2446       VectorizableTree[Id]->dump();
2447       dbgs() << "\n";
2448     }
2449   }
2450 #endif
2451 
2452   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2453 
2454   const TreeEntry *getTreeEntry(Value *V) const {
2455     return ScalarToTreeEntry.lookup(V);
2456   }
2457 
2458   /// Maps a specific scalar to its tree entry.
2459   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2460 
2461   /// Maps a value to the proposed vectorizable size.
2462   SmallDenseMap<Value *, unsigned> InstrElementSize;
2463 
2464   /// A list of scalars that we found that we need to keep as scalars.
2465   ValueSet MustGather;
2466 
2467   /// This POD struct describes one external user in the vectorized tree.
2468   struct ExternalUser {
2469     ExternalUser(Value *S, llvm::User *U, int L)
2470         : Scalar(S), User(U), Lane(L) {}
2471 
2472     // Which scalar in our function.
2473     Value *Scalar;
2474 
2475     // Which user that uses the scalar.
2476     llvm::User *User;
2477 
2478     // Which lane does the scalar belong to.
2479     int Lane;
2480   };
2481   using UserList = SmallVector<ExternalUser, 16>;
2482 
2483   /// Checks if two instructions may access the same memory.
2484   ///
2485   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2486   /// is invariant in the calling loop.
2487   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2488                  Instruction *Inst2) {
2489     // First check if the result is already in the cache.
2490     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2491     Optional<bool> &result = AliasCache[key];
2492     if (result.hasValue()) {
2493       return result.getValue();
2494     }
2495     bool aliased = true;
2496     if (Loc1.Ptr && isSimple(Inst1))
2497       aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2498     // Store the result in the cache.
2499     result = aliased;
2500     return aliased;
2501   }
2502 
2503   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2504 
2505   /// Cache for alias results.
2506   /// TODO: consider moving this to the AliasAnalysis itself.
2507   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2508 
2509   // Cache for pointerMayBeCaptured calls inside AA.  This is preserved
2510   // globally through SLP because we don't perform any action which
2511   // invalidates capture results.
2512   BatchAAResults BatchAA;
2513 
2514   /// Removes an instruction from its block and eventually deletes it.
2515   /// It's like Instruction::eraseFromParent() except that the actual deletion
2516   /// is delayed until BoUpSLP is destructed.
2517   /// This is required to ensure that there are no incorrect collisions in the
2518   /// AliasCache, which can happen if a new instruction is allocated at the
2519   /// same address as a previously deleted instruction.
2520   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2521     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2522     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2523   }
2524 
2525   /// Temporary store for deleted instructions. Instructions will be deleted
2526   /// eventually when the BoUpSLP is destructed.
2527   DenseMap<Instruction *, bool> DeletedInstructions;
2528 
2529   /// A list of values that need to extracted out of the tree.
2530   /// This list holds pairs of (Internal Scalar : External User). External User
2531   /// can be nullptr, it means that this Internal Scalar will be used later,
2532   /// after vectorization.
2533   UserList ExternalUses;
2534 
2535   /// Values used only by @llvm.assume calls.
2536   SmallPtrSet<const Value *, 32> EphValues;
2537 
2538   /// Holds all of the instructions that we gathered.
2539   SetVector<Instruction *> GatherShuffleSeq;
2540 
2541   /// A list of blocks that we are going to CSE.
2542   SetVector<BasicBlock *> CSEBlocks;
2543 
2544   /// Contains all scheduling relevant data for an instruction.
2545   /// A ScheduleData either represents a single instruction or a member of an
2546   /// instruction bundle (= a group of instructions which is combined into a
2547   /// vector instruction).
2548   struct ScheduleData {
2549     // The initial value for the dependency counters. It means that the
2550     // dependencies are not calculated yet.
2551     enum { InvalidDeps = -1 };
2552 
2553     ScheduleData() = default;
2554 
2555     void init(int BlockSchedulingRegionID, Value *OpVal) {
2556       FirstInBundle = this;
2557       NextInBundle = nullptr;
2558       NextLoadStore = nullptr;
2559       IsScheduled = false;
2560       SchedulingRegionID = BlockSchedulingRegionID;
2561       clearDependencies();
2562       OpValue = OpVal;
2563       TE = nullptr;
2564     }
2565 
2566     /// Verify basic self consistency properties
2567     void verify() {
2568       if (hasValidDependencies()) {
2569         assert(UnscheduledDeps <= Dependencies && "invariant");
2570       } else {
2571         assert(UnscheduledDeps == Dependencies && "invariant");
2572       }
2573 
2574       if (IsScheduled) {
2575         assert(isSchedulingEntity() &&
2576                 "unexpected scheduled state");
2577         for (const ScheduleData *BundleMember = this; BundleMember;
2578              BundleMember = BundleMember->NextInBundle) {
2579           assert(BundleMember->hasValidDependencies() &&
2580                  BundleMember->UnscheduledDeps == 0 &&
2581                  "unexpected scheduled state");
2582           assert((BundleMember == this || !BundleMember->IsScheduled) &&
2583                  "only bundle is marked scheduled");
2584         }
2585       }
2586 
2587       assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2588              "all bundle members must be in same basic block");
2589     }
2590 
2591     /// Returns true if the dependency information has been calculated.
2592     /// Note that depenendency validity can vary between instructions within
2593     /// a single bundle.
2594     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2595 
2596     /// Returns true for single instructions and for bundle representatives
2597     /// (= the head of a bundle).
2598     bool isSchedulingEntity() const { return FirstInBundle == this; }
2599 
2600     /// Returns true if it represents an instruction bundle and not only a
2601     /// single instruction.
2602     bool isPartOfBundle() const {
2603       return NextInBundle != nullptr || FirstInBundle != this || TE;
2604     }
2605 
2606     /// Returns true if it is ready for scheduling, i.e. it has no more
2607     /// unscheduled depending instructions/bundles.
2608     bool isReady() const {
2609       assert(isSchedulingEntity() &&
2610              "can't consider non-scheduling entity for ready list");
2611       return unscheduledDepsInBundle() == 0 && !IsScheduled;
2612     }
2613 
2614     /// Modifies the number of unscheduled dependencies for this instruction,
2615     /// and returns the number of remaining dependencies for the containing
2616     /// bundle.
2617     int incrementUnscheduledDeps(int Incr) {
2618       assert(hasValidDependencies() &&
2619              "increment of unscheduled deps would be meaningless");
2620       UnscheduledDeps += Incr;
2621       return FirstInBundle->unscheduledDepsInBundle();
2622     }
2623 
2624     /// Sets the number of unscheduled dependencies to the number of
2625     /// dependencies.
2626     void resetUnscheduledDeps() {
2627       UnscheduledDeps = Dependencies;
2628     }
2629 
2630     /// Clears all dependency information.
2631     void clearDependencies() {
2632       Dependencies = InvalidDeps;
2633       resetUnscheduledDeps();
2634       MemoryDependencies.clear();
2635     }
2636 
2637     int unscheduledDepsInBundle() const {
2638       assert(isSchedulingEntity() && "only meaningful on the bundle");
2639       int Sum = 0;
2640       for (const ScheduleData *BundleMember = this; BundleMember;
2641            BundleMember = BundleMember->NextInBundle) {
2642         if (BundleMember->UnscheduledDeps == InvalidDeps)
2643           return InvalidDeps;
2644         Sum += BundleMember->UnscheduledDeps;
2645       }
2646       return Sum;
2647     }
2648 
2649     void dump(raw_ostream &os) const {
2650       if (!isSchedulingEntity()) {
2651         os << "/ " << *Inst;
2652       } else if (NextInBundle) {
2653         os << '[' << *Inst;
2654         ScheduleData *SD = NextInBundle;
2655         while (SD) {
2656           os << ';' << *SD->Inst;
2657           SD = SD->NextInBundle;
2658         }
2659         os << ']';
2660       } else {
2661         os << *Inst;
2662       }
2663     }
2664 
2665     Instruction *Inst = nullptr;
2666 
2667     /// Opcode of the current instruction in the schedule data.
2668     Value *OpValue = nullptr;
2669 
2670     /// The TreeEntry that this instruction corresponds to.
2671     TreeEntry *TE = nullptr;
2672 
2673     /// Points to the head in an instruction bundle (and always to this for
2674     /// single instructions).
2675     ScheduleData *FirstInBundle = nullptr;
2676 
2677     /// Single linked list of all instructions in a bundle. Null if it is a
2678     /// single instruction.
2679     ScheduleData *NextInBundle = nullptr;
2680 
2681     /// Single linked list of all memory instructions (e.g. load, store, call)
2682     /// in the block - until the end of the scheduling region.
2683     ScheduleData *NextLoadStore = nullptr;
2684 
2685     /// The dependent memory instructions.
2686     /// This list is derived on demand in calculateDependencies().
2687     SmallVector<ScheduleData *, 4> MemoryDependencies;
2688 
2689     /// This ScheduleData is in the current scheduling region if this matches
2690     /// the current SchedulingRegionID of BlockScheduling.
2691     int SchedulingRegionID = 0;
2692 
2693     /// Used for getting a "good" final ordering of instructions.
2694     int SchedulingPriority = 0;
2695 
2696     /// The number of dependencies. Constitutes of the number of users of the
2697     /// instruction plus the number of dependent memory instructions (if any).
2698     /// This value is calculated on demand.
2699     /// If InvalidDeps, the number of dependencies is not calculated yet.
2700     int Dependencies = InvalidDeps;
2701 
2702     /// The number of dependencies minus the number of dependencies of scheduled
2703     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2704     /// for scheduling.
2705     /// Note that this is negative as long as Dependencies is not calculated.
2706     int UnscheduledDeps = InvalidDeps;
2707 
2708     /// True if this instruction is scheduled (or considered as scheduled in the
2709     /// dry-run).
2710     bool IsScheduled = false;
2711   };
2712 
2713 #ifndef NDEBUG
2714   friend inline raw_ostream &operator<<(raw_ostream &os,
2715                                         const BoUpSLP::ScheduleData &SD) {
2716     SD.dump(os);
2717     return os;
2718   }
2719 #endif
2720 
2721   friend struct GraphTraits<BoUpSLP *>;
2722   friend struct DOTGraphTraits<BoUpSLP *>;
2723 
2724   /// Contains all scheduling data for a basic block.
2725   /// It does not schedules instructions, which are not memory read/write
2726   /// instructions and their operands are either constants, or arguments, or
2727   /// phis, or instructions from others blocks, or their users are phis or from
2728   /// the other blocks. The resulting vector instructions can be placed at the
2729   /// beginning of the basic block without scheduling (if operands does not need
2730   /// to be scheduled) or at the end of the block (if users are outside of the
2731   /// block). It allows to save some compile time and memory used by the
2732   /// compiler.
2733   /// ScheduleData is assigned for each instruction in between the boundaries of
2734   /// the tree entry, even for those, which are not part of the graph. It is
2735   /// required to correctly follow the dependencies between the instructions and
2736   /// their correct scheduling. The ScheduleData is not allocated for the
2737   /// instructions, which do not require scheduling, like phis, nodes with
2738   /// extractelements/insertelements only or nodes with instructions, with
2739   /// uses/operands outside of the block.
2740   struct BlockScheduling {
2741     BlockScheduling(BasicBlock *BB)
2742         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2743 
2744     void clear() {
2745       ReadyInsts.clear();
2746       ScheduleStart = nullptr;
2747       ScheduleEnd = nullptr;
2748       FirstLoadStoreInRegion = nullptr;
2749       LastLoadStoreInRegion = nullptr;
2750 
2751       // Reduce the maximum schedule region size by the size of the
2752       // previous scheduling run.
2753       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2754       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2755         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2756       ScheduleRegionSize = 0;
2757 
2758       // Make a new scheduling region, i.e. all existing ScheduleData is not
2759       // in the new region yet.
2760       ++SchedulingRegionID;
2761     }
2762 
2763     ScheduleData *getScheduleData(Instruction *I) {
2764       if (BB != I->getParent())
2765         // Avoid lookup if can't possibly be in map.
2766         return nullptr;
2767       ScheduleData *SD = ScheduleDataMap.lookup(I);
2768       if (SD && isInSchedulingRegion(SD))
2769         return SD;
2770       return nullptr;
2771     }
2772 
2773     ScheduleData *getScheduleData(Value *V) {
2774       if (auto *I = dyn_cast<Instruction>(V))
2775         return getScheduleData(I);
2776       return nullptr;
2777     }
2778 
2779     ScheduleData *getScheduleData(Value *V, Value *Key) {
2780       if (V == Key)
2781         return getScheduleData(V);
2782       auto I = ExtraScheduleDataMap.find(V);
2783       if (I != ExtraScheduleDataMap.end()) {
2784         ScheduleData *SD = I->second.lookup(Key);
2785         if (SD && isInSchedulingRegion(SD))
2786           return SD;
2787       }
2788       return nullptr;
2789     }
2790 
2791     bool isInSchedulingRegion(ScheduleData *SD) const {
2792       return SD->SchedulingRegionID == SchedulingRegionID;
2793     }
2794 
2795     /// Marks an instruction as scheduled and puts all dependent ready
2796     /// instructions into the ready-list.
2797     template <typename ReadyListType>
2798     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2799       SD->IsScheduled = true;
2800       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2801 
2802       for (ScheduleData *BundleMember = SD; BundleMember;
2803            BundleMember = BundleMember->NextInBundle) {
2804         if (BundleMember->Inst != BundleMember->OpValue)
2805           continue;
2806 
2807         // Handle the def-use chain dependencies.
2808 
2809         // Decrement the unscheduled counter and insert to ready list if ready.
2810         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2811           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2812             if (OpDef && OpDef->hasValidDependencies() &&
2813                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2814               // There are no more unscheduled dependencies after
2815               // decrementing, so we can put the dependent instruction
2816               // into the ready list.
2817               ScheduleData *DepBundle = OpDef->FirstInBundle;
2818               assert(!DepBundle->IsScheduled &&
2819                      "already scheduled bundle gets ready");
2820               ReadyList.insert(DepBundle);
2821               LLVM_DEBUG(dbgs()
2822                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2823             }
2824           });
2825         };
2826 
2827         // If BundleMember is a vector bundle, its operands may have been
2828         // reordered during buildTree(). We therefore need to get its operands
2829         // through the TreeEntry.
2830         if (TreeEntry *TE = BundleMember->TE) {
2831           // Need to search for the lane since the tree entry can be reordered.
2832           int Lane = std::distance(TE->Scalars.begin(),
2833                                    find(TE->Scalars, BundleMember->Inst));
2834           assert(Lane >= 0 && "Lane not set");
2835 
2836           // Since vectorization tree is being built recursively this assertion
2837           // ensures that the tree entry has all operands set before reaching
2838           // this code. Couple of exceptions known at the moment are extracts
2839           // where their second (immediate) operand is not added. Since
2840           // immediates do not affect scheduler behavior this is considered
2841           // okay.
2842           auto *In = BundleMember->Inst;
2843           assert(In &&
2844                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2845                   In->getNumOperands() == TE->getNumOperands()) &&
2846                  "Missed TreeEntry operands?");
2847           (void)In; // fake use to avoid build failure when assertions disabled
2848 
2849           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2850                OpIdx != NumOperands; ++OpIdx)
2851             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2852               DecrUnsched(I);
2853         } else {
2854           // If BundleMember is a stand-alone instruction, no operand reordering
2855           // has taken place, so we directly access its operands.
2856           for (Use &U : BundleMember->Inst->operands())
2857             if (auto *I = dyn_cast<Instruction>(U.get()))
2858               DecrUnsched(I);
2859         }
2860         // Handle the memory dependencies.
2861         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2862           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2863             // There are no more unscheduled dependencies after decrementing,
2864             // so we can put the dependent instruction into the ready list.
2865             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2866             assert(!DepBundle->IsScheduled &&
2867                    "already scheduled bundle gets ready");
2868             ReadyList.insert(DepBundle);
2869             LLVM_DEBUG(dbgs()
2870                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2871           }
2872         }
2873       }
2874     }
2875 
2876     /// Verify basic self consistency properties of the data structure.
2877     void verify() {
2878       if (!ScheduleStart)
2879         return;
2880 
2881       assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
2882              ScheduleStart->comesBefore(ScheduleEnd) &&
2883              "Not a valid scheduling region?");
2884 
2885       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2886         auto *SD = getScheduleData(I);
2887         if (!SD)
2888           continue;
2889         assert(isInSchedulingRegion(SD) &&
2890                "primary schedule data not in window?");
2891         assert(isInSchedulingRegion(SD->FirstInBundle) &&
2892                "entire bundle in window!");
2893         (void)SD;
2894         doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
2895       }
2896 
2897       for (auto *SD : ReadyInsts) {
2898         assert(SD->isSchedulingEntity() && SD->isReady() &&
2899                "item in ready list not ready?");
2900         (void)SD;
2901       }
2902     }
2903 
2904     void doForAllOpcodes(Value *V,
2905                          function_ref<void(ScheduleData *SD)> Action) {
2906       if (ScheduleData *SD = getScheduleData(V))
2907         Action(SD);
2908       auto I = ExtraScheduleDataMap.find(V);
2909       if (I != ExtraScheduleDataMap.end())
2910         for (auto &P : I->second)
2911           if (isInSchedulingRegion(P.second))
2912             Action(P.second);
2913     }
2914 
2915     /// Put all instructions into the ReadyList which are ready for scheduling.
2916     template <typename ReadyListType>
2917     void initialFillReadyList(ReadyListType &ReadyList) {
2918       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2919         doForAllOpcodes(I, [&](ScheduleData *SD) {
2920           if (SD->isSchedulingEntity() && SD->isReady()) {
2921             ReadyList.insert(SD);
2922             LLVM_DEBUG(dbgs()
2923                        << "SLP:    initially in ready list: " << *SD << "\n");
2924           }
2925         });
2926       }
2927     }
2928 
2929     /// Build a bundle from the ScheduleData nodes corresponding to the
2930     /// scalar instruction for each lane.
2931     ScheduleData *buildBundle(ArrayRef<Value *> VL);
2932 
2933     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2934     /// cyclic dependencies. This is only a dry-run, no instructions are
2935     /// actually moved at this stage.
2936     /// \returns the scheduling bundle. The returned Optional value is non-None
2937     /// if \p VL is allowed to be scheduled.
2938     Optional<ScheduleData *>
2939     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2940                       const InstructionsState &S);
2941 
2942     /// Un-bundles a group of instructions.
2943     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2944 
2945     /// Allocates schedule data chunk.
2946     ScheduleData *allocateScheduleDataChunks();
2947 
2948     /// Extends the scheduling region so that V is inside the region.
2949     /// \returns true if the region size is within the limit.
2950     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2951 
2952     /// Initialize the ScheduleData structures for new instructions in the
2953     /// scheduling region.
2954     void initScheduleData(Instruction *FromI, Instruction *ToI,
2955                           ScheduleData *PrevLoadStore,
2956                           ScheduleData *NextLoadStore);
2957 
2958     /// Updates the dependency information of a bundle and of all instructions/
2959     /// bundles which depend on the original bundle.
2960     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2961                                BoUpSLP *SLP);
2962 
2963     /// Sets all instruction in the scheduling region to un-scheduled.
2964     void resetSchedule();
2965 
2966     BasicBlock *BB;
2967 
2968     /// Simple memory allocation for ScheduleData.
2969     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2970 
2971     /// The size of a ScheduleData array in ScheduleDataChunks.
2972     int ChunkSize;
2973 
2974     /// The allocator position in the current chunk, which is the last entry
2975     /// of ScheduleDataChunks.
2976     int ChunkPos;
2977 
2978     /// Attaches ScheduleData to Instruction.
2979     /// Note that the mapping survives during all vectorization iterations, i.e.
2980     /// ScheduleData structures are recycled.
2981     DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
2982 
2983     /// Attaches ScheduleData to Instruction with the leading key.
2984     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2985         ExtraScheduleDataMap;
2986 
2987     /// The ready-list for scheduling (only used for the dry-run).
2988     SetVector<ScheduleData *> ReadyInsts;
2989 
2990     /// The first instruction of the scheduling region.
2991     Instruction *ScheduleStart = nullptr;
2992 
2993     /// The first instruction _after_ the scheduling region.
2994     Instruction *ScheduleEnd = nullptr;
2995 
2996     /// The first memory accessing instruction in the scheduling region
2997     /// (can be null).
2998     ScheduleData *FirstLoadStoreInRegion = nullptr;
2999 
3000     /// The last memory accessing instruction in the scheduling region
3001     /// (can be null).
3002     ScheduleData *LastLoadStoreInRegion = nullptr;
3003 
3004     /// The current size of the scheduling region.
3005     int ScheduleRegionSize = 0;
3006 
3007     /// The maximum size allowed for the scheduling region.
3008     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3009 
3010     /// The ID of the scheduling region. For a new vectorization iteration this
3011     /// is incremented which "removes" all ScheduleData from the region.
3012     /// Make sure that the initial SchedulingRegionID is greater than the
3013     /// initial SchedulingRegionID in ScheduleData (which is 0).
3014     int SchedulingRegionID = 1;
3015   };
3016 
3017   /// Attaches the BlockScheduling structures to basic blocks.
3018   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
3019 
3020   /// Performs the "real" scheduling. Done before vectorization is actually
3021   /// performed in a basic block.
3022   void scheduleBlock(BlockScheduling *BS);
3023 
3024   /// List of users to ignore during scheduling and that don't need extracting.
3025   ArrayRef<Value *> UserIgnoreList;
3026 
3027   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3028   /// sorted SmallVectors of unsigned.
3029   struct OrdersTypeDenseMapInfo {
3030     static OrdersType getEmptyKey() {
3031       OrdersType V;
3032       V.push_back(~1U);
3033       return V;
3034     }
3035 
3036     static OrdersType getTombstoneKey() {
3037       OrdersType V;
3038       V.push_back(~2U);
3039       return V;
3040     }
3041 
3042     static unsigned getHashValue(const OrdersType &V) {
3043       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3044     }
3045 
3046     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3047       return LHS == RHS;
3048     }
3049   };
3050 
3051   // Analysis and block reference.
3052   Function *F;
3053   ScalarEvolution *SE;
3054   TargetTransformInfo *TTI;
3055   TargetLibraryInfo *TLI;
3056   LoopInfo *LI;
3057   DominatorTree *DT;
3058   AssumptionCache *AC;
3059   DemandedBits *DB;
3060   MemorySSA *MSSA;
3061   const DataLayout *DL;
3062   OptimizationRemarkEmitter *ORE;
3063 
3064   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3065   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3066 
3067   /// Instruction builder to construct the vectorized tree.
3068   IRBuilder<> Builder;
3069 
3070   /// A map of scalar integer values to the smallest bit width with which they
3071   /// can legally be represented. The values map to (width, signed) pairs,
3072   /// where "width" indicates the minimum bit width and "signed" is True if the
3073   /// value must be signed-extended, rather than zero-extended, back to its
3074   /// original width.
3075   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
3076 };
3077 
3078 } // end namespace slpvectorizer
3079 
3080 template <> struct GraphTraits<BoUpSLP *> {
3081   using TreeEntry = BoUpSLP::TreeEntry;
3082 
3083   /// NodeRef has to be a pointer per the GraphWriter.
3084   using NodeRef = TreeEntry *;
3085 
3086   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
3087 
3088   /// Add the VectorizableTree to the index iterator to be able to return
3089   /// TreeEntry pointers.
3090   struct ChildIteratorType
3091       : public iterator_adaptor_base<
3092             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3093     ContainerTy &VectorizableTree;
3094 
3095     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
3096                       ContainerTy &VT)
3097         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3098 
3099     NodeRef operator*() { return I->UserTE; }
3100   };
3101 
3102   static NodeRef getEntryNode(BoUpSLP &R) {
3103     return R.VectorizableTree[0].get();
3104   }
3105 
3106   static ChildIteratorType child_begin(NodeRef N) {
3107     return {N->UserTreeIndices.begin(), N->Container};
3108   }
3109 
3110   static ChildIteratorType child_end(NodeRef N) {
3111     return {N->UserTreeIndices.end(), N->Container};
3112   }
3113 
3114   /// For the node iterator we just need to turn the TreeEntry iterator into a
3115   /// TreeEntry* iterator so that it dereferences to NodeRef.
3116   class nodes_iterator {
3117     using ItTy = ContainerTy::iterator;
3118     ItTy It;
3119 
3120   public:
3121     nodes_iterator(const ItTy &It2) : It(It2) {}
3122     NodeRef operator*() { return It->get(); }
3123     nodes_iterator operator++() {
3124       ++It;
3125       return *this;
3126     }
3127     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3128   };
3129 
3130   static nodes_iterator nodes_begin(BoUpSLP *R) {
3131     return nodes_iterator(R->VectorizableTree.begin());
3132   }
3133 
3134   static nodes_iterator nodes_end(BoUpSLP *R) {
3135     return nodes_iterator(R->VectorizableTree.end());
3136   }
3137 
3138   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3139 };
3140 
3141 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3142   using TreeEntry = BoUpSLP::TreeEntry;
3143 
3144   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
3145 
3146   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3147     std::string Str;
3148     raw_string_ostream OS(Str);
3149     if (isSplat(Entry->Scalars))
3150       OS << "<splat> ";
3151     for (auto V : Entry->Scalars) {
3152       OS << *V;
3153       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3154             return EU.Scalar == V;
3155           }))
3156         OS << " <extract>";
3157       OS << "\n";
3158     }
3159     return Str;
3160   }
3161 
3162   static std::string getNodeAttributes(const TreeEntry *Entry,
3163                                        const BoUpSLP *) {
3164     if (Entry->State == TreeEntry::NeedToGather)
3165       return "color=red";
3166     return "";
3167   }
3168 };
3169 
3170 } // end namespace llvm
3171 
3172 BoUpSLP::~BoUpSLP() {
3173   if (MSSA) {
3174     MemorySSAUpdater MSSAU(MSSA);
3175     for (const auto &Pair : DeletedInstructions) {
3176       if (auto *Access = MSSA->getMemoryAccess(Pair.first))
3177         MSSAU.removeMemoryAccess(Access);
3178     }
3179   }
3180   for (const auto &Pair : DeletedInstructions) {
3181     // Replace operands of ignored instructions with Undefs in case if they were
3182     // marked for deletion.
3183     if (Pair.getSecond()) {
3184       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
3185       Pair.getFirst()->replaceAllUsesWith(Undef);
3186     }
3187     Pair.getFirst()->dropAllReferences();
3188   }
3189   for (const auto &Pair : DeletedInstructions) {
3190     assert(Pair.getFirst()->use_empty() &&
3191            "trying to erase instruction with users.");
3192     Pair.getFirst()->eraseFromParent();
3193   }
3194 #ifdef EXPENSIVE_CHECKS
3195   // If we could guarantee that this call is not extremely slow, we could
3196   // remove the ifdef limitation (see PR47712).
3197   assert(!verifyFunction(*F, &dbgs()));
3198 #endif
3199 }
3200 
3201 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
3202   for (auto *V : AV) {
3203     if (auto *I = dyn_cast<Instruction>(V))
3204       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
3205   };
3206 }
3207 
3208 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3209 /// contains original mask for the scalars reused in the node. Procedure
3210 /// transform this mask in accordance with the given \p Mask.
3211 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
3212   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3213          "Expected non-empty mask.");
3214   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3215   Prev.swap(Reuses);
3216   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3217     if (Mask[I] != UndefMaskElem)
3218       Reuses[Mask[I]] = Prev[I];
3219 }
3220 
3221 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
3222 /// the original order of the scalars. Procedure transforms the provided order
3223 /// in accordance with the given \p Mask. If the resulting \p Order is just an
3224 /// identity order, \p Order is cleared.
3225 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
3226   assert(!Mask.empty() && "Expected non-empty mask.");
3227   SmallVector<int> MaskOrder;
3228   if (Order.empty()) {
3229     MaskOrder.resize(Mask.size());
3230     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3231   } else {
3232     inversePermutation(Order, MaskOrder);
3233   }
3234   reorderReuses(MaskOrder, Mask);
3235   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3236     Order.clear();
3237     return;
3238   }
3239   Order.assign(Mask.size(), Mask.size());
3240   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3241     if (MaskOrder[I] != UndefMaskElem)
3242       Order[MaskOrder[I]] = I;
3243   fixupOrderingIndices(Order);
3244 }
3245 
3246 Optional<BoUpSLP::OrdersType>
3247 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3248   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3249   unsigned NumScalars = TE.Scalars.size();
3250   OrdersType CurrentOrder(NumScalars, NumScalars);
3251   SmallVector<int> Positions;
3252   SmallBitVector UsedPositions(NumScalars);
3253   const TreeEntry *STE = nullptr;
3254   // Try to find all gathered scalars that are gets vectorized in other
3255   // vectorize node. Here we can have only one single tree vector node to
3256   // correctly identify order of the gathered scalars.
3257   for (unsigned I = 0; I < NumScalars; ++I) {
3258     Value *V = TE.Scalars[I];
3259     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3260       continue;
3261     if (const auto *LocalSTE = getTreeEntry(V)) {
3262       if (!STE)
3263         STE = LocalSTE;
3264       else if (STE != LocalSTE)
3265         // Take the order only from the single vector node.
3266         return None;
3267       unsigned Lane =
3268           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3269       if (Lane >= NumScalars)
3270         return None;
3271       if (CurrentOrder[Lane] != NumScalars) {
3272         if (Lane != I)
3273           continue;
3274         UsedPositions.reset(CurrentOrder[Lane]);
3275       }
3276       // The partial identity (where only some elements of the gather node are
3277       // in the identity order) is good.
3278       CurrentOrder[Lane] = I;
3279       UsedPositions.set(I);
3280     }
3281   }
3282   // Need to keep the order if we have a vector entry and at least 2 scalars or
3283   // the vectorized entry has just 2 scalars.
3284   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3285     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3286       for (unsigned I = 0; I < NumScalars; ++I)
3287         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3288           return false;
3289       return true;
3290     };
3291     if (IsIdentityOrder(CurrentOrder)) {
3292       CurrentOrder.clear();
3293       return CurrentOrder;
3294     }
3295     auto *It = CurrentOrder.begin();
3296     for (unsigned I = 0; I < NumScalars;) {
3297       if (UsedPositions.test(I)) {
3298         ++I;
3299         continue;
3300       }
3301       if (*It == NumScalars) {
3302         *It = I;
3303         ++I;
3304       }
3305       ++It;
3306     }
3307     return CurrentOrder;
3308   }
3309   return None;
3310 }
3311 
3312 Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3313                                                          bool TopToBottom) {
3314   // No need to reorder if need to shuffle reuses, still need to shuffle the
3315   // node.
3316   if (!TE.ReuseShuffleIndices.empty())
3317     return None;
3318   if (TE.State == TreeEntry::Vectorize &&
3319       (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3320        (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3321       !TE.isAltShuffle())
3322     return TE.ReorderIndices;
3323   if (TE.State == TreeEntry::NeedToGather) {
3324     // TODO: add analysis of other gather nodes with extractelement
3325     // instructions and other values/instructions, not only undefs.
3326     if (((TE.getOpcode() == Instruction::ExtractElement &&
3327           !TE.isAltShuffle()) ||
3328          (all_of(TE.Scalars,
3329                  [](Value *V) {
3330                    return isa<UndefValue, ExtractElementInst>(V);
3331                  }) &&
3332           any_of(TE.Scalars,
3333                  [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
3334         all_of(TE.Scalars,
3335                [](Value *V) {
3336                  auto *EE = dyn_cast<ExtractElementInst>(V);
3337                  return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
3338                }) &&
3339         allSameType(TE.Scalars)) {
3340       // Check that gather of extractelements can be represented as
3341       // just a shuffle of a single vector.
3342       OrdersType CurrentOrder;
3343       bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
3344       if (Reuse || !CurrentOrder.empty()) {
3345         if (!CurrentOrder.empty())
3346           fixupOrderingIndices(CurrentOrder);
3347         return CurrentOrder;
3348       }
3349     }
3350     if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
3351       return CurrentOrder;
3352   }
3353   return None;
3354 }
3355 
3356 void BoUpSLP::reorderTopToBottom() {
3357   // Maps VF to the graph nodes.
3358   DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
3359   // ExtractElement gather nodes which can be vectorized and need to handle
3360   // their ordering.
3361   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3362   // Find all reorderable nodes with the given VF.
3363   // Currently the are vectorized stores,loads,extracts + some gathering of
3364   // extracts.
3365   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
3366                                  const std::unique_ptr<TreeEntry> &TE) {
3367     if (Optional<OrdersType> CurrentOrder =
3368             getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
3369       // Do not include ordering for nodes used in the alt opcode vectorization,
3370       // better to reorder them during bottom-to-top stage. If follow the order
3371       // here, it causes reordering of the whole graph though actually it is
3372       // profitable just to reorder the subgraph that starts from the alternate
3373       // opcode vectorization node. Such nodes already end-up with the shuffle
3374       // instruction and it is just enough to change this shuffle rather than
3375       // rotate the scalars for the whole graph.
3376       unsigned Cnt = 0;
3377       const TreeEntry *UserTE = TE.get();
3378       while (UserTE && Cnt < RecursionMaxDepth) {
3379         if (UserTE->UserTreeIndices.size() != 1)
3380           break;
3381         if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
3382               return EI.UserTE->State == TreeEntry::Vectorize &&
3383                      EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
3384             }))
3385           return;
3386         if (UserTE->UserTreeIndices.empty())
3387           UserTE = nullptr;
3388         else
3389           UserTE = UserTE->UserTreeIndices.back().UserTE;
3390         ++Cnt;
3391       }
3392       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
3393       if (TE->State != TreeEntry::Vectorize)
3394         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3395     }
3396   });
3397 
3398   // Reorder the graph nodes according to their vectorization factor.
3399   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
3400        VF /= 2) {
3401     auto It = VFToOrderedEntries.find(VF);
3402     if (It == VFToOrderedEntries.end())
3403       continue;
3404     // Try to find the most profitable order. We just are looking for the most
3405     // used order and reorder scalar elements in the nodes according to this
3406     // mostly used order.
3407     ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
3408     // All operands are reordered and used only in this node - propagate the
3409     // most used order to the user node.
3410     MapVector<OrdersType, unsigned,
3411               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3412         OrdersUses;
3413     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3414     for (const TreeEntry *OpTE : OrderedEntries) {
3415       // No need to reorder this nodes, still need to extend and to use shuffle,
3416       // just need to merge reordering shuffle and the reuse shuffle.
3417       if (!OpTE->ReuseShuffleIndices.empty())
3418         continue;
3419       // Count number of orders uses.
3420       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3421         if (OpTE->State == TreeEntry::NeedToGather)
3422           return GathersToOrders.find(OpTE)->second;
3423         return OpTE->ReorderIndices;
3424       }();
3425       // Stores actually store the mask, not the order, need to invert.
3426       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3427           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3428         SmallVector<int> Mask;
3429         inversePermutation(Order, Mask);
3430         unsigned E = Order.size();
3431         OrdersType CurrentOrder(E, E);
3432         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3433           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3434         });
3435         fixupOrderingIndices(CurrentOrder);
3436         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3437       } else {
3438         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3439       }
3440     }
3441     // Set order of the user node.
3442     if (OrdersUses.empty())
3443       continue;
3444     // Choose the most used order.
3445     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3446     unsigned Cnt = OrdersUses.front().second;
3447     for (const auto &Pair : drop_begin(OrdersUses)) {
3448       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3449         BestOrder = Pair.first;
3450         Cnt = Pair.second;
3451       }
3452     }
3453     // Set order of the user node.
3454     if (BestOrder.empty())
3455       continue;
3456     SmallVector<int> Mask;
3457     inversePermutation(BestOrder, Mask);
3458     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3459     unsigned E = BestOrder.size();
3460     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3461       return I < E ? static_cast<int>(I) : UndefMaskElem;
3462     });
3463     // Do an actual reordering, if profitable.
3464     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
3465       // Just do the reordering for the nodes with the given VF.
3466       if (TE->Scalars.size() != VF) {
3467         if (TE->ReuseShuffleIndices.size() == VF) {
3468           // Need to reorder the reuses masks of the operands with smaller VF to
3469           // be able to find the match between the graph nodes and scalar
3470           // operands of the given node during vectorization/cost estimation.
3471           assert(all_of(TE->UserTreeIndices,
3472                         [VF, &TE](const EdgeInfo &EI) {
3473                           return EI.UserTE->Scalars.size() == VF ||
3474                                  EI.UserTE->Scalars.size() ==
3475                                      TE->Scalars.size();
3476                         }) &&
3477                  "All users must be of VF size.");
3478           // Update ordering of the operands with the smaller VF than the given
3479           // one.
3480           reorderReuses(TE->ReuseShuffleIndices, Mask);
3481         }
3482         continue;
3483       }
3484       if (TE->State == TreeEntry::Vectorize &&
3485           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
3486               InsertElementInst>(TE->getMainOp()) &&
3487           !TE->isAltShuffle()) {
3488         // Build correct orders for extract{element,value}, loads and
3489         // stores.
3490         reorderOrder(TE->ReorderIndices, Mask);
3491         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
3492           TE->reorderOperands(Mask);
3493       } else {
3494         // Reorder the node and its operands.
3495         TE->reorderOperands(Mask);
3496         assert(TE->ReorderIndices.empty() &&
3497                "Expected empty reorder sequence.");
3498         reorderScalars(TE->Scalars, Mask);
3499       }
3500       if (!TE->ReuseShuffleIndices.empty()) {
3501         // Apply reversed order to keep the original ordering of the reused
3502         // elements to avoid extra reorder indices shuffling.
3503         OrdersType CurrentOrder;
3504         reorderOrder(CurrentOrder, MaskOrder);
3505         SmallVector<int> NewReuses;
3506         inversePermutation(CurrentOrder, NewReuses);
3507         addMask(NewReuses, TE->ReuseShuffleIndices);
3508         TE->ReuseShuffleIndices.swap(NewReuses);
3509       }
3510     }
3511   }
3512 }
3513 
3514 bool BoUpSLP::canReorderOperands(
3515     TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
3516     ArrayRef<TreeEntry *> ReorderableGathers,
3517     SmallVectorImpl<TreeEntry *> &GatherOps) {
3518   for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
3519     if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
3520           return OpData.first == I &&
3521                  OpData.second->State == TreeEntry::Vectorize;
3522         }))
3523       continue;
3524     if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
3525       // Do not reorder if operand node is used by many user nodes.
3526       if (any_of(TE->UserTreeIndices,
3527                  [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
3528         return false;
3529       // Add the node to the list of the ordered nodes with the identity
3530       // order.
3531       Edges.emplace_back(I, TE);
3532       continue;
3533     }
3534     ArrayRef<Value *> VL = UserTE->getOperand(I);
3535     TreeEntry *Gather = nullptr;
3536     if (count_if(ReorderableGathers, [VL, &Gather](TreeEntry *TE) {
3537           assert(TE->State != TreeEntry::Vectorize &&
3538                  "Only non-vectorized nodes are expected.");
3539           if (TE->isSame(VL)) {
3540             Gather = TE;
3541             return true;
3542           }
3543           return false;
3544         }) > 1)
3545       return false;
3546     if (Gather)
3547       GatherOps.push_back(Gather);
3548   }
3549   return true;
3550 }
3551 
3552 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
3553   SetVector<TreeEntry *> OrderedEntries;
3554   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
3555   // Find all reorderable leaf nodes with the given VF.
3556   // Currently the are vectorized loads,extracts without alternate operands +
3557   // some gathering of extracts.
3558   SmallVector<TreeEntry *> NonVectorized;
3559   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
3560                               &NonVectorized](
3561                                  const std::unique_ptr<TreeEntry> &TE) {
3562     if (TE->State != TreeEntry::Vectorize)
3563       NonVectorized.push_back(TE.get());
3564     if (Optional<OrdersType> CurrentOrder =
3565             getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
3566       OrderedEntries.insert(TE.get());
3567       if (TE->State != TreeEntry::Vectorize)
3568         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
3569     }
3570   });
3571 
3572   // 1. Propagate order to the graph nodes, which use only reordered nodes.
3573   // I.e., if the node has operands, that are reordered, try to make at least
3574   // one operand order in the natural order and reorder others + reorder the
3575   // user node itself.
3576   SmallPtrSet<const TreeEntry *, 4> Visited;
3577   while (!OrderedEntries.empty()) {
3578     // 1. Filter out only reordered nodes.
3579     // 2. If the entry has multiple uses - skip it and jump to the next node.
3580     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3581     SmallVector<TreeEntry *> Filtered;
3582     for (TreeEntry *TE : OrderedEntries) {
3583       if (!(TE->State == TreeEntry::Vectorize ||
3584             (TE->State == TreeEntry::NeedToGather &&
3585              GathersToOrders.count(TE))) ||
3586           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3587           !all_of(drop_begin(TE->UserTreeIndices),
3588                   [TE](const EdgeInfo &EI) {
3589                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3590                   }) ||
3591           !Visited.insert(TE).second) {
3592         Filtered.push_back(TE);
3593         continue;
3594       }
3595       // Build a map between user nodes and their operands order to speedup
3596       // search. The graph currently does not provide this dependency directly.
3597       for (EdgeInfo &EI : TE->UserTreeIndices) {
3598         TreeEntry *UserTE = EI.UserTE;
3599         auto It = Users.find(UserTE);
3600         if (It == Users.end())
3601           It = Users.insert({UserTE, {}}).first;
3602         It->second.emplace_back(EI.EdgeIdx, TE);
3603       }
3604     }
3605     // Erase filtered entries.
3606     for_each(Filtered,
3607              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3608     for (auto &Data : Users) {
3609       // Check that operands are used only in the User node.
3610       SmallVector<TreeEntry *> GatherOps;
3611       if (!canReorderOperands(Data.first, Data.second, NonVectorized,
3612                               GatherOps)) {
3613         for_each(Data.second,
3614                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3615                    OrderedEntries.remove(Op.second);
3616                  });
3617         continue;
3618       }
3619       // All operands are reordered and used only in this node - propagate the
3620       // most used order to the user node.
3621       MapVector<OrdersType, unsigned,
3622                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3623           OrdersUses;
3624       // Do the analysis for each tree entry only once, otherwise the order of
3625       // the same node my be considered several times, though might be not
3626       // profitable.
3627       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3628       SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
3629       for (const auto &Op : Data.second) {
3630         TreeEntry *OpTE = Op.second;
3631         if (!VisitedOps.insert(OpTE).second)
3632           continue;
3633         if (!OpTE->ReuseShuffleIndices.empty() ||
3634             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3635           continue;
3636         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3637           if (OpTE->State == TreeEntry::NeedToGather)
3638             return GathersToOrders.find(OpTE)->second;
3639           return OpTE->ReorderIndices;
3640         }();
3641         unsigned NumOps = count_if(
3642             Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
3643               return P.second == OpTE;
3644             });
3645         // Stores actually store the mask, not the order, need to invert.
3646         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3647             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3648           SmallVector<int> Mask;
3649           inversePermutation(Order, Mask);
3650           unsigned E = Order.size();
3651           OrdersType CurrentOrder(E, E);
3652           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3653             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3654           });
3655           fixupOrderingIndices(CurrentOrder);
3656           OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
3657               NumOps;
3658         } else {
3659           OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
3660         }
3661         auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
3662         const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
3663                                             const TreeEntry *TE) {
3664           if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3665               (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
3666               (IgnoreReorder && TE->Idx == 0))
3667             return true;
3668           if (TE->State == TreeEntry::NeedToGather) {
3669             auto It = GathersToOrders.find(TE);
3670             if (It != GathersToOrders.end())
3671               return !It->second.empty();
3672             return true;
3673           }
3674           return false;
3675         };
3676         for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
3677           TreeEntry *UserTE = EI.UserTE;
3678           if (!VisitedUsers.insert(UserTE).second)
3679             continue;
3680           // May reorder user node if it requires reordering, has reused
3681           // scalars, is an alternate op vectorize node or its op nodes require
3682           // reordering.
3683           if (AllowsReordering(UserTE))
3684             continue;
3685           // Check if users allow reordering.
3686           // Currently look up just 1 level of operands to avoid increase of
3687           // the compile time.
3688           // Profitable to reorder if definitely more operands allow
3689           // reordering rather than those with natural order.
3690           ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
3691           if (static_cast<unsigned>(count_if(
3692                   Ops, [UserTE, &AllowsReordering](
3693                            const std::pair<unsigned, TreeEntry *> &Op) {
3694                     return AllowsReordering(Op.second) &&
3695                            all_of(Op.second->UserTreeIndices,
3696                                   [UserTE](const EdgeInfo &EI) {
3697                                     return EI.UserTE == UserTE;
3698                                   });
3699                   })) <= Ops.size() / 2)
3700             ++Res.first->second;
3701         }
3702       }
3703       // If no orders - skip current nodes and jump to the next one, if any.
3704       if (OrdersUses.empty()) {
3705         for_each(Data.second,
3706                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3707                    OrderedEntries.remove(Op.second);
3708                  });
3709         continue;
3710       }
3711       // Choose the best order.
3712       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3713       unsigned Cnt = OrdersUses.front().second;
3714       for (const auto &Pair : drop_begin(OrdersUses)) {
3715         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3716           BestOrder = Pair.first;
3717           Cnt = Pair.second;
3718         }
3719       }
3720       // Set order of the user node (reordering of operands and user nodes).
3721       if (BestOrder.empty()) {
3722         for_each(Data.second,
3723                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3724                    OrderedEntries.remove(Op.second);
3725                  });
3726         continue;
3727       }
3728       // Erase operands from OrderedEntries list and adjust their orders.
3729       VisitedOps.clear();
3730       SmallVector<int> Mask;
3731       inversePermutation(BestOrder, Mask);
3732       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3733       unsigned E = BestOrder.size();
3734       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3735         return I < E ? static_cast<int>(I) : UndefMaskElem;
3736       });
3737       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3738         TreeEntry *TE = Op.second;
3739         OrderedEntries.remove(TE);
3740         if (!VisitedOps.insert(TE).second)
3741           continue;
3742         if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
3743           // Just reorder reuses indices.
3744           reorderReuses(TE->ReuseShuffleIndices, Mask);
3745           continue;
3746         }
3747         // Gathers are processed separately.
3748         if (TE->State != TreeEntry::Vectorize)
3749           continue;
3750         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3751                 TE->ReorderIndices.empty()) &&
3752                "Non-matching sizes of user/operand entries.");
3753         reorderOrder(TE->ReorderIndices, Mask);
3754       }
3755       // For gathers just need to reorder its scalars.
3756       for (TreeEntry *Gather : GatherOps) {
3757         assert(Gather->ReorderIndices.empty() &&
3758                "Unexpected reordering of gathers.");
3759         if (!Gather->ReuseShuffleIndices.empty()) {
3760           // Just reorder reuses indices.
3761           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3762           continue;
3763         }
3764         reorderScalars(Gather->Scalars, Mask);
3765         OrderedEntries.remove(Gather);
3766       }
3767       // Reorder operands of the user node and set the ordering for the user
3768       // node itself.
3769       if (Data.first->State != TreeEntry::Vectorize ||
3770           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3771               Data.first->getMainOp()) ||
3772           Data.first->isAltShuffle())
3773         Data.first->reorderOperands(Mask);
3774       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3775           Data.first->isAltShuffle()) {
3776         reorderScalars(Data.first->Scalars, Mask);
3777         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3778         if (Data.first->ReuseShuffleIndices.empty() &&
3779             !Data.first->ReorderIndices.empty() &&
3780             !Data.first->isAltShuffle()) {
3781           // Insert user node to the list to try to sink reordering deeper in
3782           // the graph.
3783           OrderedEntries.insert(Data.first);
3784         }
3785       } else {
3786         reorderOrder(Data.first->ReorderIndices, Mask);
3787       }
3788     }
3789   }
3790   // If the reordering is unnecessary, just remove the reorder.
3791   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3792       VectorizableTree.front()->ReuseShuffleIndices.empty())
3793     VectorizableTree.front()->ReorderIndices.clear();
3794 }
3795 
3796 void BoUpSLP::buildExternalUses(
3797     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3798   // Collect the values that we need to extract from the tree.
3799   for (auto &TEPtr : VectorizableTree) {
3800     TreeEntry *Entry = TEPtr.get();
3801 
3802     // No need to handle users of gathered values.
3803     if (Entry->State == TreeEntry::NeedToGather)
3804       continue;
3805 
3806     // For each lane:
3807     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3808       Value *Scalar = Entry->Scalars[Lane];
3809       int FoundLane = Entry->findLaneForValue(Scalar);
3810 
3811       // Check if the scalar is externally used as an extra arg.
3812       auto ExtI = ExternallyUsedValues.find(Scalar);
3813       if (ExtI != ExternallyUsedValues.end()) {
3814         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3815                           << Lane << " from " << *Scalar << ".\n");
3816         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3817       }
3818       for (User *U : Scalar->users()) {
3819         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3820 
3821         Instruction *UserInst = dyn_cast<Instruction>(U);
3822         if (!UserInst)
3823           continue;
3824 
3825         if (isDeleted(UserInst))
3826           continue;
3827 
3828         // Skip in-tree scalars that become vectors
3829         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3830           Value *UseScalar = UseEntry->Scalars[0];
3831           // Some in-tree scalars will remain as scalar in vectorized
3832           // instructions. If that is the case, the one in Lane 0 will
3833           // be used.
3834           if (UseScalar != U ||
3835               UseEntry->State == TreeEntry::ScatterVectorize ||
3836               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3837             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3838                               << ".\n");
3839             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3840             continue;
3841           }
3842         }
3843 
3844         // Ignore users in the user ignore list.
3845         if (is_contained(UserIgnoreList, UserInst))
3846           continue;
3847 
3848         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3849                           << Lane << " from " << *Scalar << ".\n");
3850         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3851       }
3852     }
3853   }
3854 }
3855 
3856 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3857                         ArrayRef<Value *> UserIgnoreLst) {
3858   deleteTree();
3859   UserIgnoreList = UserIgnoreLst;
3860   if (!allSameType(Roots))
3861     return;
3862   buildTree_rec(Roots, 0, EdgeInfo());
3863 }
3864 
3865 namespace {
3866 /// Tracks the state we can represent the loads in the given sequence.
3867 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3868 } // anonymous namespace
3869 
3870 /// Checks if the given array of loads can be represented as a vectorized,
3871 /// scatter or just simple gather.
3872 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3873                                     const TargetTransformInfo &TTI,
3874                                     const DataLayout &DL, ScalarEvolution &SE,
3875                                     SmallVectorImpl<unsigned> &Order,
3876                                     SmallVectorImpl<Value *> &PointerOps) {
3877   // Check that a vectorized load would load the same memory as a scalar
3878   // load. For example, we don't want to vectorize loads that are smaller
3879   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3880   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3881   // from such a struct, we read/write packed bits disagreeing with the
3882   // unvectorized version.
3883   Type *ScalarTy = VL0->getType();
3884 
3885   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3886     return LoadsState::Gather;
3887 
3888   // Make sure all loads in the bundle are simple - we can't vectorize
3889   // atomic or volatile loads.
3890   PointerOps.clear();
3891   PointerOps.resize(VL.size());
3892   auto *POIter = PointerOps.begin();
3893   for (Value *V : VL) {
3894     auto *L = cast<LoadInst>(V);
3895     if (!L->isSimple())
3896       return LoadsState::Gather;
3897     *POIter = L->getPointerOperand();
3898     ++POIter;
3899   }
3900 
3901   Order.clear();
3902   // Check the order of pointer operands.
3903   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3904     Value *Ptr0;
3905     Value *PtrN;
3906     if (Order.empty()) {
3907       Ptr0 = PointerOps.front();
3908       PtrN = PointerOps.back();
3909     } else {
3910       Ptr0 = PointerOps[Order.front()];
3911       PtrN = PointerOps[Order.back()];
3912     }
3913     Optional<int> Diff =
3914         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3915     // Check that the sorted loads are consecutive.
3916     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3917       return LoadsState::Vectorize;
3918     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3919     for (Value *V : VL)
3920       CommonAlignment =
3921           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3922     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3923                                 CommonAlignment))
3924       return LoadsState::ScatterVectorize;
3925   }
3926 
3927   return LoadsState::Gather;
3928 }
3929 
3930 /// \return true if the specified list of values has only one instruction that
3931 /// requires scheduling, false otherwise.
3932 static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
3933   Value *NeedsScheduling = nullptr;
3934   for (Value *V : VL) {
3935     if (doesNotNeedToBeScheduled(V))
3936       continue;
3937     if (!NeedsScheduling) {
3938       NeedsScheduling = V;
3939       continue;
3940     }
3941     return false;
3942   }
3943   return NeedsScheduling;
3944 }
3945 
3946 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3947                             const EdgeInfo &UserTreeIdx) {
3948   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3949 
3950   SmallVector<int> ReuseShuffleIndicies;
3951   SmallVector<Value *> UniqueValues;
3952   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3953                                 &UserTreeIdx,
3954                                 this](const InstructionsState &S) {
3955     // Check that every instruction appears once in this bundle.
3956     DenseMap<Value *, unsigned> UniquePositions;
3957     for (Value *V : VL) {
3958       if (isConstant(V)) {
3959         ReuseShuffleIndicies.emplace_back(
3960             isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
3961         UniqueValues.emplace_back(V);
3962         continue;
3963       }
3964       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3965       ReuseShuffleIndicies.emplace_back(Res.first->second);
3966       if (Res.second)
3967         UniqueValues.emplace_back(V);
3968     }
3969     size_t NumUniqueScalarValues = UniqueValues.size();
3970     if (NumUniqueScalarValues == VL.size()) {
3971       ReuseShuffleIndicies.clear();
3972     } else {
3973       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3974       if (NumUniqueScalarValues <= 1 ||
3975           (UniquePositions.size() == 1 && all_of(UniqueValues,
3976                                                  [](Value *V) {
3977                                                    return isa<UndefValue>(V) ||
3978                                                           !isConstant(V);
3979                                                  })) ||
3980           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3981         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3982         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3983         return false;
3984       }
3985       VL = UniqueValues;
3986     }
3987     return true;
3988   };
3989 
3990   InstructionsState S = getSameOpcode(VL);
3991   if (Depth == RecursionMaxDepth) {
3992     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3993     if (TryToFindDuplicates(S))
3994       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3995                    ReuseShuffleIndicies);
3996     return;
3997   }
3998 
3999   // Don't handle scalable vectors
4000   if (S.getOpcode() == Instruction::ExtractElement &&
4001       isa<ScalableVectorType>(
4002           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
4003     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
4004     if (TryToFindDuplicates(S))
4005       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4006                    ReuseShuffleIndicies);
4007     return;
4008   }
4009 
4010   // Don't handle vectors.
4011   if (S.OpValue->getType()->isVectorTy() &&
4012       !isa<InsertElementInst>(S.OpValue)) {
4013     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
4014     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4015     return;
4016   }
4017 
4018   // Avoid attempting to schedule allocas; there are unmodeled dependencies
4019   // for "static" alloca status and for reordering with stacksave calls.
4020   for (Value *V : VL) {
4021     if (isa<AllocaInst>(V)) {
4022       LLVM_DEBUG(dbgs() << "SLP: Gathering due to alloca.\n");
4023       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4024       return;
4025     }
4026   }
4027 
4028   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4029     if (SI->getValueOperand()->getType()->isVectorTy()) {
4030       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
4031       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4032       return;
4033     }
4034 
4035   // If all of the operands are identical or constant we have a simple solution.
4036   // If we deal with insert/extract instructions, they all must have constant
4037   // indices, otherwise we should gather them, not try to vectorize.
4038   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
4039       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
4040        !all_of(VL, isVectorLikeInstWithConstOps))) {
4041     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
4042     if (TryToFindDuplicates(S))
4043       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4044                    ReuseShuffleIndicies);
4045     return;
4046   }
4047 
4048   // We now know that this is a vector of instructions of the same type from
4049   // the same block.
4050 
4051   // Don't vectorize ephemeral values.
4052   for (Value *V : VL) {
4053     if (EphValues.count(V)) {
4054       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4055                         << ") is ephemeral.\n");
4056       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4057       return;
4058     }
4059   }
4060 
4061   // Check if this is a duplicate of another entry.
4062   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4063     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
4064     if (!E->isSame(VL)) {
4065       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
4066       if (TryToFindDuplicates(S))
4067         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4068                      ReuseShuffleIndicies);
4069       return;
4070     }
4071     // Record the reuse of the tree node.  FIXME, currently this is only used to
4072     // properly draw the graph rather than for the actual vectorization.
4073     E->UserTreeIndices.push_back(UserTreeIdx);
4074     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
4075                       << ".\n");
4076     return;
4077   }
4078 
4079   // Check that none of the instructions in the bundle are already in the tree.
4080   for (Value *V : VL) {
4081     auto *I = dyn_cast<Instruction>(V);
4082     if (!I)
4083       continue;
4084     if (getTreeEntry(I)) {
4085       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
4086                         << ") is already in tree.\n");
4087       if (TryToFindDuplicates(S))
4088         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4089                      ReuseShuffleIndicies);
4090       return;
4091     }
4092   }
4093 
4094   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
4095   for (Value *V : VL) {
4096     if (is_contained(UserIgnoreList, V)) {
4097       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
4098       if (TryToFindDuplicates(S))
4099         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4100                      ReuseShuffleIndicies);
4101       return;
4102     }
4103   }
4104 
4105   // Check that all of the users of the scalars that we want to vectorize are
4106   // schedulable.
4107   auto *VL0 = cast<Instruction>(S.OpValue);
4108   BasicBlock *BB = VL0->getParent();
4109 
4110   if (!DT->isReachableFromEntry(BB)) {
4111     // Don't go into unreachable blocks. They may contain instructions with
4112     // dependency cycles which confuse the final scheduling.
4113     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
4114     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4115     return;
4116   }
4117 
4118   // Check that every instruction appears once in this bundle.
4119   if (!TryToFindDuplicates(S))
4120     return;
4121 
4122   auto &BSRef = BlocksSchedules[BB];
4123   if (!BSRef)
4124     BSRef = std::make_unique<BlockScheduling>(BB);
4125 
4126   BlockScheduling &BS = *BSRef.get();
4127 
4128   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
4129 #ifdef EXPENSIVE_CHECKS
4130   // Make sure we didn't break any internal invariants
4131   BS.verify();
4132 #endif
4133   if (!Bundle) {
4134     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
4135     assert((!BS.getScheduleData(VL0) ||
4136             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
4137            "tryScheduleBundle should cancelScheduling on failure");
4138     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4139                  ReuseShuffleIndicies);
4140     return;
4141   }
4142   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
4143 
4144   unsigned ShuffleOrOp = S.isAltShuffle() ?
4145                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
4146   switch (ShuffleOrOp) {
4147     case Instruction::PHI: {
4148       auto *PH = cast<PHINode>(VL0);
4149 
4150       // Check for terminator values (e.g. invoke).
4151       for (Value *V : VL)
4152         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4153           Instruction *Term = dyn_cast<Instruction>(
4154               cast<PHINode>(V)->getIncomingValueForBlock(
4155                   PH->getIncomingBlock(I)));
4156           if (Term && Term->isTerminator()) {
4157             LLVM_DEBUG(dbgs()
4158                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
4159             BS.cancelScheduling(VL, VL0);
4160             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4161                          ReuseShuffleIndicies);
4162             return;
4163           }
4164         }
4165 
4166       TreeEntry *TE =
4167           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
4168       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
4169 
4170       // Keeps the reordered operands to avoid code duplication.
4171       SmallVector<ValueList, 2> OperandsVec;
4172       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
4173         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
4174           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
4175           TE->setOperand(I, Operands);
4176           OperandsVec.push_back(Operands);
4177           continue;
4178         }
4179         ValueList Operands;
4180         // Prepare the operand vector.
4181         for (Value *V : VL)
4182           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
4183               PH->getIncomingBlock(I)));
4184         TE->setOperand(I, Operands);
4185         OperandsVec.push_back(Operands);
4186       }
4187       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
4188         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
4189       return;
4190     }
4191     case Instruction::ExtractValue:
4192     case Instruction::ExtractElement: {
4193       OrdersType CurrentOrder;
4194       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
4195       if (Reuse) {
4196         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
4197         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4198                      ReuseShuffleIndicies);
4199         // This is a special case, as it does not gather, but at the same time
4200         // we are not extending buildTree_rec() towards the operands.
4201         ValueList Op0;
4202         Op0.assign(VL.size(), VL0->getOperand(0));
4203         VectorizableTree.back()->setOperand(0, Op0);
4204         return;
4205       }
4206       if (!CurrentOrder.empty()) {
4207         LLVM_DEBUG({
4208           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
4209                     "with order";
4210           for (unsigned Idx : CurrentOrder)
4211             dbgs() << " " << Idx;
4212           dbgs() << "\n";
4213         });
4214         fixupOrderingIndices(CurrentOrder);
4215         // Insert new order with initial value 0, if it does not exist,
4216         // otherwise return the iterator to the existing one.
4217         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4218                      ReuseShuffleIndicies, CurrentOrder);
4219         // This is a special case, as it does not gather, but at the same time
4220         // we are not extending buildTree_rec() towards the operands.
4221         ValueList Op0;
4222         Op0.assign(VL.size(), VL0->getOperand(0));
4223         VectorizableTree.back()->setOperand(0, Op0);
4224         return;
4225       }
4226       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
4227       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4228                    ReuseShuffleIndicies);
4229       BS.cancelScheduling(VL, VL0);
4230       return;
4231     }
4232     case Instruction::InsertElement: {
4233       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
4234 
4235       // Check that we have a buildvector and not a shuffle of 2 or more
4236       // different vectors.
4237       ValueSet SourceVectors;
4238       for (Value *V : VL) {
4239         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
4240         assert(getInsertIndex(V) != None && "Non-constant or undef index?");
4241       }
4242 
4243       if (count_if(VL, [&SourceVectors](Value *V) {
4244             return !SourceVectors.contains(V);
4245           }) >= 2) {
4246         // Found 2nd source vector - cancel.
4247         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
4248                              "different source vectors.\n");
4249         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
4250         BS.cancelScheduling(VL, VL0);
4251         return;
4252       }
4253 
4254       auto OrdCompare = [](const std::pair<int, int> &P1,
4255                            const std::pair<int, int> &P2) {
4256         return P1.first > P2.first;
4257       };
4258       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
4259                     decltype(OrdCompare)>
4260           Indices(OrdCompare);
4261       for (int I = 0, E = VL.size(); I < E; ++I) {
4262         unsigned Idx = *getInsertIndex(VL[I]);
4263         Indices.emplace(Idx, I);
4264       }
4265       OrdersType CurrentOrder(VL.size(), VL.size());
4266       bool IsIdentity = true;
4267       for (int I = 0, E = VL.size(); I < E; ++I) {
4268         CurrentOrder[Indices.top().second] = I;
4269         IsIdentity &= Indices.top().second == I;
4270         Indices.pop();
4271       }
4272       if (IsIdentity)
4273         CurrentOrder.clear();
4274       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4275                                    None, CurrentOrder);
4276       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
4277 
4278       constexpr int NumOps = 2;
4279       ValueList VectorOperands[NumOps];
4280       for (int I = 0; I < NumOps; ++I) {
4281         for (Value *V : VL)
4282           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
4283 
4284         TE->setOperand(I, VectorOperands[I]);
4285       }
4286       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
4287       return;
4288     }
4289     case Instruction::Load: {
4290       // Check that a vectorized load would load the same memory as a scalar
4291       // load. For example, we don't want to vectorize loads that are smaller
4292       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
4293       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
4294       // from such a struct, we read/write packed bits disagreeing with the
4295       // unvectorized version.
4296       SmallVector<Value *> PointerOps;
4297       OrdersType CurrentOrder;
4298       TreeEntry *TE = nullptr;
4299       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
4300                                 PointerOps)) {
4301       case LoadsState::Vectorize:
4302         if (CurrentOrder.empty()) {
4303           // Original loads are consecutive and does not require reordering.
4304           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4305                             ReuseShuffleIndicies);
4306           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
4307         } else {
4308           fixupOrderingIndices(CurrentOrder);
4309           // Need to reorder.
4310           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4311                             ReuseShuffleIndicies, CurrentOrder);
4312           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
4313         }
4314         TE->setOperandsInOrder();
4315         break;
4316       case LoadsState::ScatterVectorize:
4317         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
4318         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
4319                           UserTreeIdx, ReuseShuffleIndicies);
4320         TE->setOperandsInOrder();
4321         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
4322         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
4323         break;
4324       case LoadsState::Gather:
4325         BS.cancelScheduling(VL, VL0);
4326         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4327                      ReuseShuffleIndicies);
4328 #ifndef NDEBUG
4329         Type *ScalarTy = VL0->getType();
4330         if (DL->getTypeSizeInBits(ScalarTy) !=
4331             DL->getTypeAllocSizeInBits(ScalarTy))
4332           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
4333         else if (any_of(VL, [](Value *V) {
4334                    return !cast<LoadInst>(V)->isSimple();
4335                  }))
4336           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
4337         else
4338           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
4339 #endif // NDEBUG
4340         break;
4341       }
4342       return;
4343     }
4344     case Instruction::ZExt:
4345     case Instruction::SExt:
4346     case Instruction::FPToUI:
4347     case Instruction::FPToSI:
4348     case Instruction::FPExt:
4349     case Instruction::PtrToInt:
4350     case Instruction::IntToPtr:
4351     case Instruction::SIToFP:
4352     case Instruction::UIToFP:
4353     case Instruction::Trunc:
4354     case Instruction::FPTrunc:
4355     case Instruction::BitCast: {
4356       Type *SrcTy = VL0->getOperand(0)->getType();
4357       for (Value *V : VL) {
4358         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
4359         if (Ty != SrcTy || !isValidElementType(Ty)) {
4360           BS.cancelScheduling(VL, VL0);
4361           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4362                        ReuseShuffleIndicies);
4363           LLVM_DEBUG(dbgs()
4364                      << "SLP: Gathering casts with different src types.\n");
4365           return;
4366         }
4367       }
4368       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4369                                    ReuseShuffleIndicies);
4370       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
4371 
4372       TE->setOperandsInOrder();
4373       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4374         ValueList Operands;
4375         // Prepare the operand vector.
4376         for (Value *V : VL)
4377           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4378 
4379         buildTree_rec(Operands, Depth + 1, {TE, i});
4380       }
4381       return;
4382     }
4383     case Instruction::ICmp:
4384     case Instruction::FCmp: {
4385       // Check that all of the compares have the same predicate.
4386       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4387       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
4388       Type *ComparedTy = VL0->getOperand(0)->getType();
4389       for (Value *V : VL) {
4390         CmpInst *Cmp = cast<CmpInst>(V);
4391         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
4392             Cmp->getOperand(0)->getType() != ComparedTy) {
4393           BS.cancelScheduling(VL, VL0);
4394           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4395                        ReuseShuffleIndicies);
4396           LLVM_DEBUG(dbgs()
4397                      << "SLP: Gathering cmp with different predicate.\n");
4398           return;
4399         }
4400       }
4401 
4402       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4403                                    ReuseShuffleIndicies);
4404       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
4405 
4406       ValueList Left, Right;
4407       if (cast<CmpInst>(VL0)->isCommutative()) {
4408         // Commutative predicate - collect + sort operands of the instructions
4409         // so that each side is more likely to have the same opcode.
4410         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
4411         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4412       } else {
4413         // Collect operands - commute if it uses the swapped predicate.
4414         for (Value *V : VL) {
4415           auto *Cmp = cast<CmpInst>(V);
4416           Value *LHS = Cmp->getOperand(0);
4417           Value *RHS = Cmp->getOperand(1);
4418           if (Cmp->getPredicate() != P0)
4419             std::swap(LHS, RHS);
4420           Left.push_back(LHS);
4421           Right.push_back(RHS);
4422         }
4423       }
4424       TE->setOperand(0, Left);
4425       TE->setOperand(1, Right);
4426       buildTree_rec(Left, Depth + 1, {TE, 0});
4427       buildTree_rec(Right, Depth + 1, {TE, 1});
4428       return;
4429     }
4430     case Instruction::Select:
4431     case Instruction::FNeg:
4432     case Instruction::Add:
4433     case Instruction::FAdd:
4434     case Instruction::Sub:
4435     case Instruction::FSub:
4436     case Instruction::Mul:
4437     case Instruction::FMul:
4438     case Instruction::UDiv:
4439     case Instruction::SDiv:
4440     case Instruction::FDiv:
4441     case Instruction::URem:
4442     case Instruction::SRem:
4443     case Instruction::FRem:
4444     case Instruction::Shl:
4445     case Instruction::LShr:
4446     case Instruction::AShr:
4447     case Instruction::And:
4448     case Instruction::Or:
4449     case Instruction::Xor: {
4450       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4451                                    ReuseShuffleIndicies);
4452       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
4453 
4454       // Sort operands of the instructions so that each side is more likely to
4455       // have the same opcode.
4456       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
4457         ValueList Left, Right;
4458         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4459         TE->setOperand(0, Left);
4460         TE->setOperand(1, Right);
4461         buildTree_rec(Left, Depth + 1, {TE, 0});
4462         buildTree_rec(Right, Depth + 1, {TE, 1});
4463         return;
4464       }
4465 
4466       TE->setOperandsInOrder();
4467       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4468         ValueList Operands;
4469         // Prepare the operand vector.
4470         for (Value *V : VL)
4471           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4472 
4473         buildTree_rec(Operands, Depth + 1, {TE, i});
4474       }
4475       return;
4476     }
4477     case Instruction::GetElementPtr: {
4478       // We don't combine GEPs with complicated (nested) indexing.
4479       for (Value *V : VL) {
4480         if (cast<Instruction>(V)->getNumOperands() != 2) {
4481           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
4482           BS.cancelScheduling(VL, VL0);
4483           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4484                        ReuseShuffleIndicies);
4485           return;
4486         }
4487       }
4488 
4489       // We can't combine several GEPs into one vector if they operate on
4490       // different types.
4491       Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
4492       for (Value *V : VL) {
4493         Type *CurTy = cast<GEPOperator>(V)->getSourceElementType();
4494         if (Ty0 != CurTy) {
4495           LLVM_DEBUG(dbgs()
4496                      << "SLP: not-vectorizable GEP (different types).\n");
4497           BS.cancelScheduling(VL, VL0);
4498           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4499                        ReuseShuffleIndicies);
4500           return;
4501         }
4502       }
4503 
4504       // We don't combine GEPs with non-constant indexes.
4505       Type *Ty1 = VL0->getOperand(1)->getType();
4506       for (Value *V : VL) {
4507         auto Op = cast<Instruction>(V)->getOperand(1);
4508         if (!isa<ConstantInt>(Op) ||
4509             (Op->getType() != Ty1 &&
4510              Op->getType()->getScalarSizeInBits() >
4511                  DL->getIndexSizeInBits(
4512                      V->getType()->getPointerAddressSpace()))) {
4513           LLVM_DEBUG(dbgs()
4514                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
4515           BS.cancelScheduling(VL, VL0);
4516           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4517                        ReuseShuffleIndicies);
4518           return;
4519         }
4520       }
4521 
4522       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4523                                    ReuseShuffleIndicies);
4524       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
4525       SmallVector<ValueList, 2> Operands(2);
4526       // Prepare the operand vector for pointer operands.
4527       for (Value *V : VL)
4528         Operands.front().push_back(
4529             cast<GetElementPtrInst>(V)->getPointerOperand());
4530       TE->setOperand(0, Operands.front());
4531       // Need to cast all indices to the same type before vectorization to
4532       // avoid crash.
4533       // Required to be able to find correct matches between different gather
4534       // nodes and reuse the vectorized values rather than trying to gather them
4535       // again.
4536       int IndexIdx = 1;
4537       Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
4538       Type *Ty = all_of(VL,
4539                         [VL0Ty, IndexIdx](Value *V) {
4540                           return VL0Ty == cast<GetElementPtrInst>(V)
4541                                               ->getOperand(IndexIdx)
4542                                               ->getType();
4543                         })
4544                      ? VL0Ty
4545                      : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4546                                             ->getPointerOperandType()
4547                                             ->getScalarType());
4548       // Prepare the operand vector.
4549       for (Value *V : VL) {
4550         auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
4551         auto *CI = cast<ConstantInt>(Op);
4552         Operands.back().push_back(ConstantExpr::getIntegerCast(
4553             CI, Ty, CI->getValue().isSignBitSet()));
4554       }
4555       TE->setOperand(IndexIdx, Operands.back());
4556 
4557       for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
4558         buildTree_rec(Operands[I], Depth + 1, {TE, I});
4559       return;
4560     }
4561     case Instruction::Store: {
4562       // Check if the stores are consecutive or if we need to swizzle them.
4563       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
4564       // Avoid types that are padded when being allocated as scalars, while
4565       // being packed together in a vector (such as i1).
4566       if (DL->getTypeSizeInBits(ScalarTy) !=
4567           DL->getTypeAllocSizeInBits(ScalarTy)) {
4568         BS.cancelScheduling(VL, VL0);
4569         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4570                      ReuseShuffleIndicies);
4571         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
4572         return;
4573       }
4574       // Make sure all stores in the bundle are simple - we can't vectorize
4575       // atomic or volatile stores.
4576       SmallVector<Value *, 4> PointerOps(VL.size());
4577       ValueList Operands(VL.size());
4578       auto POIter = PointerOps.begin();
4579       auto OIter = Operands.begin();
4580       for (Value *V : VL) {
4581         auto *SI = cast<StoreInst>(V);
4582         if (!SI->isSimple()) {
4583           BS.cancelScheduling(VL, VL0);
4584           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4585                        ReuseShuffleIndicies);
4586           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
4587           return;
4588         }
4589         *POIter = SI->getPointerOperand();
4590         *OIter = SI->getValueOperand();
4591         ++POIter;
4592         ++OIter;
4593       }
4594 
4595       OrdersType CurrentOrder;
4596       // Check the order of pointer operands.
4597       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
4598         Value *Ptr0;
4599         Value *PtrN;
4600         if (CurrentOrder.empty()) {
4601           Ptr0 = PointerOps.front();
4602           PtrN = PointerOps.back();
4603         } else {
4604           Ptr0 = PointerOps[CurrentOrder.front()];
4605           PtrN = PointerOps[CurrentOrder.back()];
4606         }
4607         Optional<int> Dist =
4608             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
4609         // Check that the sorted pointer operands are consecutive.
4610         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
4611           if (CurrentOrder.empty()) {
4612             // Original stores are consecutive and does not require reordering.
4613             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
4614                                          UserTreeIdx, ReuseShuffleIndicies);
4615             TE->setOperandsInOrder();
4616             buildTree_rec(Operands, Depth + 1, {TE, 0});
4617             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
4618           } else {
4619             fixupOrderingIndices(CurrentOrder);
4620             TreeEntry *TE =
4621                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4622                              ReuseShuffleIndicies, CurrentOrder);
4623             TE->setOperandsInOrder();
4624             buildTree_rec(Operands, Depth + 1, {TE, 0});
4625             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
4626           }
4627           return;
4628         }
4629       }
4630 
4631       BS.cancelScheduling(VL, VL0);
4632       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4633                    ReuseShuffleIndicies);
4634       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
4635       return;
4636     }
4637     case Instruction::Call: {
4638       // Check if the calls are all to the same vectorizable intrinsic or
4639       // library function.
4640       CallInst *CI = cast<CallInst>(VL0);
4641       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4642 
4643       VFShape Shape = VFShape::get(
4644           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
4645           false /*HasGlobalPred*/);
4646       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4647 
4648       if (!VecFunc && !isTriviallyVectorizable(ID)) {
4649         BS.cancelScheduling(VL, VL0);
4650         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4651                      ReuseShuffleIndicies);
4652         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
4653         return;
4654       }
4655       Function *F = CI->getCalledFunction();
4656       unsigned NumArgs = CI->arg_size();
4657       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
4658       for (unsigned j = 0; j != NumArgs; ++j)
4659         if (hasVectorInstrinsicScalarOpd(ID, j))
4660           ScalarArgs[j] = CI->getArgOperand(j);
4661       for (Value *V : VL) {
4662         CallInst *CI2 = dyn_cast<CallInst>(V);
4663         if (!CI2 || CI2->getCalledFunction() != F ||
4664             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
4665             (VecFunc &&
4666              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
4667             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
4668           BS.cancelScheduling(VL, VL0);
4669           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4670                        ReuseShuffleIndicies);
4671           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
4672                             << "\n");
4673           return;
4674         }
4675         // Some intrinsics have scalar arguments and should be same in order for
4676         // them to be vectorized.
4677         for (unsigned j = 0; j != NumArgs; ++j) {
4678           if (hasVectorInstrinsicScalarOpd(ID, j)) {
4679             Value *A1J = CI2->getArgOperand(j);
4680             if (ScalarArgs[j] != A1J) {
4681               BS.cancelScheduling(VL, VL0);
4682               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4683                            ReuseShuffleIndicies);
4684               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4685                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4686                                 << "\n");
4687               return;
4688             }
4689           }
4690         }
4691         // Verify that the bundle operands are identical between the two calls.
4692         if (CI->hasOperandBundles() &&
4693             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4694                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4695                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4696           BS.cancelScheduling(VL, VL0);
4697           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4698                        ReuseShuffleIndicies);
4699           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4700                             << *CI << "!=" << *V << '\n');
4701           return;
4702         }
4703       }
4704 
4705       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4706                                    ReuseShuffleIndicies);
4707       TE->setOperandsInOrder();
4708       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4709         // For scalar operands no need to to create an entry since no need to
4710         // vectorize it.
4711         if (hasVectorInstrinsicScalarOpd(ID, i))
4712           continue;
4713         ValueList Operands;
4714         // Prepare the operand vector.
4715         for (Value *V : VL) {
4716           auto *CI2 = cast<CallInst>(V);
4717           Operands.push_back(CI2->getArgOperand(i));
4718         }
4719         buildTree_rec(Operands, Depth + 1, {TE, i});
4720       }
4721       return;
4722     }
4723     case Instruction::ShuffleVector: {
4724       // If this is not an alternate sequence of opcode like add-sub
4725       // then do not vectorize this instruction.
4726       if (!S.isAltShuffle()) {
4727         BS.cancelScheduling(VL, VL0);
4728         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4729                      ReuseShuffleIndicies);
4730         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4731         return;
4732       }
4733       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4734                                    ReuseShuffleIndicies);
4735       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4736 
4737       // Reorder operands if reordering would enable vectorization.
4738       auto *CI = dyn_cast<CmpInst>(VL0);
4739       if (isa<BinaryOperator>(VL0) || CI) {
4740         ValueList Left, Right;
4741         if (!CI || all_of(VL, [](Value *V) {
4742               return cast<CmpInst>(V)->isCommutative();
4743             })) {
4744           reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4745         } else {
4746           CmpInst::Predicate P0 = CI->getPredicate();
4747           CmpInst::Predicate AltP0 = cast<CmpInst>(S.AltOp)->getPredicate();
4748           assert(P0 != AltP0 &&
4749                  "Expected different main/alternate predicates.");
4750           CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
4751           Value *BaseOp0 = VL0->getOperand(0);
4752           Value *BaseOp1 = VL0->getOperand(1);
4753           // Collect operands - commute if it uses the swapped predicate or
4754           // alternate operation.
4755           for (Value *V : VL) {
4756             auto *Cmp = cast<CmpInst>(V);
4757             Value *LHS = Cmp->getOperand(0);
4758             Value *RHS = Cmp->getOperand(1);
4759             CmpInst::Predicate CurrentPred = Cmp->getPredicate();
4760             if (P0 == AltP0Swapped) {
4761               if (CI != Cmp && S.AltOp != Cmp &&
4762                   ((P0 == CurrentPred &&
4763                     !areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS)) ||
4764                    (AltP0 == CurrentPred &&
4765                     areCompatibleCmpOps(BaseOp0, BaseOp1, LHS, RHS))))
4766                 std::swap(LHS, RHS);
4767             } else if (P0 != CurrentPred && AltP0 != CurrentPred) {
4768               std::swap(LHS, RHS);
4769             }
4770             Left.push_back(LHS);
4771             Right.push_back(RHS);
4772           }
4773         }
4774         TE->setOperand(0, Left);
4775         TE->setOperand(1, Right);
4776         buildTree_rec(Left, Depth + 1, {TE, 0});
4777         buildTree_rec(Right, Depth + 1, {TE, 1});
4778         return;
4779       }
4780 
4781       TE->setOperandsInOrder();
4782       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4783         ValueList Operands;
4784         // Prepare the operand vector.
4785         for (Value *V : VL)
4786           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4787 
4788         buildTree_rec(Operands, Depth + 1, {TE, i});
4789       }
4790       return;
4791     }
4792     default:
4793       BS.cancelScheduling(VL, VL0);
4794       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4795                    ReuseShuffleIndicies);
4796       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4797       return;
4798   }
4799 }
4800 
4801 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4802   unsigned N = 1;
4803   Type *EltTy = T;
4804 
4805   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4806          isa<VectorType>(EltTy)) {
4807     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4808       // Check that struct is homogeneous.
4809       for (const auto *Ty : ST->elements())
4810         if (Ty != *ST->element_begin())
4811           return 0;
4812       N *= ST->getNumElements();
4813       EltTy = *ST->element_begin();
4814     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4815       N *= AT->getNumElements();
4816       EltTy = AT->getElementType();
4817     } else {
4818       auto *VT = cast<FixedVectorType>(EltTy);
4819       N *= VT->getNumElements();
4820       EltTy = VT->getElementType();
4821     }
4822   }
4823 
4824   if (!isValidElementType(EltTy))
4825     return 0;
4826   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4827   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4828     return 0;
4829   return N;
4830 }
4831 
4832 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4833                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4834   const auto *It = find_if(VL, [](Value *V) {
4835     return isa<ExtractElementInst, ExtractValueInst>(V);
4836   });
4837   assert(It != VL.end() && "Expected at least one extract instruction.");
4838   auto *E0 = cast<Instruction>(*It);
4839   assert(all_of(VL,
4840                 [](Value *V) {
4841                   return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
4842                       V);
4843                 }) &&
4844          "Invalid opcode");
4845   // Check if all of the extracts come from the same vector and from the
4846   // correct offset.
4847   Value *Vec = E0->getOperand(0);
4848 
4849   CurrentOrder.clear();
4850 
4851   // We have to extract from a vector/aggregate with the same number of elements.
4852   unsigned NElts;
4853   if (E0->getOpcode() == Instruction::ExtractValue) {
4854     const DataLayout &DL = E0->getModule()->getDataLayout();
4855     NElts = canMapToVector(Vec->getType(), DL);
4856     if (!NElts)
4857       return false;
4858     // Check if load can be rewritten as load of vector.
4859     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4860     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4861       return false;
4862   } else {
4863     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4864   }
4865 
4866   if (NElts != VL.size())
4867     return false;
4868 
4869   // Check that all of the indices extract from the correct offset.
4870   bool ShouldKeepOrder = true;
4871   unsigned E = VL.size();
4872   // Assign to all items the initial value E + 1 so we can check if the extract
4873   // instruction index was used already.
4874   // Also, later we can check that all the indices are used and we have a
4875   // consecutive access in the extract instructions, by checking that no
4876   // element of CurrentOrder still has value E + 1.
4877   CurrentOrder.assign(E, E);
4878   unsigned I = 0;
4879   for (; I < E; ++I) {
4880     auto *Inst = dyn_cast<Instruction>(VL[I]);
4881     if (!Inst)
4882       continue;
4883     if (Inst->getOperand(0) != Vec)
4884       break;
4885     if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
4886       if (isa<UndefValue>(EE->getIndexOperand()))
4887         continue;
4888     Optional<unsigned> Idx = getExtractIndex(Inst);
4889     if (!Idx)
4890       break;
4891     const unsigned ExtIdx = *Idx;
4892     if (ExtIdx != I) {
4893       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
4894         break;
4895       ShouldKeepOrder = false;
4896       CurrentOrder[ExtIdx] = I;
4897     } else {
4898       if (CurrentOrder[I] != E)
4899         break;
4900       CurrentOrder[I] = I;
4901     }
4902   }
4903   if (I < E) {
4904     CurrentOrder.clear();
4905     return false;
4906   }
4907   if (ShouldKeepOrder)
4908     CurrentOrder.clear();
4909 
4910   return ShouldKeepOrder;
4911 }
4912 
4913 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4914                                     ArrayRef<Value *> VectorizedVals) const {
4915   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4916          all_of(I->users(), [this](User *U) {
4917            return ScalarToTreeEntry.count(U) > 0 ||
4918                   isVectorLikeInstWithConstOps(U) ||
4919                   (isa<ExtractElementInst>(U) && MustGather.contains(U));
4920          });
4921 }
4922 
4923 static std::pair<InstructionCost, InstructionCost>
4924 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4925                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4926   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4927 
4928   // Calculate the cost of the scalar and vector calls.
4929   SmallVector<Type *, 4> VecTys;
4930   for (Use &Arg : CI->args())
4931     VecTys.push_back(
4932         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4933   FastMathFlags FMF;
4934   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4935     FMF = FPCI->getFastMathFlags();
4936   SmallVector<const Value *> Arguments(CI->args());
4937   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4938                                     dyn_cast<IntrinsicInst>(CI));
4939   auto IntrinsicCost =
4940     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4941 
4942   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4943                                      VecTy->getNumElements())),
4944                             false /*HasGlobalPred*/);
4945   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4946   auto LibCost = IntrinsicCost;
4947   if (!CI->isNoBuiltin() && VecFunc) {
4948     // Calculate the cost of the vector library call.
4949     // If the corresponding vector call is cheaper, return its cost.
4950     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4951                                     TTI::TCK_RecipThroughput);
4952   }
4953   return {IntrinsicCost, LibCost};
4954 }
4955 
4956 /// Compute the cost of creating a vector of type \p VecTy containing the
4957 /// extracted values from \p VL.
4958 static InstructionCost
4959 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4960                    TargetTransformInfo::ShuffleKind ShuffleKind,
4961                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4962   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4963 
4964   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4965       VecTy->getNumElements() < NumOfParts)
4966     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4967 
4968   bool AllConsecutive = true;
4969   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4970   unsigned Idx = -1;
4971   InstructionCost Cost = 0;
4972 
4973   // Process extracts in blocks of EltsPerVector to check if the source vector
4974   // operand can be re-used directly. If not, add the cost of creating a shuffle
4975   // to extract the values into a vector register.
4976   for (auto *V : VL) {
4977     ++Idx;
4978 
4979     // Need to exclude undefs from analysis.
4980     if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
4981       continue;
4982 
4983     // Reached the start of a new vector registers.
4984     if (Idx % EltsPerVector == 0) {
4985       AllConsecutive = true;
4986       continue;
4987     }
4988 
4989     // Check all extracts for a vector register on the target directly
4990     // extract values in order.
4991     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4992     if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
4993       unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4994       AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4995                         CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4996     }
4997 
4998     if (AllConsecutive)
4999       continue;
5000 
5001     // Skip all indices, except for the last index per vector block.
5002     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
5003       continue;
5004 
5005     // If we have a series of extracts which are not consecutive and hence
5006     // cannot re-use the source vector register directly, compute the shuffle
5007     // cost to extract the a vector with EltsPerVector elements.
5008     Cost += TTI.getShuffleCost(
5009         TargetTransformInfo::SK_PermuteSingleSrc,
5010         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
5011   }
5012   return Cost;
5013 }
5014 
5015 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
5016 /// operations operands.
5017 static void
5018 buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
5019                       ArrayRef<int> ReusesIndices,
5020                       const function_ref<bool(Instruction *)> IsAltOp,
5021                       SmallVectorImpl<int> &Mask,
5022                       SmallVectorImpl<Value *> *OpScalars = nullptr,
5023                       SmallVectorImpl<Value *> *AltScalars = nullptr) {
5024   unsigned Sz = VL.size();
5025   Mask.assign(Sz, UndefMaskElem);
5026   SmallVector<int> OrderMask;
5027   if (!ReorderIndices.empty())
5028     inversePermutation(ReorderIndices, OrderMask);
5029   for (unsigned I = 0; I < Sz; ++I) {
5030     unsigned Idx = I;
5031     if (!ReorderIndices.empty())
5032       Idx = OrderMask[I];
5033     auto *OpInst = cast<Instruction>(VL[Idx]);
5034     if (IsAltOp(OpInst)) {
5035       Mask[I] = Sz + Idx;
5036       if (AltScalars)
5037         AltScalars->push_back(OpInst);
5038     } else {
5039       Mask[I] = Idx;
5040       if (OpScalars)
5041         OpScalars->push_back(OpInst);
5042     }
5043   }
5044   if (!ReusesIndices.empty()) {
5045     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
5046     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
5047       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
5048     });
5049     Mask.swap(NewMask);
5050   }
5051 }
5052 
5053 /// Checks if the specified instruction \p I is an alternate operation for the
5054 /// given \p MainOp and \p AltOp instructions.
5055 static bool isAlternateInstruction(const Instruction *I,
5056                                    const Instruction *MainOp,
5057                                    const Instruction *AltOp) {
5058   if (auto *CI0 = dyn_cast<CmpInst>(MainOp)) {
5059     auto *AltCI0 = cast<CmpInst>(AltOp);
5060     auto *CI = cast<CmpInst>(I);
5061     CmpInst::Predicate P0 = CI0->getPredicate();
5062     CmpInst::Predicate AltP0 = AltCI0->getPredicate();
5063     assert(P0 != AltP0 && "Expected different main/alternate predicates.");
5064     CmpInst::Predicate AltP0Swapped = CmpInst::getSwappedPredicate(AltP0);
5065     CmpInst::Predicate CurrentPred = CI->getPredicate();
5066     if (P0 == AltP0Swapped)
5067       return I == AltCI0 ||
5068              (I != MainOp &&
5069               !areCompatibleCmpOps(CI0->getOperand(0), CI0->getOperand(1),
5070                                    CI->getOperand(0), CI->getOperand(1)));
5071     return AltP0 == CurrentPred || AltP0Swapped == CurrentPred;
5072   }
5073   return I->getOpcode() == AltOp->getOpcode();
5074 }
5075 
5076 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
5077                                       ArrayRef<Value *> VectorizedVals) {
5078   ArrayRef<Value*> VL = E->Scalars;
5079 
5080   Type *ScalarTy = VL[0]->getType();
5081   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5082     ScalarTy = SI->getValueOperand()->getType();
5083   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
5084     ScalarTy = CI->getOperand(0)->getType();
5085   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
5086     ScalarTy = IE->getOperand(1)->getType();
5087   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5088   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
5089 
5090   // If we have computed a smaller type for the expression, update VecTy so
5091   // that the costs will be accurate.
5092   if (MinBWs.count(VL[0]))
5093     VecTy = FixedVectorType::get(
5094         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
5095   unsigned EntryVF = E->getVectorFactor();
5096   auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
5097 
5098   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5099   // FIXME: it tries to fix a problem with MSVC buildbots.
5100   TargetTransformInfo &TTIRef = *TTI;
5101   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
5102                                VectorizedVals, E](InstructionCost &Cost) {
5103     DenseMap<Value *, int> ExtractVectorsTys;
5104     SmallPtrSet<Value *, 4> CheckedExtracts;
5105     for (auto *V : VL) {
5106       if (isa<UndefValue>(V))
5107         continue;
5108       // If all users of instruction are going to be vectorized and this
5109       // instruction itself is not going to be vectorized, consider this
5110       // instruction as dead and remove its cost from the final cost of the
5111       // vectorized tree.
5112       // Also, avoid adjusting the cost for extractelements with multiple uses
5113       // in different graph entries.
5114       const TreeEntry *VE = getTreeEntry(V);
5115       if (!CheckedExtracts.insert(V).second ||
5116           !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
5117           (VE && VE != E))
5118         continue;
5119       auto *EE = cast<ExtractElementInst>(V);
5120       Optional<unsigned> EEIdx = getExtractIndex(EE);
5121       if (!EEIdx)
5122         continue;
5123       unsigned Idx = *EEIdx;
5124       if (TTIRef.getNumberOfParts(VecTy) !=
5125           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
5126         auto It =
5127             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
5128         It->getSecond() = std::min<int>(It->second, Idx);
5129       }
5130       // Take credit for instruction that will become dead.
5131       if (EE->hasOneUse()) {
5132         Instruction *Ext = EE->user_back();
5133         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5134             all_of(Ext->users(),
5135                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
5136           // Use getExtractWithExtendCost() to calculate the cost of
5137           // extractelement/ext pair.
5138           Cost -=
5139               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
5140                                               EE->getVectorOperandType(), Idx);
5141           // Add back the cost of s|zext which is subtracted separately.
5142           Cost += TTIRef.getCastInstrCost(
5143               Ext->getOpcode(), Ext->getType(), EE->getType(),
5144               TTI::getCastContextHint(Ext), CostKind, Ext);
5145           continue;
5146         }
5147       }
5148       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
5149                                         EE->getVectorOperandType(), Idx);
5150     }
5151     // Add a cost for subvector extracts/inserts if required.
5152     for (const auto &Data : ExtractVectorsTys) {
5153       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
5154       unsigned NumElts = VecTy->getNumElements();
5155       if (Data.second % NumElts == 0)
5156         continue;
5157       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
5158         unsigned Idx = (Data.second / NumElts) * NumElts;
5159         unsigned EENumElts = EEVTy->getNumElements();
5160         if (Idx + NumElts <= EENumElts) {
5161           Cost +=
5162               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5163                                     EEVTy, None, Idx, VecTy);
5164         } else {
5165           // Need to round up the subvector type vectorization factor to avoid a
5166           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
5167           // <= EENumElts.
5168           auto *SubVT =
5169               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
5170           Cost +=
5171               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
5172                                     EEVTy, None, Idx, SubVT);
5173         }
5174       } else {
5175         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
5176                                       VecTy, None, 0, EEVTy);
5177       }
5178     }
5179   };
5180   if (E->State == TreeEntry::NeedToGather) {
5181     if (allConstant(VL))
5182       return 0;
5183     if (isa<InsertElementInst>(VL[0]))
5184       return InstructionCost::getInvalid();
5185     SmallVector<int> Mask;
5186     SmallVector<const TreeEntry *> Entries;
5187     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5188         isGatherShuffledEntry(E, Mask, Entries);
5189     if (Shuffle.hasValue()) {
5190       InstructionCost GatherCost = 0;
5191       if (ShuffleVectorInst::isIdentityMask(Mask)) {
5192         // Perfect match in the graph, will reuse the previously vectorized
5193         // node. Cost is 0.
5194         LLVM_DEBUG(
5195             dbgs()
5196             << "SLP: perfect diamond match for gather bundle that starts with "
5197             << *VL.front() << ".\n");
5198         if (NeedToShuffleReuses)
5199           GatherCost =
5200               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5201                                   FinalVecTy, E->ReuseShuffleIndices);
5202       } else {
5203         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
5204                           << " entries for bundle that starts with "
5205                           << *VL.front() << ".\n");
5206         // Detected that instead of gather we can emit a shuffle of single/two
5207         // previously vectorized nodes. Add the cost of the permutation rather
5208         // than gather.
5209         ::addMask(Mask, E->ReuseShuffleIndices);
5210         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
5211       }
5212       return GatherCost;
5213     }
5214     if ((E->getOpcode() == Instruction::ExtractElement ||
5215          all_of(E->Scalars,
5216                 [](Value *V) {
5217                   return isa<ExtractElementInst, UndefValue>(V);
5218                 })) &&
5219         allSameType(VL)) {
5220       // Check that gather of extractelements can be represented as just a
5221       // shuffle of a single/two vectors the scalars are extracted from.
5222       SmallVector<int> Mask;
5223       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
5224           isFixedVectorShuffle(VL, Mask);
5225       if (ShuffleKind.hasValue()) {
5226         // Found the bunch of extractelement instructions that must be gathered
5227         // into a vector and can be represented as a permutation elements in a
5228         // single input vector or of 2 input vectors.
5229         InstructionCost Cost =
5230             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
5231         AdjustExtractsCost(Cost);
5232         if (NeedToShuffleReuses)
5233           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
5234                                       FinalVecTy, E->ReuseShuffleIndices);
5235         return Cost;
5236       }
5237     }
5238     if (isSplat(VL)) {
5239       // Found the broadcasting of the single scalar, calculate the cost as the
5240       // broadcast.
5241       assert(VecTy == FinalVecTy &&
5242              "No reused scalars expected for broadcast.");
5243       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
5244     }
5245     InstructionCost ReuseShuffleCost = 0;
5246     if (NeedToShuffleReuses)
5247       ReuseShuffleCost = TTI->getShuffleCost(
5248           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
5249     // Improve gather cost for gather of loads, if we can group some of the
5250     // loads into vector loads.
5251     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
5252         !E->isAltShuffle()) {
5253       BoUpSLP::ValueSet VectorizedLoads;
5254       unsigned StartIdx = 0;
5255       unsigned VF = VL.size() / 2;
5256       unsigned VectorizedCnt = 0;
5257       unsigned ScatterVectorizeCnt = 0;
5258       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
5259       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
5260         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
5261              Cnt += VF) {
5262           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
5263           if (!VectorizedLoads.count(Slice.front()) &&
5264               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
5265             SmallVector<Value *> PointerOps;
5266             OrdersType CurrentOrder;
5267             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
5268                                               *SE, CurrentOrder, PointerOps);
5269             switch (LS) {
5270             case LoadsState::Vectorize:
5271             case LoadsState::ScatterVectorize:
5272               // Mark the vectorized loads so that we don't vectorize them
5273               // again.
5274               if (LS == LoadsState::Vectorize)
5275                 ++VectorizedCnt;
5276               else
5277                 ++ScatterVectorizeCnt;
5278               VectorizedLoads.insert(Slice.begin(), Slice.end());
5279               // If we vectorized initial block, no need to try to vectorize it
5280               // again.
5281               if (Cnt == StartIdx)
5282                 StartIdx += VF;
5283               break;
5284             case LoadsState::Gather:
5285               break;
5286             }
5287           }
5288         }
5289         // Check if the whole array was vectorized already - exit.
5290         if (StartIdx >= VL.size())
5291           break;
5292         // Found vectorizable parts - exit.
5293         if (!VectorizedLoads.empty())
5294           break;
5295       }
5296       if (!VectorizedLoads.empty()) {
5297         InstructionCost GatherCost = 0;
5298         unsigned NumParts = TTI->getNumberOfParts(VecTy);
5299         bool NeedInsertSubvectorAnalysis =
5300             !NumParts || (VL.size() / VF) > NumParts;
5301         // Get the cost for gathered loads.
5302         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
5303           if (VectorizedLoads.contains(VL[I]))
5304             continue;
5305           GatherCost += getGatherCost(VL.slice(I, VF));
5306         }
5307         // The cost for vectorized loads.
5308         InstructionCost ScalarsCost = 0;
5309         for (Value *V : VectorizedLoads) {
5310           auto *LI = cast<LoadInst>(V);
5311           ScalarsCost += TTI->getMemoryOpCost(
5312               Instruction::Load, LI->getType(), LI->getAlign(),
5313               LI->getPointerAddressSpace(), CostKind, LI);
5314         }
5315         auto *LI = cast<LoadInst>(E->getMainOp());
5316         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
5317         Align Alignment = LI->getAlign();
5318         GatherCost +=
5319             VectorizedCnt *
5320             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
5321                                  LI->getPointerAddressSpace(), CostKind, LI);
5322         GatherCost += ScatterVectorizeCnt *
5323                       TTI->getGatherScatterOpCost(
5324                           Instruction::Load, LoadTy, LI->getPointerOperand(),
5325                           /*VariableMask=*/false, Alignment, CostKind, LI);
5326         if (NeedInsertSubvectorAnalysis) {
5327           // Add the cost for the subvectors insert.
5328           for (int I = VF, E = VL.size(); I < E; I += VF)
5329             GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
5330                                               None, I, LoadTy);
5331         }
5332         return ReuseShuffleCost + GatherCost - ScalarsCost;
5333       }
5334     }
5335     return ReuseShuffleCost + getGatherCost(VL);
5336   }
5337   InstructionCost CommonCost = 0;
5338   SmallVector<int> Mask;
5339   if (!E->ReorderIndices.empty()) {
5340     SmallVector<int> NewMask;
5341     if (E->getOpcode() == Instruction::Store) {
5342       // For stores the order is actually a mask.
5343       NewMask.resize(E->ReorderIndices.size());
5344       copy(E->ReorderIndices, NewMask.begin());
5345     } else {
5346       inversePermutation(E->ReorderIndices, NewMask);
5347     }
5348     ::addMask(Mask, NewMask);
5349   }
5350   if (NeedToShuffleReuses)
5351     ::addMask(Mask, E->ReuseShuffleIndices);
5352   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
5353     CommonCost =
5354         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
5355   assert((E->State == TreeEntry::Vectorize ||
5356           E->State == TreeEntry::ScatterVectorize) &&
5357          "Unhandled state");
5358   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
5359   Instruction *VL0 = E->getMainOp();
5360   unsigned ShuffleOrOp =
5361       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5362   switch (ShuffleOrOp) {
5363     case Instruction::PHI:
5364       return 0;
5365 
5366     case Instruction::ExtractValue:
5367     case Instruction::ExtractElement: {
5368       // The common cost of removal ExtractElement/ExtractValue instructions +
5369       // the cost of shuffles, if required to resuffle the original vector.
5370       if (NeedToShuffleReuses) {
5371         unsigned Idx = 0;
5372         for (unsigned I : E->ReuseShuffleIndices) {
5373           if (ShuffleOrOp == Instruction::ExtractElement) {
5374             auto *EE = cast<ExtractElementInst>(VL[I]);
5375             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5376                                                   EE->getVectorOperandType(),
5377                                                   *getExtractIndex(EE));
5378           } else {
5379             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
5380                                                   VecTy, Idx);
5381             ++Idx;
5382           }
5383         }
5384         Idx = EntryVF;
5385         for (Value *V : VL) {
5386           if (ShuffleOrOp == Instruction::ExtractElement) {
5387             auto *EE = cast<ExtractElementInst>(V);
5388             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5389                                                   EE->getVectorOperandType(),
5390                                                   *getExtractIndex(EE));
5391           } else {
5392             --Idx;
5393             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
5394                                                   VecTy, Idx);
5395           }
5396         }
5397       }
5398       if (ShuffleOrOp == Instruction::ExtractValue) {
5399         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
5400           auto *EI = cast<Instruction>(VL[I]);
5401           // Take credit for instruction that will become dead.
5402           if (EI->hasOneUse()) {
5403             Instruction *Ext = EI->user_back();
5404             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
5405                 all_of(Ext->users(),
5406                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
5407               // Use getExtractWithExtendCost() to calculate the cost of
5408               // extractelement/ext pair.
5409               CommonCost -= TTI->getExtractWithExtendCost(
5410                   Ext->getOpcode(), Ext->getType(), VecTy, I);
5411               // Add back the cost of s|zext which is subtracted separately.
5412               CommonCost += TTI->getCastInstrCost(
5413                   Ext->getOpcode(), Ext->getType(), EI->getType(),
5414                   TTI::getCastContextHint(Ext), CostKind, Ext);
5415               continue;
5416             }
5417           }
5418           CommonCost -=
5419               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
5420         }
5421       } else {
5422         AdjustExtractsCost(CommonCost);
5423       }
5424       return CommonCost;
5425     }
5426     case Instruction::InsertElement: {
5427       assert(E->ReuseShuffleIndices.empty() &&
5428              "Unique insertelements only are expected.");
5429       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
5430 
5431       unsigned const NumElts = SrcVecTy->getNumElements();
5432       unsigned const NumScalars = VL.size();
5433       APInt DemandedElts = APInt::getZero(NumElts);
5434       // TODO: Add support for Instruction::InsertValue.
5435       SmallVector<int> Mask;
5436       if (!E->ReorderIndices.empty()) {
5437         inversePermutation(E->ReorderIndices, Mask);
5438         Mask.append(NumElts - NumScalars, UndefMaskElem);
5439       } else {
5440         Mask.assign(NumElts, UndefMaskElem);
5441         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
5442       }
5443       unsigned Offset = *getInsertIndex(VL0);
5444       bool IsIdentity = true;
5445       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
5446       Mask.swap(PrevMask);
5447       for (unsigned I = 0; I < NumScalars; ++I) {
5448         unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
5449         DemandedElts.setBit(InsertIdx);
5450         IsIdentity &= InsertIdx - Offset == I;
5451         Mask[InsertIdx - Offset] = I;
5452       }
5453       assert(Offset < NumElts && "Failed to find vector index offset");
5454 
5455       InstructionCost Cost = 0;
5456       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
5457                                             /*Insert*/ true, /*Extract*/ false);
5458 
5459       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
5460         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
5461         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
5462         Cost += TTI->getShuffleCost(
5463             TargetTransformInfo::SK_PermuteSingleSrc,
5464             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
5465       } else if (!IsIdentity) {
5466         auto *FirstInsert =
5467             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5468               return !is_contained(E->Scalars,
5469                                    cast<Instruction>(V)->getOperand(0));
5470             }));
5471         if (isUndefVector(FirstInsert->getOperand(0))) {
5472           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
5473         } else {
5474           SmallVector<int> InsertMask(NumElts);
5475           std::iota(InsertMask.begin(), InsertMask.end(), 0);
5476           for (unsigned I = 0; I < NumElts; I++) {
5477             if (Mask[I] != UndefMaskElem)
5478               InsertMask[Offset + I] = NumElts + I;
5479           }
5480           Cost +=
5481               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
5482         }
5483       }
5484 
5485       return Cost;
5486     }
5487     case Instruction::ZExt:
5488     case Instruction::SExt:
5489     case Instruction::FPToUI:
5490     case Instruction::FPToSI:
5491     case Instruction::FPExt:
5492     case Instruction::PtrToInt:
5493     case Instruction::IntToPtr:
5494     case Instruction::SIToFP:
5495     case Instruction::UIToFP:
5496     case Instruction::Trunc:
5497     case Instruction::FPTrunc:
5498     case Instruction::BitCast: {
5499       Type *SrcTy = VL0->getOperand(0)->getType();
5500       InstructionCost ScalarEltCost =
5501           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
5502                                 TTI::getCastContextHint(VL0), CostKind, VL0);
5503       if (NeedToShuffleReuses) {
5504         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5505       }
5506 
5507       // Calculate the cost of this instruction.
5508       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
5509 
5510       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
5511       InstructionCost VecCost = 0;
5512       // Check if the values are candidates to demote.
5513       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
5514         VecCost = CommonCost + TTI->getCastInstrCost(
5515                                    E->getOpcode(), VecTy, SrcVecTy,
5516                                    TTI::getCastContextHint(VL0), CostKind, VL0);
5517       }
5518       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5519       return VecCost - ScalarCost;
5520     }
5521     case Instruction::FCmp:
5522     case Instruction::ICmp:
5523     case Instruction::Select: {
5524       // Calculate the cost of this instruction.
5525       InstructionCost ScalarEltCost =
5526           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5527                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
5528       if (NeedToShuffleReuses) {
5529         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5530       }
5531       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
5532       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5533 
5534       // Check if all entries in VL are either compares or selects with compares
5535       // as condition that have the same predicates.
5536       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
5537       bool First = true;
5538       for (auto *V : VL) {
5539         CmpInst::Predicate CurrentPred;
5540         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
5541         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
5542              !match(V, MatchCmp)) ||
5543             (!First && VecPred != CurrentPred)) {
5544           VecPred = CmpInst::BAD_ICMP_PREDICATE;
5545           break;
5546         }
5547         First = false;
5548         VecPred = CurrentPred;
5549       }
5550 
5551       InstructionCost VecCost = TTI->getCmpSelInstrCost(
5552           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
5553       // Check if it is possible and profitable to use min/max for selects in
5554       // VL.
5555       //
5556       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
5557       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
5558         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
5559                                           {VecTy, VecTy});
5560         InstructionCost IntrinsicCost =
5561             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5562         // If the selects are the only uses of the compares, they will be dead
5563         // and we can adjust the cost by removing their cost.
5564         if (IntrinsicAndUse.second)
5565           IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
5566                                                    MaskTy, VecPred, CostKind);
5567         VecCost = std::min(VecCost, IntrinsicCost);
5568       }
5569       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5570       return CommonCost + VecCost - ScalarCost;
5571     }
5572     case Instruction::FNeg:
5573     case Instruction::Add:
5574     case Instruction::FAdd:
5575     case Instruction::Sub:
5576     case Instruction::FSub:
5577     case Instruction::Mul:
5578     case Instruction::FMul:
5579     case Instruction::UDiv:
5580     case Instruction::SDiv:
5581     case Instruction::FDiv:
5582     case Instruction::URem:
5583     case Instruction::SRem:
5584     case Instruction::FRem:
5585     case Instruction::Shl:
5586     case Instruction::LShr:
5587     case Instruction::AShr:
5588     case Instruction::And:
5589     case Instruction::Or:
5590     case Instruction::Xor: {
5591       // Certain instructions can be cheaper to vectorize if they have a
5592       // constant second vector operand.
5593       TargetTransformInfo::OperandValueKind Op1VK =
5594           TargetTransformInfo::OK_AnyValue;
5595       TargetTransformInfo::OperandValueKind Op2VK =
5596           TargetTransformInfo::OK_UniformConstantValue;
5597       TargetTransformInfo::OperandValueProperties Op1VP =
5598           TargetTransformInfo::OP_None;
5599       TargetTransformInfo::OperandValueProperties Op2VP =
5600           TargetTransformInfo::OP_PowerOf2;
5601 
5602       // If all operands are exactly the same ConstantInt then set the
5603       // operand kind to OK_UniformConstantValue.
5604       // If instead not all operands are constants, then set the operand kind
5605       // to OK_AnyValue. If all operands are constants but not the same,
5606       // then set the operand kind to OK_NonUniformConstantValue.
5607       ConstantInt *CInt0 = nullptr;
5608       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
5609         const Instruction *I = cast<Instruction>(VL[i]);
5610         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
5611         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
5612         if (!CInt) {
5613           Op2VK = TargetTransformInfo::OK_AnyValue;
5614           Op2VP = TargetTransformInfo::OP_None;
5615           break;
5616         }
5617         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
5618             !CInt->getValue().isPowerOf2())
5619           Op2VP = TargetTransformInfo::OP_None;
5620         if (i == 0) {
5621           CInt0 = CInt;
5622           continue;
5623         }
5624         if (CInt0 != CInt)
5625           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
5626       }
5627 
5628       SmallVector<const Value *, 4> Operands(VL0->operand_values());
5629       InstructionCost ScalarEltCost =
5630           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
5631                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5632       if (NeedToShuffleReuses) {
5633         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5634       }
5635       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5636       InstructionCost VecCost =
5637           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
5638                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
5639       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5640       return CommonCost + VecCost - ScalarCost;
5641     }
5642     case Instruction::GetElementPtr: {
5643       TargetTransformInfo::OperandValueKind Op1VK =
5644           TargetTransformInfo::OK_AnyValue;
5645       TargetTransformInfo::OperandValueKind Op2VK =
5646           TargetTransformInfo::OK_UniformConstantValue;
5647 
5648       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
5649           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
5650       if (NeedToShuffleReuses) {
5651         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5652       }
5653       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
5654       InstructionCost VecCost = TTI->getArithmeticInstrCost(
5655           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
5656       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5657       return CommonCost + VecCost - ScalarCost;
5658     }
5659     case Instruction::Load: {
5660       // Cost of wide load - cost of scalar loads.
5661       Align Alignment = cast<LoadInst>(VL0)->getAlign();
5662       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5663           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
5664       if (NeedToShuffleReuses) {
5665         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5666       }
5667       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
5668       InstructionCost VecLdCost;
5669       if (E->State == TreeEntry::Vectorize) {
5670         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
5671                                          CostKind, VL0);
5672       } else {
5673         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
5674         Align CommonAlignment = Alignment;
5675         for (Value *V : VL)
5676           CommonAlignment =
5677               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
5678         VecLdCost = TTI->getGatherScatterOpCost(
5679             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
5680             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
5681       }
5682       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
5683       return CommonCost + VecLdCost - ScalarLdCost;
5684     }
5685     case Instruction::Store: {
5686       // We know that we can merge the stores. Calculate the cost.
5687       bool IsReorder = !E->ReorderIndices.empty();
5688       auto *SI =
5689           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
5690       Align Alignment = SI->getAlign();
5691       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
5692           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
5693       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
5694       InstructionCost VecStCost = TTI->getMemoryOpCost(
5695           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
5696       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
5697       return CommonCost + VecStCost - ScalarStCost;
5698     }
5699     case Instruction::Call: {
5700       CallInst *CI = cast<CallInst>(VL0);
5701       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
5702 
5703       // Calculate the cost of the scalar and vector calls.
5704       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
5705       InstructionCost ScalarEltCost =
5706           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
5707       if (NeedToShuffleReuses) {
5708         CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
5709       }
5710       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
5711 
5712       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
5713       InstructionCost VecCallCost =
5714           std::min(VecCallCosts.first, VecCallCosts.second);
5715 
5716       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
5717                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
5718                         << " for " << *CI << "\n");
5719 
5720       return CommonCost + VecCallCost - ScalarCallCost;
5721     }
5722     case Instruction::ShuffleVector: {
5723       assert(E->isAltShuffle() &&
5724              ((Instruction::isBinaryOp(E->getOpcode()) &&
5725                Instruction::isBinaryOp(E->getAltOpcode())) ||
5726               (Instruction::isCast(E->getOpcode()) &&
5727                Instruction::isCast(E->getAltOpcode())) ||
5728               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
5729              "Invalid Shuffle Vector Operand");
5730       InstructionCost ScalarCost = 0;
5731       if (NeedToShuffleReuses) {
5732         for (unsigned Idx : E->ReuseShuffleIndices) {
5733           Instruction *I = cast<Instruction>(VL[Idx]);
5734           CommonCost -= TTI->getInstructionCost(I, CostKind);
5735         }
5736         for (Value *V : VL) {
5737           Instruction *I = cast<Instruction>(V);
5738           CommonCost += TTI->getInstructionCost(I, CostKind);
5739         }
5740       }
5741       for (Value *V : VL) {
5742         Instruction *I = cast<Instruction>(V);
5743         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5744         ScalarCost += TTI->getInstructionCost(I, CostKind);
5745       }
5746       // VecCost is equal to sum of the cost of creating 2 vectors
5747       // and the cost of creating shuffle.
5748       InstructionCost VecCost = 0;
5749       // Try to find the previous shuffle node with the same operands and same
5750       // main/alternate ops.
5751       auto &&TryFindNodeWithEqualOperands = [this, E]() {
5752         for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
5753           if (TE.get() == E)
5754             break;
5755           if (TE->isAltShuffle() &&
5756               ((TE->getOpcode() == E->getOpcode() &&
5757                 TE->getAltOpcode() == E->getAltOpcode()) ||
5758                (TE->getOpcode() == E->getAltOpcode() &&
5759                 TE->getAltOpcode() == E->getOpcode())) &&
5760               TE->hasEqualOperands(*E))
5761             return true;
5762         }
5763         return false;
5764       };
5765       if (TryFindNodeWithEqualOperands()) {
5766         LLVM_DEBUG({
5767           dbgs() << "SLP: diamond match for alternate node found.\n";
5768           E->dump();
5769         });
5770         // No need to add new vector costs here since we're going to reuse
5771         // same main/alternate vector ops, just do different shuffling.
5772       } else if (Instruction::isBinaryOp(E->getOpcode())) {
5773         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
5774         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
5775                                                CostKind);
5776       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
5777         VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
5778                                           Builder.getInt1Ty(),
5779                                           CI0->getPredicate(), CostKind, VL0);
5780         VecCost += TTI->getCmpSelInstrCost(
5781             E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
5782             cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
5783             E->getAltOp());
5784       } else {
5785         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
5786         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
5787         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
5788         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
5789         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
5790                                         TTI::CastContextHint::None, CostKind);
5791         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
5792                                          TTI::CastContextHint::None, CostKind);
5793       }
5794 
5795       SmallVector<int> Mask;
5796       buildShuffleEntryMask(
5797           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
5798           [E](Instruction *I) {
5799             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
5800             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
5801           },
5802           Mask);
5803       CommonCost =
5804           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
5805       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
5806       return CommonCost + VecCost - ScalarCost;
5807     }
5808     default:
5809       llvm_unreachable("Unknown instruction");
5810   }
5811 }
5812 
5813 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5814   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5815                     << VectorizableTree.size() << " is fully vectorizable .\n");
5816 
5817   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5818     SmallVector<int> Mask;
5819     return TE->State == TreeEntry::NeedToGather &&
5820            !any_of(TE->Scalars,
5821                    [this](Value *V) { return EphValues.contains(V); }) &&
5822            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5823             TE->Scalars.size() < Limit ||
5824             ((TE->getOpcode() == Instruction::ExtractElement ||
5825               all_of(TE->Scalars,
5826                      [](Value *V) {
5827                        return isa<ExtractElementInst, UndefValue>(V);
5828                      })) &&
5829              isFixedVectorShuffle(TE->Scalars, Mask)) ||
5830             (TE->State == TreeEntry::NeedToGather &&
5831              TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
5832   };
5833 
5834   // We only handle trees of heights 1 and 2.
5835   if (VectorizableTree.size() == 1 &&
5836       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5837        (ForReduction &&
5838         AreVectorizableGathers(VectorizableTree[0].get(),
5839                                VectorizableTree[0]->Scalars.size()) &&
5840         VectorizableTree[0]->getVectorFactor() > 2)))
5841     return true;
5842 
5843   if (VectorizableTree.size() != 2)
5844     return false;
5845 
5846   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5847   // with the second gather nodes if they have less scalar operands rather than
5848   // the initial tree element (may be profitable to shuffle the second gather)
5849   // or they are extractelements, which form shuffle.
5850   SmallVector<int> Mask;
5851   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5852       AreVectorizableGathers(VectorizableTree[1].get(),
5853                              VectorizableTree[0]->Scalars.size()))
5854     return true;
5855 
5856   // Gathering cost would be too much for tiny trees.
5857   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5858       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5859        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5860     return false;
5861 
5862   return true;
5863 }
5864 
5865 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5866                                        TargetTransformInfo *TTI,
5867                                        bool MustMatchOrInst) {
5868   // Look past the root to find a source value. Arbitrarily follow the
5869   // path through operand 0 of any 'or'. Also, peek through optional
5870   // shift-left-by-multiple-of-8-bits.
5871   Value *ZextLoad = Root;
5872   const APInt *ShAmtC;
5873   bool FoundOr = false;
5874   while (!isa<ConstantExpr>(ZextLoad) &&
5875          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5876           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5877            ShAmtC->urem(8) == 0))) {
5878     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5879     ZextLoad = BinOp->getOperand(0);
5880     if (BinOp->getOpcode() == Instruction::Or)
5881       FoundOr = true;
5882   }
5883   // Check if the input is an extended load of the required or/shift expression.
5884   Value *Load;
5885   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5886       !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
5887     return false;
5888 
5889   // Require that the total load bit width is a legal integer type.
5890   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5891   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5892   Type *SrcTy = Load->getType();
5893   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5894   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5895     return false;
5896 
5897   // Everything matched - assume that we can fold the whole sequence using
5898   // load combining.
5899   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5900              << *(cast<Instruction>(Root)) << "\n");
5901 
5902   return true;
5903 }
5904 
5905 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5906   if (RdxKind != RecurKind::Or)
5907     return false;
5908 
5909   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5910   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5911   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5912                                     /* MatchOr */ false);
5913 }
5914 
5915 bool BoUpSLP::isLoadCombineCandidate() const {
5916   // Peek through a final sequence of stores and check if all operations are
5917   // likely to be load-combined.
5918   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5919   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5920     Value *X;
5921     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5922         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5923       return false;
5924   }
5925   return true;
5926 }
5927 
5928 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5929   // No need to vectorize inserts of gathered values.
5930   if (VectorizableTree.size() == 2 &&
5931       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5932       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5933     return true;
5934 
5935   // We can vectorize the tree if its size is greater than or equal to the
5936   // minimum size specified by the MinTreeSize command line option.
5937   if (VectorizableTree.size() >= MinTreeSize)
5938     return false;
5939 
5940   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5941   // can vectorize it if we can prove it fully vectorizable.
5942   if (isFullyVectorizableTinyTree(ForReduction))
5943     return false;
5944 
5945   assert(VectorizableTree.empty()
5946              ? ExternalUses.empty()
5947              : true && "We shouldn't have any external users");
5948 
5949   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5950   // vectorizable.
5951   return true;
5952 }
5953 
5954 InstructionCost BoUpSLP::getSpillCost() const {
5955   // Walk from the bottom of the tree to the top, tracking which values are
5956   // live. When we see a call instruction that is not part of our tree,
5957   // query TTI to see if there is a cost to keeping values live over it
5958   // (for example, if spills and fills are required).
5959   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5960   InstructionCost Cost = 0;
5961 
5962   SmallPtrSet<Instruction*, 4> LiveValues;
5963   Instruction *PrevInst = nullptr;
5964 
5965   // The entries in VectorizableTree are not necessarily ordered by their
5966   // position in basic blocks. Collect them and order them by dominance so later
5967   // instructions are guaranteed to be visited first. For instructions in
5968   // different basic blocks, we only scan to the beginning of the block, so
5969   // their order does not matter, as long as all instructions in a basic block
5970   // are grouped together. Using dominance ensures a deterministic order.
5971   SmallVector<Instruction *, 16> OrderedScalars;
5972   for (const auto &TEPtr : VectorizableTree) {
5973     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5974     if (!Inst)
5975       continue;
5976     OrderedScalars.push_back(Inst);
5977   }
5978   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5979     auto *NodeA = DT->getNode(A->getParent());
5980     auto *NodeB = DT->getNode(B->getParent());
5981     assert(NodeA && "Should only process reachable instructions");
5982     assert(NodeB && "Should only process reachable instructions");
5983     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5984            "Different nodes should have different DFS numbers");
5985     if (NodeA != NodeB)
5986       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5987     return B->comesBefore(A);
5988   });
5989 
5990   for (Instruction *Inst : OrderedScalars) {
5991     if (!PrevInst) {
5992       PrevInst = Inst;
5993       continue;
5994     }
5995 
5996     // Update LiveValues.
5997     LiveValues.erase(PrevInst);
5998     for (auto &J : PrevInst->operands()) {
5999       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
6000         LiveValues.insert(cast<Instruction>(&*J));
6001     }
6002 
6003     LLVM_DEBUG({
6004       dbgs() << "SLP: #LV: " << LiveValues.size();
6005       for (auto *X : LiveValues)
6006         dbgs() << " " << X->getName();
6007       dbgs() << ", Looking at ";
6008       Inst->dump();
6009     });
6010 
6011     // Now find the sequence of instructions between PrevInst and Inst.
6012     unsigned NumCalls = 0;
6013     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
6014                                  PrevInstIt =
6015                                      PrevInst->getIterator().getReverse();
6016     while (InstIt != PrevInstIt) {
6017       if (PrevInstIt == PrevInst->getParent()->rend()) {
6018         PrevInstIt = Inst->getParent()->rbegin();
6019         continue;
6020       }
6021 
6022       // Debug information does not impact spill cost.
6023       if ((isa<CallInst>(&*PrevInstIt) &&
6024            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
6025           &*PrevInstIt != PrevInst)
6026         NumCalls++;
6027 
6028       ++PrevInstIt;
6029     }
6030 
6031     if (NumCalls) {
6032       SmallVector<Type*, 4> V;
6033       for (auto *II : LiveValues) {
6034         auto *ScalarTy = II->getType();
6035         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
6036           ScalarTy = VectorTy->getElementType();
6037         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
6038       }
6039       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
6040     }
6041 
6042     PrevInst = Inst;
6043   }
6044 
6045   return Cost;
6046 }
6047 
6048 /// Check if two insertelement instructions are from the same buildvector.
6049 static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
6050                                             InsertElementInst *V) {
6051   // Instructions must be from the same basic blocks.
6052   if (VU->getParent() != V->getParent())
6053     return false;
6054   // Checks if 2 insertelements are from the same buildvector.
6055   if (VU->getType() != V->getType())
6056     return false;
6057   // Multiple used inserts are separate nodes.
6058   if (!VU->hasOneUse() && !V->hasOneUse())
6059     return false;
6060   auto *IE1 = VU;
6061   auto *IE2 = V;
6062   // Go through the vector operand of insertelement instructions trying to find
6063   // either VU as the original vector for IE2 or V as the original vector for
6064   // IE1.
6065   do {
6066     if (IE2 == VU || IE1 == V)
6067       return true;
6068     if (IE1) {
6069       if (IE1 != VU && !IE1->hasOneUse())
6070         IE1 = nullptr;
6071       else
6072         IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
6073     }
6074     if (IE2) {
6075       if (IE2 != V && !IE2->hasOneUse())
6076         IE2 = nullptr;
6077       else
6078         IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
6079     }
6080   } while (IE1 || IE2);
6081   return false;
6082 }
6083 
6084 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
6085   InstructionCost Cost = 0;
6086   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
6087                     << VectorizableTree.size() << ".\n");
6088 
6089   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
6090 
6091   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
6092     TreeEntry &TE = *VectorizableTree[I].get();
6093 
6094     InstructionCost C = getEntryCost(&TE, VectorizedVals);
6095     Cost += C;
6096     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6097                       << " for bundle that starts with " << *TE.Scalars[0]
6098                       << ".\n"
6099                       << "SLP: Current total cost = " << Cost << "\n");
6100   }
6101 
6102   SmallPtrSet<Value *, 16> ExtractCostCalculated;
6103   InstructionCost ExtractCost = 0;
6104   SmallVector<unsigned> VF;
6105   SmallVector<SmallVector<int>> ShuffleMask;
6106   SmallVector<Value *> FirstUsers;
6107   SmallVector<APInt> DemandedElts;
6108   for (ExternalUser &EU : ExternalUses) {
6109     // We only add extract cost once for the same scalar.
6110     if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
6111         !ExtractCostCalculated.insert(EU.Scalar).second)
6112       continue;
6113 
6114     // Uses by ephemeral values are free (because the ephemeral value will be
6115     // removed prior to code generation, and so the extraction will be
6116     // removed as well).
6117     if (EphValues.count(EU.User))
6118       continue;
6119 
6120     // No extract cost for vector "scalar"
6121     if (isa<FixedVectorType>(EU.Scalar->getType()))
6122       continue;
6123 
6124     // Already counted the cost for external uses when tried to adjust the cost
6125     // for extractelements, no need to add it again.
6126     if (isa<ExtractElementInst>(EU.Scalar))
6127       continue;
6128 
6129     // If found user is an insertelement, do not calculate extract cost but try
6130     // to detect it as a final shuffled/identity match.
6131     if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
6132       if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
6133         Optional<unsigned> InsertIdx = getInsertIndex(VU);
6134         if (InsertIdx) {
6135           auto *It = find_if(FirstUsers, [VU](Value *V) {
6136             return areTwoInsertFromSameBuildVector(VU,
6137                                                    cast<InsertElementInst>(V));
6138           });
6139           int VecId = -1;
6140           if (It == FirstUsers.end()) {
6141             VF.push_back(FTy->getNumElements());
6142             ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
6143             // Find the insertvector, vectorized in tree, if any.
6144             Value *Base = VU;
6145             while (isa<InsertElementInst>(Base)) {
6146               // Build the mask for the vectorized insertelement instructions.
6147               if (const TreeEntry *E = getTreeEntry(Base)) {
6148                 VU = cast<InsertElementInst>(Base);
6149                 do {
6150                   int Idx = E->findLaneForValue(Base);
6151                   ShuffleMask.back()[Idx] = Idx;
6152                   Base = cast<InsertElementInst>(Base)->getOperand(0);
6153                 } while (E == getTreeEntry(Base));
6154                 break;
6155               }
6156               Base = cast<InsertElementInst>(Base)->getOperand(0);
6157             }
6158             FirstUsers.push_back(VU);
6159             DemandedElts.push_back(APInt::getZero(VF.back()));
6160             VecId = FirstUsers.size() - 1;
6161           } else {
6162             VecId = std::distance(FirstUsers.begin(), It);
6163           }
6164           ShuffleMask[VecId][*InsertIdx] = EU.Lane;
6165           DemandedElts[VecId].setBit(*InsertIdx);
6166           continue;
6167         }
6168       }
6169     }
6170 
6171     // If we plan to rewrite the tree in a smaller type, we will need to sign
6172     // extend the extracted value back to the original type. Here, we account
6173     // for the extract and the added cost of the sign extend if needed.
6174     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
6175     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6176     if (MinBWs.count(ScalarRoot)) {
6177       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6178       auto Extend =
6179           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
6180       VecTy = FixedVectorType::get(MinTy, BundleWidth);
6181       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
6182                                                    VecTy, EU.Lane);
6183     } else {
6184       ExtractCost +=
6185           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
6186     }
6187   }
6188 
6189   InstructionCost SpillCost = getSpillCost();
6190   Cost += SpillCost + ExtractCost;
6191   if (FirstUsers.size() == 1) {
6192     int Limit = ShuffleMask.front().size() * 2;
6193     if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
6194         !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
6195       InstructionCost C = TTI->getShuffleCost(
6196           TTI::SK_PermuteSingleSrc,
6197           cast<FixedVectorType>(FirstUsers.front()->getType()),
6198           ShuffleMask.front());
6199       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6200                         << " for final shuffle of insertelement external users "
6201                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6202                         << "SLP: Current total cost = " << Cost << "\n");
6203       Cost += C;
6204     }
6205     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6206         cast<FixedVectorType>(FirstUsers.front()->getType()),
6207         DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
6208     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6209                       << " for insertelements gather.\n"
6210                       << "SLP: Current total cost = " << Cost << "\n");
6211     Cost -= InsertCost;
6212   } else if (FirstUsers.size() >= 2) {
6213     unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
6214     // Combined masks of the first 2 vectors.
6215     SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
6216     copy(ShuffleMask.front(), CombinedMask.begin());
6217     APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
6218     auto *VecTy = FixedVectorType::get(
6219         cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
6220         MaxVF);
6221     for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
6222       if (ShuffleMask[1][I] != UndefMaskElem) {
6223         CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
6224         CombinedDemandedElts.setBit(I);
6225       }
6226     }
6227     InstructionCost C =
6228         TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6229     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6230                       << " for final shuffle of vector node and external "
6231                          "insertelement users "
6232                       << *VectorizableTree.front()->Scalars.front() << ".\n"
6233                       << "SLP: Current total cost = " << Cost << "\n");
6234     Cost += C;
6235     InstructionCost InsertCost = TTI->getScalarizationOverhead(
6236         VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
6237     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6238                       << " for insertelements gather.\n"
6239                       << "SLP: Current total cost = " << Cost << "\n");
6240     Cost -= InsertCost;
6241     for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
6242       // Other elements - permutation of 2 vectors (the initial one and the
6243       // next Ith incoming vector).
6244       unsigned VF = ShuffleMask[I].size();
6245       for (unsigned Idx = 0; Idx < VF; ++Idx) {
6246         int Mask = ShuffleMask[I][Idx];
6247         if (Mask != UndefMaskElem)
6248           CombinedMask[Idx] = MaxVF + Mask;
6249         else if (CombinedMask[Idx] != UndefMaskElem)
6250           CombinedMask[Idx] = Idx;
6251       }
6252       for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
6253         if (CombinedMask[Idx] != UndefMaskElem)
6254           CombinedMask[Idx] = Idx;
6255       InstructionCost C =
6256           TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
6257       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
6258                         << " for final shuffle of vector node and external "
6259                            "insertelement users "
6260                         << *VectorizableTree.front()->Scalars.front() << ".\n"
6261                         << "SLP: Current total cost = " << Cost << "\n");
6262       Cost += C;
6263       InstructionCost InsertCost = TTI->getScalarizationOverhead(
6264           cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
6265           /*Insert*/ true, /*Extract*/ false);
6266       LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
6267                         << " for insertelements gather.\n"
6268                         << "SLP: Current total cost = " << Cost << "\n");
6269       Cost -= InsertCost;
6270     }
6271   }
6272 
6273 #ifndef NDEBUG
6274   SmallString<256> Str;
6275   {
6276     raw_svector_ostream OS(Str);
6277     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
6278        << "SLP: Extract Cost = " << ExtractCost << ".\n"
6279        << "SLP: Total Cost = " << Cost << ".\n";
6280   }
6281   LLVM_DEBUG(dbgs() << Str);
6282   if (ViewSLPTree)
6283     ViewGraph(this, "SLP" + F->getName(), false, Str);
6284 #endif
6285 
6286   return Cost;
6287 }
6288 
6289 Optional<TargetTransformInfo::ShuffleKind>
6290 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
6291                                SmallVectorImpl<const TreeEntry *> &Entries) {
6292   // TODO: currently checking only for Scalars in the tree entry, need to count
6293   // reused elements too for better cost estimation.
6294   Mask.assign(TE->Scalars.size(), UndefMaskElem);
6295   Entries.clear();
6296   // Build a lists of values to tree entries.
6297   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
6298   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
6299     if (EntryPtr.get() == TE)
6300       break;
6301     if (EntryPtr->State != TreeEntry::NeedToGather)
6302       continue;
6303     for (Value *V : EntryPtr->Scalars)
6304       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
6305   }
6306   // Find all tree entries used by the gathered values. If no common entries
6307   // found - not a shuffle.
6308   // Here we build a set of tree nodes for each gathered value and trying to
6309   // find the intersection between these sets. If we have at least one common
6310   // tree node for each gathered value - we have just a permutation of the
6311   // single vector. If we have 2 different sets, we're in situation where we
6312   // have a permutation of 2 input vectors.
6313   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
6314   DenseMap<Value *, int> UsedValuesEntry;
6315   for (Value *V : TE->Scalars) {
6316     if (isa<UndefValue>(V))
6317       continue;
6318     // Build a list of tree entries where V is used.
6319     SmallPtrSet<const TreeEntry *, 4> VToTEs;
6320     auto It = ValueToTEs.find(V);
6321     if (It != ValueToTEs.end())
6322       VToTEs = It->second;
6323     if (const TreeEntry *VTE = getTreeEntry(V))
6324       VToTEs.insert(VTE);
6325     if (VToTEs.empty())
6326       return None;
6327     if (UsedTEs.empty()) {
6328       // The first iteration, just insert the list of nodes to vector.
6329       UsedTEs.push_back(VToTEs);
6330     } else {
6331       // Need to check if there are any previously used tree nodes which use V.
6332       // If there are no such nodes, consider that we have another one input
6333       // vector.
6334       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
6335       unsigned Idx = 0;
6336       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
6337         // Do we have a non-empty intersection of previously listed tree entries
6338         // and tree entries using current V?
6339         set_intersect(VToTEs, Set);
6340         if (!VToTEs.empty()) {
6341           // Yes, write the new subset and continue analysis for the next
6342           // scalar.
6343           Set.swap(VToTEs);
6344           break;
6345         }
6346         VToTEs = SavedVToTEs;
6347         ++Idx;
6348       }
6349       // No non-empty intersection found - need to add a second set of possible
6350       // source vectors.
6351       if (Idx == UsedTEs.size()) {
6352         // If the number of input vectors is greater than 2 - not a permutation,
6353         // fallback to the regular gather.
6354         if (UsedTEs.size() == 2)
6355           return None;
6356         UsedTEs.push_back(SavedVToTEs);
6357         Idx = UsedTEs.size() - 1;
6358       }
6359       UsedValuesEntry.try_emplace(V, Idx);
6360     }
6361   }
6362 
6363   unsigned VF = 0;
6364   if (UsedTEs.size() == 1) {
6365     // Try to find the perfect match in another gather node at first.
6366     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
6367       return EntryPtr->isSame(TE->Scalars);
6368     });
6369     if (It != UsedTEs.front().end()) {
6370       Entries.push_back(*It);
6371       std::iota(Mask.begin(), Mask.end(), 0);
6372       return TargetTransformInfo::SK_PermuteSingleSrc;
6373     }
6374     // No perfect match, just shuffle, so choose the first tree node.
6375     Entries.push_back(*UsedTEs.front().begin());
6376   } else {
6377     // Try to find nodes with the same vector factor.
6378     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
6379     DenseMap<int, const TreeEntry *> VFToTE;
6380     for (const TreeEntry *TE : UsedTEs.front())
6381       VFToTE.try_emplace(TE->getVectorFactor(), TE);
6382     for (const TreeEntry *TE : UsedTEs.back()) {
6383       auto It = VFToTE.find(TE->getVectorFactor());
6384       if (It != VFToTE.end()) {
6385         VF = It->first;
6386         Entries.push_back(It->second);
6387         Entries.push_back(TE);
6388         break;
6389       }
6390     }
6391     // No 2 source vectors with the same vector factor - give up and do regular
6392     // gather.
6393     if (Entries.empty())
6394       return None;
6395   }
6396 
6397   // Build a shuffle mask for better cost estimation and vector emission.
6398   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
6399     Value *V = TE->Scalars[I];
6400     if (isa<UndefValue>(V))
6401       continue;
6402     unsigned Idx = UsedValuesEntry.lookup(V);
6403     const TreeEntry *VTE = Entries[Idx];
6404     int FoundLane = VTE->findLaneForValue(V);
6405     Mask[I] = Idx * VF + FoundLane;
6406     // Extra check required by isSingleSourceMaskImpl function (called by
6407     // ShuffleVectorInst::isSingleSourceMask).
6408     if (Mask[I] >= 2 * E)
6409       return None;
6410   }
6411   switch (Entries.size()) {
6412   case 1:
6413     return TargetTransformInfo::SK_PermuteSingleSrc;
6414   case 2:
6415     return TargetTransformInfo::SK_PermuteTwoSrc;
6416   default:
6417     break;
6418   }
6419   return None;
6420 }
6421 
6422 InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
6423                                        const APInt &ShuffledIndices,
6424                                        bool NeedToShuffle) const {
6425   InstructionCost Cost =
6426       TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
6427                                     /*Extract*/ false);
6428   if (NeedToShuffle)
6429     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
6430   return Cost;
6431 }
6432 
6433 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
6434   // Find the type of the operands in VL.
6435   Type *ScalarTy = VL[0]->getType();
6436   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
6437     ScalarTy = SI->getValueOperand()->getType();
6438   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
6439   bool DuplicateNonConst = false;
6440   // Find the cost of inserting/extracting values from the vector.
6441   // Check if the same elements are inserted several times and count them as
6442   // shuffle candidates.
6443   APInt ShuffledElements = APInt::getZero(VL.size());
6444   DenseSet<Value *> UniqueElements;
6445   // Iterate in reverse order to consider insert elements with the high cost.
6446   for (unsigned I = VL.size(); I > 0; --I) {
6447     unsigned Idx = I - 1;
6448     // No need to shuffle duplicates for constants.
6449     if (isConstant(VL[Idx])) {
6450       ShuffledElements.setBit(Idx);
6451       continue;
6452     }
6453     if (!UniqueElements.insert(VL[Idx]).second) {
6454       DuplicateNonConst = true;
6455       ShuffledElements.setBit(Idx);
6456     }
6457   }
6458   return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
6459 }
6460 
6461 // Perform operand reordering on the instructions in VL and return the reordered
6462 // operands in Left and Right.
6463 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
6464                                              SmallVectorImpl<Value *> &Left,
6465                                              SmallVectorImpl<Value *> &Right,
6466                                              const DataLayout &DL,
6467                                              ScalarEvolution &SE,
6468                                              const BoUpSLP &R) {
6469   if (VL.empty())
6470     return;
6471   VLOperands Ops(VL, DL, SE, R);
6472   // Reorder the operands in place.
6473   Ops.reorder();
6474   Left = Ops.getVL(0);
6475   Right = Ops.getVL(1);
6476 }
6477 
6478 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
6479   // Get the basic block this bundle is in. All instructions in the bundle
6480   // should be in this block.
6481   auto *Front = E->getMainOp();
6482   auto *BB = Front->getParent();
6483   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
6484     auto *I = cast<Instruction>(V);
6485     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
6486   }));
6487 
6488   // Set the insert point to the beginning of the basic block if the entry
6489   // should not be scheduled.
6490   if (E->State != TreeEntry::NeedToGather &&
6491       doesNotNeedToSchedule(E->Scalars)) {
6492     BasicBlock::iterator InsertPt;
6493     if (all_of(E->Scalars, isUsedOutsideBlock))
6494       InsertPt = BB->getTerminator()->getIterator();
6495     else
6496       InsertPt = BB->getFirstInsertionPt();
6497     Builder.SetInsertPoint(BB, InsertPt);
6498     Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6499     return;
6500   }
6501 
6502   // The last instruction in the bundle in program order.
6503   Instruction *LastInst = nullptr;
6504 
6505   // Find the last instruction. The common case should be that BB has been
6506   // scheduled, and the last instruction is VL.back(). So we start with
6507   // VL.back() and iterate over schedule data until we reach the end of the
6508   // bundle. The end of the bundle is marked by null ScheduleData.
6509   if (BlocksSchedules.count(BB)) {
6510     Value *V = E->isOneOf(E->Scalars.back());
6511     if (doesNotNeedToBeScheduled(V))
6512       V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
6513     auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
6514     if (Bundle && Bundle->isPartOfBundle())
6515       for (; Bundle; Bundle = Bundle->NextInBundle)
6516         if (Bundle->OpValue == Bundle->Inst)
6517           LastInst = Bundle->Inst;
6518   }
6519 
6520   // LastInst can still be null at this point if there's either not an entry
6521   // for BB in BlocksSchedules or there's no ScheduleData available for
6522   // VL.back(). This can be the case if buildTree_rec aborts for various
6523   // reasons (e.g., the maximum recursion depth is reached, the maximum region
6524   // size is reached, etc.). ScheduleData is initialized in the scheduling
6525   // "dry-run".
6526   //
6527   // If this happens, we can still find the last instruction by brute force. We
6528   // iterate forwards from Front (inclusive) until we either see all
6529   // instructions in the bundle or reach the end of the block. If Front is the
6530   // last instruction in program order, LastInst will be set to Front, and we
6531   // will visit all the remaining instructions in the block.
6532   //
6533   // One of the reasons we exit early from buildTree_rec is to place an upper
6534   // bound on compile-time. Thus, taking an additional compile-time hit here is
6535   // not ideal. However, this should be exceedingly rare since it requires that
6536   // we both exit early from buildTree_rec and that the bundle be out-of-order
6537   // (causing us to iterate all the way to the end of the block).
6538   if (!LastInst) {
6539     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
6540     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
6541       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
6542         LastInst = &I;
6543       if (Bundle.empty())
6544         break;
6545     }
6546   }
6547   assert(LastInst && "Failed to find last instruction in bundle");
6548 
6549   // Set the insertion point after the last instruction in the bundle. Set the
6550   // debug location to Front.
6551   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
6552   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
6553 }
6554 
6555 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
6556   // List of instructions/lanes from current block and/or the blocks which are
6557   // part of the current loop. These instructions will be inserted at the end to
6558   // make it possible to optimize loops and hoist invariant instructions out of
6559   // the loops body with better chances for success.
6560   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
6561   SmallSet<int, 4> PostponedIndices;
6562   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
6563   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
6564     SmallPtrSet<BasicBlock *, 4> Visited;
6565     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
6566       InsertBB = InsertBB->getSinglePredecessor();
6567     return InsertBB && InsertBB == InstBB;
6568   };
6569   for (int I = 0, E = VL.size(); I < E; ++I) {
6570     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
6571       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
6572            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
6573           PostponedIndices.insert(I).second)
6574         PostponedInsts.emplace_back(Inst, I);
6575   }
6576 
6577   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
6578     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
6579     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
6580     if (!InsElt)
6581       return Vec;
6582     GatherShuffleSeq.insert(InsElt);
6583     CSEBlocks.insert(InsElt->getParent());
6584     // Add to our 'need-to-extract' list.
6585     if (TreeEntry *Entry = getTreeEntry(V)) {
6586       // Find which lane we need to extract.
6587       unsigned FoundLane = Entry->findLaneForValue(V);
6588       ExternalUses.emplace_back(V, InsElt, FoundLane);
6589     }
6590     return Vec;
6591   };
6592   Value *Val0 =
6593       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
6594   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
6595   Value *Vec = PoisonValue::get(VecTy);
6596   SmallVector<int> NonConsts;
6597   // Insert constant values at first.
6598   for (int I = 0, E = VL.size(); I < E; ++I) {
6599     if (PostponedIndices.contains(I))
6600       continue;
6601     if (!isConstant(VL[I])) {
6602       NonConsts.push_back(I);
6603       continue;
6604     }
6605     Vec = CreateInsertElement(Vec, VL[I], I);
6606   }
6607   // Insert non-constant values.
6608   for (int I : NonConsts)
6609     Vec = CreateInsertElement(Vec, VL[I], I);
6610   // Append instructions, which are/may be part of the loop, in the end to make
6611   // it possible to hoist non-loop-based instructions.
6612   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
6613     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
6614 
6615   return Vec;
6616 }
6617 
6618 namespace {
6619 /// Merges shuffle masks and emits final shuffle instruction, if required.
6620 class ShuffleInstructionBuilder {
6621   IRBuilderBase &Builder;
6622   const unsigned VF = 0;
6623   bool IsFinalized = false;
6624   SmallVector<int, 4> Mask;
6625   /// Holds all of the instructions that we gathered.
6626   SetVector<Instruction *> &GatherShuffleSeq;
6627   /// A list of blocks that we are going to CSE.
6628   SetVector<BasicBlock *> &CSEBlocks;
6629 
6630 public:
6631   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
6632                             SetVector<Instruction *> &GatherShuffleSeq,
6633                             SetVector<BasicBlock *> &CSEBlocks)
6634       : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
6635         CSEBlocks(CSEBlocks) {}
6636 
6637   /// Adds a mask, inverting it before applying.
6638   void addInversedMask(ArrayRef<unsigned> SubMask) {
6639     if (SubMask.empty())
6640       return;
6641     SmallVector<int, 4> NewMask;
6642     inversePermutation(SubMask, NewMask);
6643     addMask(NewMask);
6644   }
6645 
6646   /// Functions adds masks, merging them into  single one.
6647   void addMask(ArrayRef<unsigned> SubMask) {
6648     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
6649     addMask(NewMask);
6650   }
6651 
6652   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
6653 
6654   Value *finalize(Value *V) {
6655     IsFinalized = true;
6656     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
6657     if (VF == ValueVF && Mask.empty())
6658       return V;
6659     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
6660     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
6661     addMask(NormalizedMask);
6662 
6663     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
6664       return V;
6665     Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
6666     if (auto *I = dyn_cast<Instruction>(Vec)) {
6667       GatherShuffleSeq.insert(I);
6668       CSEBlocks.insert(I->getParent());
6669     }
6670     return Vec;
6671   }
6672 
6673   ~ShuffleInstructionBuilder() {
6674     assert((IsFinalized || Mask.empty()) &&
6675            "Shuffle construction must be finalized.");
6676   }
6677 };
6678 } // namespace
6679 
6680 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
6681   const unsigned VF = VL.size();
6682   InstructionsState S = getSameOpcode(VL);
6683   if (S.getOpcode()) {
6684     if (TreeEntry *E = getTreeEntry(S.OpValue))
6685       if (E->isSame(VL)) {
6686         Value *V = vectorizeTree(E);
6687         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
6688           if (!E->ReuseShuffleIndices.empty()) {
6689             // Reshuffle to get only unique values.
6690             // If some of the scalars are duplicated in the vectorization tree
6691             // entry, we do not vectorize them but instead generate a mask for
6692             // the reuses. But if there are several users of the same entry,
6693             // they may have different vectorization factors. This is especially
6694             // important for PHI nodes. In this case, we need to adapt the
6695             // resulting instruction for the user vectorization factor and have
6696             // to reshuffle it again to take only unique elements of the vector.
6697             // Without this code the function incorrectly returns reduced vector
6698             // instruction with the same elements, not with the unique ones.
6699 
6700             // block:
6701             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
6702             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
6703             // ... (use %2)
6704             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
6705             // br %block
6706             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
6707             SmallSet<int, 4> UsedIdxs;
6708             int Pos = 0;
6709             int Sz = VL.size();
6710             for (int Idx : E->ReuseShuffleIndices) {
6711               if (Idx != Sz && Idx != UndefMaskElem &&
6712                   UsedIdxs.insert(Idx).second)
6713                 UniqueIdxs[Idx] = Pos;
6714               ++Pos;
6715             }
6716             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
6717                                             "less than original vector size.");
6718             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
6719             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
6720           } else {
6721             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
6722                    "Expected vectorization factor less "
6723                    "than original vector size.");
6724             SmallVector<int> UniformMask(VF, 0);
6725             std::iota(UniformMask.begin(), UniformMask.end(), 0);
6726             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
6727           }
6728           if (auto *I = dyn_cast<Instruction>(V)) {
6729             GatherShuffleSeq.insert(I);
6730             CSEBlocks.insert(I->getParent());
6731           }
6732         }
6733         return V;
6734       }
6735   }
6736 
6737   // Can't vectorize this, so simply build a new vector with each lane
6738   // corresponding to the requested value.
6739   return createBuildVector(VL);
6740 }
6741 Value *BoUpSLP::createBuildVector(ArrayRef<Value *> VL) {
6742   unsigned VF = VL.size();
6743   // Exploit possible reuse of values across lanes.
6744   SmallVector<int> ReuseShuffleIndicies;
6745   SmallVector<Value *> UniqueValues;
6746   if (VL.size() > 2) {
6747     DenseMap<Value *, unsigned> UniquePositions;
6748     unsigned NumValues =
6749         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
6750                                     return !isa<UndefValue>(V);
6751                                   }).base());
6752     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
6753     int UniqueVals = 0;
6754     for (Value *V : VL.drop_back(VL.size() - VF)) {
6755       if (isa<UndefValue>(V)) {
6756         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
6757         continue;
6758       }
6759       if (isConstant(V)) {
6760         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
6761         UniqueValues.emplace_back(V);
6762         continue;
6763       }
6764       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
6765       ReuseShuffleIndicies.emplace_back(Res.first->second);
6766       if (Res.second) {
6767         UniqueValues.emplace_back(V);
6768         ++UniqueVals;
6769       }
6770     }
6771     if (UniqueVals == 1 && UniqueValues.size() == 1) {
6772       // Emit pure splat vector.
6773       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
6774                                   UndefMaskElem);
6775     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
6776       ReuseShuffleIndicies.clear();
6777       UniqueValues.clear();
6778       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
6779     }
6780     UniqueValues.append(VF - UniqueValues.size(),
6781                         PoisonValue::get(VL[0]->getType()));
6782     VL = UniqueValues;
6783   }
6784 
6785   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6786                                            CSEBlocks);
6787   Value *Vec = gather(VL);
6788   if (!ReuseShuffleIndicies.empty()) {
6789     ShuffleBuilder.addMask(ReuseShuffleIndicies);
6790     Vec = ShuffleBuilder.finalize(Vec);
6791   }
6792   return Vec;
6793 }
6794 
6795 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
6796   IRBuilder<>::InsertPointGuard Guard(Builder);
6797 
6798   if (E->VectorizedValue) {
6799     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
6800     return E->VectorizedValue;
6801   }
6802 
6803   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
6804   unsigned VF = E->getVectorFactor();
6805   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
6806                                            CSEBlocks);
6807   if (E->State == TreeEntry::NeedToGather) {
6808     if (E->getMainOp())
6809       setInsertPointAfterBundle(E);
6810     Value *Vec;
6811     SmallVector<int> Mask;
6812     SmallVector<const TreeEntry *> Entries;
6813     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
6814         isGatherShuffledEntry(E, Mask, Entries);
6815     if (Shuffle.hasValue()) {
6816       assert((Entries.size() == 1 || Entries.size() == 2) &&
6817              "Expected shuffle of 1 or 2 entries.");
6818       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
6819                                         Entries.back()->VectorizedValue, Mask);
6820       if (auto *I = dyn_cast<Instruction>(Vec)) {
6821         GatherShuffleSeq.insert(I);
6822         CSEBlocks.insert(I->getParent());
6823       }
6824     } else {
6825       Vec = gather(E->Scalars);
6826     }
6827     if (NeedToShuffleReuses) {
6828       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6829       Vec = ShuffleBuilder.finalize(Vec);
6830     }
6831     E->VectorizedValue = Vec;
6832     return Vec;
6833   }
6834 
6835   assert((E->State == TreeEntry::Vectorize ||
6836           E->State == TreeEntry::ScatterVectorize) &&
6837          "Unhandled state");
6838   unsigned ShuffleOrOp =
6839       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
6840   Instruction *VL0 = E->getMainOp();
6841   Type *ScalarTy = VL0->getType();
6842   if (auto *Store = dyn_cast<StoreInst>(VL0))
6843     ScalarTy = Store->getValueOperand()->getType();
6844   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
6845     ScalarTy = IE->getOperand(1)->getType();
6846   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
6847   switch (ShuffleOrOp) {
6848     case Instruction::PHI: {
6849       assert(
6850           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
6851           "PHI reordering is free.");
6852       auto *PH = cast<PHINode>(VL0);
6853       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
6854       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6855       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
6856       Value *V = NewPhi;
6857 
6858       // Adjust insertion point once all PHI's have been generated.
6859       Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
6860       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6861 
6862       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6863       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6864       V = ShuffleBuilder.finalize(V);
6865 
6866       E->VectorizedValue = V;
6867 
6868       // PHINodes may have multiple entries from the same block. We want to
6869       // visit every block once.
6870       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
6871 
6872       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
6873         ValueList Operands;
6874         BasicBlock *IBB = PH->getIncomingBlock(i);
6875 
6876         if (!VisitedBBs.insert(IBB).second) {
6877           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
6878           continue;
6879         }
6880 
6881         Builder.SetInsertPoint(IBB->getTerminator());
6882         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
6883         Value *Vec = vectorizeTree(E->getOperand(i));
6884         NewPhi->addIncoming(Vec, IBB);
6885       }
6886 
6887       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
6888              "Invalid number of incoming values");
6889       return V;
6890     }
6891 
6892     case Instruction::ExtractElement: {
6893       Value *V = E->getSingleOperand(0);
6894       Builder.SetInsertPoint(VL0);
6895       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6896       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6897       V = ShuffleBuilder.finalize(V);
6898       E->VectorizedValue = V;
6899       return V;
6900     }
6901     case Instruction::ExtractValue: {
6902       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
6903       Builder.SetInsertPoint(LI);
6904       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
6905       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
6906       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
6907       if (MSSA) {
6908         MemorySSAUpdater MSSAU(MSSA);
6909         auto *Access = MSSA->getMemoryAccess(LI);
6910         assert(Access);
6911         MemoryUseOrDef *NewAccess =
6912           MSSAU.createMemoryAccessBefore(V, Access->getDefiningAccess(),
6913                                          Access);
6914         MSSAU.insertUse(cast<MemoryUse>(NewAccess), true);
6915       }
6916       Value *NewV = propagateMetadata(V, E->Scalars);
6917       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6918       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6919       NewV = ShuffleBuilder.finalize(NewV);
6920       E->VectorizedValue = NewV;
6921       return NewV;
6922     }
6923     case Instruction::InsertElement: {
6924       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
6925       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
6926       Value *V = vectorizeTree(E->getOperand(1));
6927 
6928       // Create InsertVector shuffle if necessary
6929       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
6930         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
6931       }));
6932       const unsigned NumElts =
6933           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6934       const unsigned NumScalars = E->Scalars.size();
6935 
6936       unsigned Offset = *getInsertIndex(VL0);
6937       assert(Offset < NumElts && "Failed to find vector index offset");
6938 
6939       // Create shuffle to resize vector
6940       SmallVector<int> Mask;
6941       if (!E->ReorderIndices.empty()) {
6942         inversePermutation(E->ReorderIndices, Mask);
6943         Mask.append(NumElts - NumScalars, UndefMaskElem);
6944       } else {
6945         Mask.assign(NumElts, UndefMaskElem);
6946         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6947       }
6948       // Create InsertVector shuffle if necessary
6949       bool IsIdentity = true;
6950       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6951       Mask.swap(PrevMask);
6952       for (unsigned I = 0; I < NumScalars; ++I) {
6953         Value *Scalar = E->Scalars[PrevMask[I]];
6954         unsigned InsertIdx = *getInsertIndex(Scalar);
6955         IsIdentity &= InsertIdx - Offset == I;
6956         Mask[InsertIdx - Offset] = I;
6957       }
6958       if (!IsIdentity || NumElts != NumScalars) {
6959         V = Builder.CreateShuffleVector(V, Mask);
6960         if (auto *I = dyn_cast<Instruction>(V)) {
6961           GatherShuffleSeq.insert(I);
6962           CSEBlocks.insert(I->getParent());
6963         }
6964       }
6965 
6966       if ((!IsIdentity || Offset != 0 ||
6967            !isUndefVector(FirstInsert->getOperand(0))) &&
6968           NumElts != NumScalars) {
6969         SmallVector<int> InsertMask(NumElts);
6970         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6971         for (unsigned I = 0; I < NumElts; I++) {
6972           if (Mask[I] != UndefMaskElem)
6973             InsertMask[Offset + I] = NumElts + I;
6974         }
6975 
6976         V = Builder.CreateShuffleVector(
6977             FirstInsert->getOperand(0), V, InsertMask,
6978             cast<Instruction>(E->Scalars.back())->getName());
6979         if (auto *I = dyn_cast<Instruction>(V)) {
6980           GatherShuffleSeq.insert(I);
6981           CSEBlocks.insert(I->getParent());
6982         }
6983       }
6984 
6985       ++NumVectorInstructions;
6986       E->VectorizedValue = V;
6987       return V;
6988     }
6989     case Instruction::ZExt:
6990     case Instruction::SExt:
6991     case Instruction::FPToUI:
6992     case Instruction::FPToSI:
6993     case Instruction::FPExt:
6994     case Instruction::PtrToInt:
6995     case Instruction::IntToPtr:
6996     case Instruction::SIToFP:
6997     case Instruction::UIToFP:
6998     case Instruction::Trunc:
6999     case Instruction::FPTrunc:
7000     case Instruction::BitCast: {
7001       setInsertPointAfterBundle(E);
7002 
7003       Value *InVec = vectorizeTree(E->getOperand(0));
7004 
7005       if (E->VectorizedValue) {
7006         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7007         return E->VectorizedValue;
7008       }
7009 
7010       auto *CI = cast<CastInst>(VL0);
7011       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
7012       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7013       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7014       V = ShuffleBuilder.finalize(V);
7015 
7016       E->VectorizedValue = V;
7017       ++NumVectorInstructions;
7018       return V;
7019     }
7020     case Instruction::FCmp:
7021     case Instruction::ICmp: {
7022       setInsertPointAfterBundle(E);
7023 
7024       Value *L = vectorizeTree(E->getOperand(0));
7025       Value *R = vectorizeTree(E->getOperand(1));
7026 
7027       if (E->VectorizedValue) {
7028         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7029         return E->VectorizedValue;
7030       }
7031 
7032       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
7033       Value *V = Builder.CreateCmp(P0, L, R);
7034       propagateIRFlags(V, E->Scalars, VL0);
7035       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7036       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7037       V = ShuffleBuilder.finalize(V);
7038 
7039       E->VectorizedValue = V;
7040       ++NumVectorInstructions;
7041       return V;
7042     }
7043     case Instruction::Select: {
7044       setInsertPointAfterBundle(E);
7045 
7046       Value *Cond = vectorizeTree(E->getOperand(0));
7047       Value *True = vectorizeTree(E->getOperand(1));
7048       Value *False = vectorizeTree(E->getOperand(2));
7049 
7050       if (E->VectorizedValue) {
7051         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7052         return E->VectorizedValue;
7053       }
7054 
7055       Value *V = Builder.CreateSelect(Cond, True, False);
7056       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7057       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7058       V = ShuffleBuilder.finalize(V);
7059 
7060       E->VectorizedValue = V;
7061       ++NumVectorInstructions;
7062       return V;
7063     }
7064     case Instruction::FNeg: {
7065       setInsertPointAfterBundle(E);
7066 
7067       Value *Op = vectorizeTree(E->getOperand(0));
7068 
7069       if (E->VectorizedValue) {
7070         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7071         return E->VectorizedValue;
7072       }
7073 
7074       Value *V = Builder.CreateUnOp(
7075           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
7076       propagateIRFlags(V, E->Scalars, VL0);
7077       if (auto *I = dyn_cast<Instruction>(V))
7078         V = propagateMetadata(I, E->Scalars);
7079 
7080       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7081       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7082       V = ShuffleBuilder.finalize(V);
7083 
7084       E->VectorizedValue = V;
7085       ++NumVectorInstructions;
7086 
7087       return V;
7088     }
7089     case Instruction::Add:
7090     case Instruction::FAdd:
7091     case Instruction::Sub:
7092     case Instruction::FSub:
7093     case Instruction::Mul:
7094     case Instruction::FMul:
7095     case Instruction::UDiv:
7096     case Instruction::SDiv:
7097     case Instruction::FDiv:
7098     case Instruction::URem:
7099     case Instruction::SRem:
7100     case Instruction::FRem:
7101     case Instruction::Shl:
7102     case Instruction::LShr:
7103     case Instruction::AShr:
7104     case Instruction::And:
7105     case Instruction::Or:
7106     case Instruction::Xor: {
7107       setInsertPointAfterBundle(E);
7108 
7109       Value *LHS = vectorizeTree(E->getOperand(0));
7110       Value *RHS = vectorizeTree(E->getOperand(1));
7111 
7112       if (E->VectorizedValue) {
7113         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7114         return E->VectorizedValue;
7115       }
7116 
7117       Value *V = Builder.CreateBinOp(
7118           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
7119           RHS);
7120       propagateIRFlags(V, E->Scalars, VL0);
7121       if (auto *I = dyn_cast<Instruction>(V))
7122         V = propagateMetadata(I, E->Scalars);
7123 
7124       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7125       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7126       V = ShuffleBuilder.finalize(V);
7127 
7128       E->VectorizedValue = V;
7129       ++NumVectorInstructions;
7130 
7131       return V;
7132     }
7133     case Instruction::Load: {
7134       // Loads are inserted at the head of the tree because we don't want to
7135       // sink them all the way down past store instructions.
7136       setInsertPointAfterBundle(E);
7137 
7138       LoadInst *LI = cast<LoadInst>(VL0);
7139       Instruction *NewLI;
7140       unsigned AS = LI->getPointerAddressSpace();
7141       Value *PO = LI->getPointerOperand();
7142       if (E->State == TreeEntry::Vectorize) {
7143         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
7144         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
7145 
7146         // The pointer operand uses an in-tree scalar so we add the new BitCast
7147         // or LoadInst to ExternalUses list to make sure that an extract will
7148         // be generated in the future.
7149         if (TreeEntry *Entry = getTreeEntry(PO)) {
7150           // Find which lane we need to extract.
7151           unsigned FoundLane = Entry->findLaneForValue(PO);
7152           ExternalUses.emplace_back(
7153               PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
7154         }
7155       } else {
7156         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
7157         Value *VecPtr = vectorizeTree(E->getOperand(0));
7158         // Use the minimum alignment of the gathered loads.
7159         Align CommonAlignment = LI->getAlign();
7160         for (Value *V : E->Scalars)
7161           CommonAlignment =
7162               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
7163         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
7164       }
7165 
7166       if (MSSA) {
7167         MemorySSAUpdater MSSAU(MSSA);
7168         auto *Access = MSSA->getMemoryAccess(LI);
7169         assert(Access);
7170         MemoryUseOrDef *NewAccess =
7171           MSSAU.createMemoryAccessAfter(NewLI, Access->getDefiningAccess(),
7172                                         Access);
7173         MSSAU.insertUse(cast<MemoryUse>(NewAccess), true);
7174       }
7175 
7176       Value *V = propagateMetadata(NewLI, E->Scalars);
7177 
7178       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7179       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7180       V = ShuffleBuilder.finalize(V);
7181       E->VectorizedValue = V;
7182       ++NumVectorInstructions;
7183       return V;
7184     }
7185     case Instruction::Store: {
7186       auto *SI = cast<StoreInst>(VL0);
7187       unsigned AS = SI->getPointerAddressSpace();
7188 
7189       setInsertPointAfterBundle(E);
7190 
7191       Value *VecValue = vectorizeTree(E->getOperand(0));
7192       ShuffleBuilder.addMask(E->ReorderIndices);
7193       VecValue = ShuffleBuilder.finalize(VecValue);
7194 
7195       Value *ScalarPtr = SI->getPointerOperand();
7196       Value *VecPtr = Builder.CreateBitCast(
7197           ScalarPtr, VecValue->getType()->getPointerTo(AS));
7198       StoreInst *ST =
7199           Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
7200 
7201       if (MSSA) {
7202         MemorySSAUpdater MSSAU(MSSA);
7203         auto *Access = MSSA->getMemoryAccess(SI);
7204         assert(Access);
7205         MemoryUseOrDef *NewAccess =
7206           MSSAU.createMemoryAccessAfter(ST, Access->getDefiningAccess(),
7207                                         Access);
7208         MSSAU.insertDef(cast<MemoryDef>(NewAccess), true);
7209       }
7210 
7211       // The pointer operand uses an in-tree scalar, so add the new BitCast or
7212       // StoreInst to ExternalUses to make sure that an extract will be
7213       // generated in the future.
7214       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
7215         // Find which lane we need to extract.
7216         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
7217         ExternalUses.push_back(ExternalUser(
7218             ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
7219             FoundLane));
7220       }
7221 
7222       Value *V = propagateMetadata(ST, E->Scalars);
7223 
7224       E->VectorizedValue = V;
7225       ++NumVectorInstructions;
7226       return V;
7227     }
7228     case Instruction::GetElementPtr: {
7229       auto *GEP0 = cast<GetElementPtrInst>(VL0);
7230       setInsertPointAfterBundle(E);
7231 
7232       Value *Op0 = vectorizeTree(E->getOperand(0));
7233 
7234       SmallVector<Value *> OpVecs;
7235       for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
7236         Value *OpVec = vectorizeTree(E->getOperand(J));
7237         OpVecs.push_back(OpVec);
7238       }
7239 
7240       Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
7241       if (Instruction *I = dyn_cast<Instruction>(V))
7242         V = propagateMetadata(I, E->Scalars);
7243 
7244       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7245       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7246       V = ShuffleBuilder.finalize(V);
7247 
7248       E->VectorizedValue = V;
7249       ++NumVectorInstructions;
7250 
7251       return V;
7252     }
7253     case Instruction::Call: {
7254       CallInst *CI = cast<CallInst>(VL0);
7255       setInsertPointAfterBundle(E);
7256 
7257       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
7258       if (Function *FI = CI->getCalledFunction())
7259         IID = FI->getIntrinsicID();
7260 
7261       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
7262 
7263       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
7264       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
7265                           VecCallCosts.first <= VecCallCosts.second;
7266 
7267       Value *ScalarArg = nullptr;
7268       std::vector<Value *> OpVecs;
7269       SmallVector<Type *, 2> TysForDecl =
7270           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
7271       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
7272         ValueList OpVL;
7273         // Some intrinsics have scalar arguments. This argument should not be
7274         // vectorized.
7275         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
7276           CallInst *CEI = cast<CallInst>(VL0);
7277           ScalarArg = CEI->getArgOperand(j);
7278           OpVecs.push_back(CEI->getArgOperand(j));
7279           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
7280             TysForDecl.push_back(ScalarArg->getType());
7281           continue;
7282         }
7283 
7284         Value *OpVec = vectorizeTree(E->getOperand(j));
7285         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
7286         OpVecs.push_back(OpVec);
7287       }
7288 
7289       Function *CF;
7290       if (!UseIntrinsic) {
7291         VFShape Shape =
7292             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
7293                                   VecTy->getNumElements())),
7294                          false /*HasGlobalPred*/);
7295         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
7296       } else {
7297         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
7298       }
7299 
7300       SmallVector<OperandBundleDef, 1> OpBundles;
7301       CI->getOperandBundlesAsDefs(OpBundles);
7302       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
7303 
7304       // The scalar argument uses an in-tree scalar so we add the new vectorized
7305       // call to ExternalUses list to make sure that an extract will be
7306       // generated in the future.
7307       if (ScalarArg) {
7308         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
7309           // Find which lane we need to extract.
7310           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
7311           ExternalUses.push_back(
7312               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
7313         }
7314       }
7315 
7316       propagateIRFlags(V, E->Scalars, VL0);
7317       ShuffleBuilder.addInversedMask(E->ReorderIndices);
7318       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
7319       V = ShuffleBuilder.finalize(V);
7320 
7321       E->VectorizedValue = V;
7322       ++NumVectorInstructions;
7323       return V;
7324     }
7325     case Instruction::ShuffleVector: {
7326       assert(E->isAltShuffle() &&
7327              ((Instruction::isBinaryOp(E->getOpcode()) &&
7328                Instruction::isBinaryOp(E->getAltOpcode())) ||
7329               (Instruction::isCast(E->getOpcode()) &&
7330                Instruction::isCast(E->getAltOpcode())) ||
7331               (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
7332              "Invalid Shuffle Vector Operand");
7333 
7334       Value *LHS = nullptr, *RHS = nullptr;
7335       if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
7336         setInsertPointAfterBundle(E);
7337         LHS = vectorizeTree(E->getOperand(0));
7338         RHS = vectorizeTree(E->getOperand(1));
7339       } else {
7340         setInsertPointAfterBundle(E);
7341         LHS = vectorizeTree(E->getOperand(0));
7342       }
7343 
7344       if (E->VectorizedValue) {
7345         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
7346         return E->VectorizedValue;
7347       }
7348 
7349       Value *V0, *V1;
7350       if (Instruction::isBinaryOp(E->getOpcode())) {
7351         V0 = Builder.CreateBinOp(
7352             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
7353         V1 = Builder.CreateBinOp(
7354             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
7355       } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
7356         V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
7357         auto *AltCI = cast<CmpInst>(E->getAltOp());
7358         CmpInst::Predicate AltPred = AltCI->getPredicate();
7359         V1 = Builder.CreateCmp(AltPred, LHS, RHS);
7360       } else {
7361         V0 = Builder.CreateCast(
7362             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
7363         V1 = Builder.CreateCast(
7364             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
7365       }
7366       // Add V0 and V1 to later analysis to try to find and remove matching
7367       // instruction, if any.
7368       for (Value *V : {V0, V1}) {
7369         if (auto *I = dyn_cast<Instruction>(V)) {
7370           GatherShuffleSeq.insert(I);
7371           CSEBlocks.insert(I->getParent());
7372         }
7373       }
7374 
7375       // Create shuffle to take alternate operations from the vector.
7376       // Also, gather up main and alt scalar ops to propagate IR flags to
7377       // each vector operation.
7378       ValueList OpScalars, AltScalars;
7379       SmallVector<int> Mask;
7380       buildShuffleEntryMask(
7381           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
7382           [E](Instruction *I) {
7383             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
7384             return isAlternateInstruction(I, E->getMainOp(), E->getAltOp());
7385           },
7386           Mask, &OpScalars, &AltScalars);
7387 
7388       propagateIRFlags(V0, OpScalars);
7389       propagateIRFlags(V1, AltScalars);
7390 
7391       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
7392       if (auto *I = dyn_cast<Instruction>(V)) {
7393         V = propagateMetadata(I, E->Scalars);
7394         GatherShuffleSeq.insert(I);
7395         CSEBlocks.insert(I->getParent());
7396       }
7397       V = ShuffleBuilder.finalize(V);
7398 
7399       E->VectorizedValue = V;
7400       ++NumVectorInstructions;
7401 
7402       return V;
7403     }
7404     default:
7405     llvm_unreachable("unknown inst");
7406   }
7407   return nullptr;
7408 }
7409 
7410 Value *BoUpSLP::vectorizeTree() {
7411   ExtraValueToDebugLocsMap ExternallyUsedValues;
7412   return vectorizeTree(ExternallyUsedValues);
7413 }
7414 
7415 Value *
7416 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
7417   // All blocks must be scheduled before any instructions are inserted.
7418   for (auto &BSIter : BlocksSchedules) {
7419     scheduleBlock(BSIter.second.get());
7420   }
7421 
7422   Builder.SetInsertPoint(&F->getEntryBlock().front());
7423   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
7424 
7425   // If the vectorized tree can be rewritten in a smaller type, we truncate the
7426   // vectorized root. InstCombine will then rewrite the entire expression. We
7427   // sign extend the extracted values below.
7428   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
7429   if (MinBWs.count(ScalarRoot)) {
7430     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
7431       // If current instr is a phi and not the last phi, insert it after the
7432       // last phi node.
7433       if (isa<PHINode>(I))
7434         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
7435       else
7436         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
7437     }
7438     auto BundleWidth = VectorizableTree[0]->Scalars.size();
7439     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
7440     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
7441     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
7442     VectorizableTree[0]->VectorizedValue = Trunc;
7443   }
7444 
7445   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
7446                     << " values .\n");
7447 
7448   // Extract all of the elements with the external uses.
7449   for (const auto &ExternalUse : ExternalUses) {
7450     Value *Scalar = ExternalUse.Scalar;
7451     llvm::User *User = ExternalUse.User;
7452 
7453     // Skip users that we already RAUW. This happens when one instruction
7454     // has multiple uses of the same value.
7455     if (User && !is_contained(Scalar->users(), User))
7456       continue;
7457     TreeEntry *E = getTreeEntry(Scalar);
7458     assert(E && "Invalid scalar");
7459     assert(E->State != TreeEntry::NeedToGather &&
7460            "Extracting from a gather list");
7461 
7462     Value *Vec = E->VectorizedValue;
7463     assert(Vec && "Can't find vectorizable value");
7464 
7465     Value *Lane = Builder.getInt32(ExternalUse.Lane);
7466     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
7467       if (Scalar->getType() != Vec->getType()) {
7468         Value *Ex;
7469         // "Reuse" the existing extract to improve final codegen.
7470         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
7471           Ex = Builder.CreateExtractElement(ES->getOperand(0),
7472                                             ES->getOperand(1));
7473         } else {
7474           Ex = Builder.CreateExtractElement(Vec, Lane);
7475         }
7476         // If necessary, sign-extend or zero-extend ScalarRoot
7477         // to the larger type.
7478         if (!MinBWs.count(ScalarRoot))
7479           return Ex;
7480         if (MinBWs[ScalarRoot].second)
7481           return Builder.CreateSExt(Ex, Scalar->getType());
7482         return Builder.CreateZExt(Ex, Scalar->getType());
7483       }
7484       assert(isa<FixedVectorType>(Scalar->getType()) &&
7485              isa<InsertElementInst>(Scalar) &&
7486              "In-tree scalar of vector type is not insertelement?");
7487       return Vec;
7488     };
7489     // If User == nullptr, the Scalar is used as extra arg. Generate
7490     // ExtractElement instruction and update the record for this scalar in
7491     // ExternallyUsedValues.
7492     if (!User) {
7493       assert(ExternallyUsedValues.count(Scalar) &&
7494              "Scalar with nullptr as an external user must be registered in "
7495              "ExternallyUsedValues map");
7496       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7497         Builder.SetInsertPoint(VecI->getParent(),
7498                                std::next(VecI->getIterator()));
7499       } else {
7500         Builder.SetInsertPoint(&F->getEntryBlock().front());
7501       }
7502       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7503       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
7504       auto &NewInstLocs = ExternallyUsedValues[NewInst];
7505       auto It = ExternallyUsedValues.find(Scalar);
7506       assert(It != ExternallyUsedValues.end() &&
7507              "Externally used scalar is not found in ExternallyUsedValues");
7508       NewInstLocs.append(It->second);
7509       ExternallyUsedValues.erase(Scalar);
7510       // Required to update internally referenced instructions.
7511       Scalar->replaceAllUsesWith(NewInst);
7512       continue;
7513     }
7514 
7515     // Generate extracts for out-of-tree users.
7516     // Find the insertion point for the extractelement lane.
7517     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
7518       if (PHINode *PH = dyn_cast<PHINode>(User)) {
7519         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
7520           if (PH->getIncomingValue(i) == Scalar) {
7521             Instruction *IncomingTerminator =
7522                 PH->getIncomingBlock(i)->getTerminator();
7523             if (isa<CatchSwitchInst>(IncomingTerminator)) {
7524               Builder.SetInsertPoint(VecI->getParent(),
7525                                      std::next(VecI->getIterator()));
7526             } else {
7527               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
7528             }
7529             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7530             CSEBlocks.insert(PH->getIncomingBlock(i));
7531             PH->setOperand(i, NewInst);
7532           }
7533         }
7534       } else {
7535         Builder.SetInsertPoint(cast<Instruction>(User));
7536         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7537         CSEBlocks.insert(cast<Instruction>(User)->getParent());
7538         User->replaceUsesOfWith(Scalar, NewInst);
7539       }
7540     } else {
7541       Builder.SetInsertPoint(&F->getEntryBlock().front());
7542       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
7543       CSEBlocks.insert(&F->getEntryBlock());
7544       User->replaceUsesOfWith(Scalar, NewInst);
7545     }
7546 
7547     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
7548   }
7549 
7550   // For each vectorized value:
7551   for (auto &TEPtr : VectorizableTree) {
7552     TreeEntry *Entry = TEPtr.get();
7553 
7554     // No need to handle users of gathered values.
7555     if (Entry->State == TreeEntry::NeedToGather)
7556       continue;
7557 
7558     assert(Entry->VectorizedValue && "Can't find vectorizable value");
7559 
7560     // For each lane:
7561     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
7562       Value *Scalar = Entry->Scalars[Lane];
7563 
7564 #ifndef NDEBUG
7565       Type *Ty = Scalar->getType();
7566       if (!Ty->isVoidTy()) {
7567         for (User *U : Scalar->users()) {
7568           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
7569 
7570           // It is legal to delete users in the ignorelist.
7571           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
7572                   (isa_and_nonnull<Instruction>(U) &&
7573                    isDeleted(cast<Instruction>(U)))) &&
7574                  "Deleting out-of-tree value");
7575         }
7576       }
7577 #endif
7578       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
7579       eraseInstruction(cast<Instruction>(Scalar));
7580     }
7581   }
7582 
7583   Builder.ClearInsertionPoint();
7584   InstrElementSize.clear();
7585 
7586   return VectorizableTree[0]->VectorizedValue;
7587 }
7588 
7589 void BoUpSLP::optimizeGatherSequence() {
7590   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
7591                     << " gather sequences instructions.\n");
7592   // LICM InsertElementInst sequences.
7593   for (Instruction *I : GatherShuffleSeq) {
7594     if (isDeleted(I))
7595       continue;
7596 
7597     // Check if this block is inside a loop.
7598     Loop *L = LI->getLoopFor(I->getParent());
7599     if (!L)
7600       continue;
7601 
7602     // Check if it has a preheader.
7603     BasicBlock *PreHeader = L->getLoopPreheader();
7604     if (!PreHeader)
7605       continue;
7606 
7607     // If the vector or the element that we insert into it are
7608     // instructions that are defined in this basic block then we can't
7609     // hoist this instruction.
7610     if (any_of(I->operands(), [L](Value *V) {
7611           auto *OpI = dyn_cast<Instruction>(V);
7612           return OpI && L->contains(OpI);
7613         }))
7614       continue;
7615 
7616     // We can hoist this instruction. Move it to the pre-header.
7617     I->moveBefore(PreHeader->getTerminator());
7618   }
7619 
7620   // Make a list of all reachable blocks in our CSE queue.
7621   SmallVector<const DomTreeNode *, 8> CSEWorkList;
7622   CSEWorkList.reserve(CSEBlocks.size());
7623   for (BasicBlock *BB : CSEBlocks)
7624     if (DomTreeNode *N = DT->getNode(BB)) {
7625       assert(DT->isReachableFromEntry(N));
7626       CSEWorkList.push_back(N);
7627     }
7628 
7629   // Sort blocks by domination. This ensures we visit a block after all blocks
7630   // dominating it are visited.
7631   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
7632     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
7633            "Different nodes should have different DFS numbers");
7634     return A->getDFSNumIn() < B->getDFSNumIn();
7635   });
7636 
7637   // Less defined shuffles can be replaced by the more defined copies.
7638   // Between two shuffles one is less defined if it has the same vector operands
7639   // and its mask indeces are the same as in the first one or undefs. E.g.
7640   // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
7641   // poison, <0, 0, 0, 0>.
7642   auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
7643                                            SmallVectorImpl<int> &NewMask) {
7644     if (I1->getType() != I2->getType())
7645       return false;
7646     auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
7647     auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
7648     if (!SI1 || !SI2)
7649       return I1->isIdenticalTo(I2);
7650     if (SI1->isIdenticalTo(SI2))
7651       return true;
7652     for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
7653       if (SI1->getOperand(I) != SI2->getOperand(I))
7654         return false;
7655     // Check if the second instruction is more defined than the first one.
7656     NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
7657     ArrayRef<int> SM1 = SI1->getShuffleMask();
7658     // Count trailing undefs in the mask to check the final number of used
7659     // registers.
7660     unsigned LastUndefsCnt = 0;
7661     for (int I = 0, E = NewMask.size(); I < E; ++I) {
7662       if (SM1[I] == UndefMaskElem)
7663         ++LastUndefsCnt;
7664       else
7665         LastUndefsCnt = 0;
7666       if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
7667           NewMask[I] != SM1[I])
7668         return false;
7669       if (NewMask[I] == UndefMaskElem)
7670         NewMask[I] = SM1[I];
7671     }
7672     // Check if the last undefs actually change the final number of used vector
7673     // registers.
7674     return SM1.size() - LastUndefsCnt > 1 &&
7675            TTI->getNumberOfParts(SI1->getType()) ==
7676                TTI->getNumberOfParts(
7677                    FixedVectorType::get(SI1->getType()->getElementType(),
7678                                         SM1.size() - LastUndefsCnt));
7679   };
7680   // Perform O(N^2) search over the gather/shuffle sequences and merge identical
7681   // instructions. TODO: We can further optimize this scan if we split the
7682   // instructions into different buckets based on the insert lane.
7683   SmallVector<Instruction *, 16> Visited;
7684   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
7685     assert(*I &&
7686            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
7687            "Worklist not sorted properly!");
7688     BasicBlock *BB = (*I)->getBlock();
7689     // For all instructions in blocks containing gather sequences:
7690     for (Instruction &In : llvm::make_early_inc_range(*BB)) {
7691       if (isDeleted(&In))
7692         continue;
7693       if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
7694           !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
7695         continue;
7696 
7697       // Check if we can replace this instruction with any of the
7698       // visited instructions.
7699       bool Replaced = false;
7700       for (Instruction *&V : Visited) {
7701         SmallVector<int> NewMask;
7702         if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
7703             DT->dominates(V->getParent(), In.getParent())) {
7704           In.replaceAllUsesWith(V);
7705           eraseInstruction(&In);
7706           if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
7707             if (!NewMask.empty())
7708               SI->setShuffleMask(NewMask);
7709           Replaced = true;
7710           break;
7711         }
7712         if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
7713             GatherShuffleSeq.contains(V) &&
7714             IsIdenticalOrLessDefined(V, &In, NewMask) &&
7715             DT->dominates(In.getParent(), V->getParent())) {
7716           In.moveAfter(V);
7717           V->replaceAllUsesWith(&In);
7718           eraseInstruction(V);
7719           if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
7720             if (!NewMask.empty())
7721               SI->setShuffleMask(NewMask);
7722           V = &In;
7723           Replaced = true;
7724           break;
7725         }
7726       }
7727       if (!Replaced) {
7728         assert(!is_contained(Visited, &In));
7729         Visited.push_back(&In);
7730       }
7731     }
7732   }
7733   CSEBlocks.clear();
7734   GatherShuffleSeq.clear();
7735 }
7736 
7737 BoUpSLP::ScheduleData *
7738 BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
7739   ScheduleData *Bundle = nullptr;
7740   ScheduleData *PrevInBundle = nullptr;
7741   for (Value *V : VL) {
7742     if (doesNotNeedToBeScheduled(V))
7743       continue;
7744     ScheduleData *BundleMember = getScheduleData(V);
7745     assert(BundleMember &&
7746            "no ScheduleData for bundle member "
7747            "(maybe not in same basic block)");
7748     assert(BundleMember->isSchedulingEntity() &&
7749            "bundle member already part of other bundle");
7750     if (PrevInBundle) {
7751       PrevInBundle->NextInBundle = BundleMember;
7752     } else {
7753       Bundle = BundleMember;
7754     }
7755 
7756     // Group the instructions to a bundle.
7757     BundleMember->FirstInBundle = Bundle;
7758     PrevInBundle = BundleMember;
7759   }
7760   assert(Bundle && "Failed to find schedule bundle");
7761   return Bundle;
7762 }
7763 
7764 // Groups the instructions to a bundle (which is then a single scheduling entity)
7765 // and schedules instructions until the bundle gets ready.
7766 Optional<BoUpSLP::ScheduleData *>
7767 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
7768                                             const InstructionsState &S) {
7769   // No need to schedule PHIs, insertelement, extractelement and extractvalue
7770   // instructions.
7771   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
7772       doesNotNeedToSchedule(VL))
7773     return nullptr;
7774 
7775   // Initialize the instruction bundle.
7776   Instruction *OldScheduleEnd = ScheduleEnd;
7777   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
7778 
7779   auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
7780                                                          ScheduleData *Bundle) {
7781     // The scheduling region got new instructions at the lower end (or it is a
7782     // new region for the first bundle). This makes it necessary to
7783     // recalculate all dependencies.
7784     // It is seldom that this needs to be done a second time after adding the
7785     // initial bundle to the region.
7786     if (ScheduleEnd != OldScheduleEnd) {
7787       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
7788         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
7789       ReSchedule = true;
7790     }
7791     if (Bundle) {
7792       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
7793                         << " in block " << BB->getName() << "\n");
7794       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
7795     }
7796 
7797     if (ReSchedule) {
7798       resetSchedule();
7799       initialFillReadyList(ReadyInsts);
7800     }
7801 
7802     // Now try to schedule the new bundle or (if no bundle) just calculate
7803     // dependencies. As soon as the bundle is "ready" it means that there are no
7804     // cyclic dependencies and we can schedule it. Note that's important that we
7805     // don't "schedule" the bundle yet (see cancelScheduling).
7806     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
7807            !ReadyInsts.empty()) {
7808       ScheduleData *Picked = ReadyInsts.pop_back_val();
7809       assert(Picked->isSchedulingEntity() && Picked->isReady() &&
7810              "must be ready to schedule");
7811       schedule(Picked, ReadyInsts);
7812     }
7813   };
7814 
7815   // Make sure that the scheduling region contains all
7816   // instructions of the bundle.
7817   for (Value *V : VL) {
7818     if (doesNotNeedToBeScheduled(V))
7819       continue;
7820     if (!extendSchedulingRegion(V, S)) {
7821       // If the scheduling region got new instructions at the lower end (or it
7822       // is a new region for the first bundle). This makes it necessary to
7823       // recalculate all dependencies.
7824       // Otherwise the compiler may crash trying to incorrectly calculate
7825       // dependencies and emit instruction in the wrong order at the actual
7826       // scheduling.
7827       TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
7828       return None;
7829     }
7830   }
7831 
7832   bool ReSchedule = false;
7833   for (Value *V : VL) {
7834     if (doesNotNeedToBeScheduled(V))
7835       continue;
7836     ScheduleData *BundleMember = getScheduleData(V);
7837     assert(BundleMember &&
7838            "no ScheduleData for bundle member (maybe not in same basic block)");
7839 
7840     // Make sure we don't leave the pieces of the bundle in the ready list when
7841     // whole bundle might not be ready.
7842     ReadyInsts.remove(BundleMember);
7843 
7844     if (!BundleMember->IsScheduled)
7845       continue;
7846     // A bundle member was scheduled as single instruction before and now
7847     // needs to be scheduled as part of the bundle. We just get rid of the
7848     // existing schedule.
7849     LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
7850                       << " was already scheduled\n");
7851     ReSchedule = true;
7852   }
7853 
7854   auto *Bundle = buildBundle(VL);
7855   TryScheduleBundleImpl(ReSchedule, Bundle);
7856   if (!Bundle->isReady()) {
7857     cancelScheduling(VL, S.OpValue);
7858     return None;
7859   }
7860   return Bundle;
7861 }
7862 
7863 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
7864                                                 Value *OpValue) {
7865   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
7866       doesNotNeedToSchedule(VL))
7867     return;
7868 
7869   if (doesNotNeedToBeScheduled(OpValue))
7870     OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
7871   ScheduleData *Bundle = getScheduleData(OpValue);
7872   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
7873   assert(!Bundle->IsScheduled &&
7874          "Can't cancel bundle which is already scheduled");
7875   assert(Bundle->isSchedulingEntity() &&
7876          (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
7877          "tried to unbundle something which is not a bundle");
7878 
7879   // Remove the bundle from the ready list.
7880   if (Bundle->isReady())
7881     ReadyInsts.remove(Bundle);
7882 
7883   // Un-bundle: make single instructions out of the bundle.
7884   ScheduleData *BundleMember = Bundle;
7885   while (BundleMember) {
7886     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
7887     BundleMember->FirstInBundle = BundleMember;
7888     ScheduleData *Next = BundleMember->NextInBundle;
7889     BundleMember->NextInBundle = nullptr;
7890     BundleMember->TE = nullptr;
7891     if (BundleMember->unscheduledDepsInBundle() == 0) {
7892       ReadyInsts.insert(BundleMember);
7893     }
7894     BundleMember = Next;
7895   }
7896 }
7897 
7898 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
7899   // Allocate a new ScheduleData for the instruction.
7900   if (ChunkPos >= ChunkSize) {
7901     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
7902     ChunkPos = 0;
7903   }
7904   return &(ScheduleDataChunks.back()[ChunkPos++]);
7905 }
7906 
7907 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
7908                                                       const InstructionsState &S) {
7909   if (getScheduleData(V, isOneOf(S, V)))
7910     return true;
7911   Instruction *I = dyn_cast<Instruction>(V);
7912   assert(I && "bundle member must be an instruction");
7913   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
7914          !doesNotNeedToBeScheduled(I) &&
7915          "phi nodes/insertelements/extractelements/extractvalues don't need to "
7916          "be scheduled");
7917   auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
7918     ScheduleData *ISD = getScheduleData(I);
7919     if (!ISD)
7920       return false;
7921     assert(isInSchedulingRegion(ISD) &&
7922            "ScheduleData not in scheduling region");
7923     ScheduleData *SD = allocateScheduleDataChunks();
7924     SD->Inst = I;
7925     SD->init(SchedulingRegionID, S.OpValue);
7926     ExtraScheduleDataMap[I][S.OpValue] = SD;
7927     return true;
7928   };
7929   if (CheckScheduleForI(I))
7930     return true;
7931   if (!ScheduleStart) {
7932     // It's the first instruction in the new region.
7933     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
7934     ScheduleStart = I;
7935     ScheduleEnd = I->getNextNode();
7936     if (isOneOf(S, I) != I)
7937       CheckScheduleForI(I);
7938     assert(ScheduleEnd && "tried to vectorize a terminator?");
7939     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
7940     return true;
7941   }
7942   // Search up and down at the same time, because we don't know if the new
7943   // instruction is above or below the existing scheduling region.
7944   BasicBlock::reverse_iterator UpIter =
7945       ++ScheduleStart->getIterator().getReverse();
7946   BasicBlock::reverse_iterator UpperEnd = BB->rend();
7947   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
7948   BasicBlock::iterator LowerEnd = BB->end();
7949   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
7950          &*DownIter != I) {
7951     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
7952       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
7953       return false;
7954     }
7955 
7956     ++UpIter;
7957     ++DownIter;
7958   }
7959   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
7960     assert(I->getParent() == ScheduleStart->getParent() &&
7961            "Instruction is in wrong basic block.");
7962     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
7963     ScheduleStart = I;
7964     if (isOneOf(S, I) != I)
7965       CheckScheduleForI(I);
7966     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
7967                       << "\n");
7968     return true;
7969   }
7970   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
7971          "Expected to reach top of the basic block or instruction down the "
7972          "lower end.");
7973   assert(I->getParent() == ScheduleEnd->getParent() &&
7974          "Instruction is in wrong basic block.");
7975   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
7976                    nullptr);
7977   ScheduleEnd = I->getNextNode();
7978   if (isOneOf(S, I) != I)
7979     CheckScheduleForI(I);
7980   assert(ScheduleEnd && "tried to vectorize a terminator?");
7981   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
7982   return true;
7983 }
7984 
7985 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
7986                                                 Instruction *ToI,
7987                                                 ScheduleData *PrevLoadStore,
7988                                                 ScheduleData *NextLoadStore) {
7989   ScheduleData *CurrentLoadStore = PrevLoadStore;
7990   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
7991     // No need to allocate data for non-schedulable instructions.
7992     if (doesNotNeedToBeScheduled(I))
7993       continue;
7994     ScheduleData *SD = ScheduleDataMap.lookup(I);
7995     if (!SD) {
7996       SD = allocateScheduleDataChunks();
7997       ScheduleDataMap[I] = SD;
7998       SD->Inst = I;
7999     }
8000     assert(!isInSchedulingRegion(SD) &&
8001            "new ScheduleData already in scheduling region");
8002     SD->init(SchedulingRegionID, I);
8003 
8004     if (I->mayReadOrWriteMemory() &&
8005         (!isa<IntrinsicInst>(I) ||
8006          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
8007           cast<IntrinsicInst>(I)->getIntrinsicID() !=
8008               Intrinsic::pseudoprobe))) {
8009       // Update the linked list of memory accessing instructions.
8010       if (CurrentLoadStore) {
8011         CurrentLoadStore->NextLoadStore = SD;
8012       } else {
8013         FirstLoadStoreInRegion = SD;
8014       }
8015       CurrentLoadStore = SD;
8016     }
8017   }
8018   if (NextLoadStore) {
8019     if (CurrentLoadStore)
8020       CurrentLoadStore->NextLoadStore = NextLoadStore;
8021   } else {
8022     LastLoadStoreInRegion = CurrentLoadStore;
8023   }
8024 }
8025 
8026 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
8027                                                      bool InsertInReadyList,
8028                                                      BoUpSLP *SLP) {
8029   assert(SD->isSchedulingEntity());
8030 
8031   SmallVector<ScheduleData *, 10> WorkList;
8032   WorkList.push_back(SD);
8033 
8034   while (!WorkList.empty()) {
8035     ScheduleData *SD = WorkList.pop_back_val();
8036     for (ScheduleData *BundleMember = SD; BundleMember;
8037          BundleMember = BundleMember->NextInBundle) {
8038       assert(isInSchedulingRegion(BundleMember));
8039       if (BundleMember->hasValidDependencies())
8040         continue;
8041 
8042       LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
8043                  << "\n");
8044       BundleMember->Dependencies = 0;
8045       BundleMember->resetUnscheduledDeps();
8046 
8047       // Handle def-use chain dependencies.
8048       if (BundleMember->OpValue != BundleMember->Inst) {
8049         if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
8050           BundleMember->Dependencies++;
8051           ScheduleData *DestBundle = UseSD->FirstInBundle;
8052           if (!DestBundle->IsScheduled)
8053             BundleMember->incrementUnscheduledDeps(1);
8054           if (!DestBundle->hasValidDependencies())
8055             WorkList.push_back(DestBundle);
8056         }
8057       } else {
8058         for (User *U : BundleMember->Inst->users()) {
8059           if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
8060             BundleMember->Dependencies++;
8061             ScheduleData *DestBundle = UseSD->FirstInBundle;
8062             if (!DestBundle->IsScheduled)
8063               BundleMember->incrementUnscheduledDeps(1);
8064             if (!DestBundle->hasValidDependencies())
8065               WorkList.push_back(DestBundle);
8066           }
8067         }
8068       }
8069 
8070       // Handle the memory dependencies (if any).
8071       ScheduleData *DepDest = BundleMember->NextLoadStore;
8072       if (!DepDest)
8073         continue;
8074       Instruction *SrcInst = BundleMember->Inst;
8075       assert(SrcInst->mayReadOrWriteMemory() &&
8076              "NextLoadStore list for non memory effecting bundle?");
8077       MemoryLocation SrcLoc = getLocation(SrcInst);
8078       bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
8079       unsigned numAliased = 0;
8080       unsigned DistToSrc = 1;
8081 
8082       for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
8083         assert(isInSchedulingRegion(DepDest));
8084 
8085         // We have two limits to reduce the complexity:
8086         // 1) AliasedCheckLimit: It's a small limit to reduce calls to
8087         //    SLP->isAliased (which is the expensive part in this loop).
8088         // 2) MaxMemDepDistance: It's for very large blocks and it aborts
8089         //    the whole loop (even if the loop is fast, it's quadratic).
8090         //    It's important for the loop break condition (see below) to
8091         //    check this limit even between two read-only instructions.
8092         if (DistToSrc >= MaxMemDepDistance ||
8093             ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
8094              (numAliased >= AliasedCheckLimit ||
8095               SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
8096 
8097           // We increment the counter only if the locations are aliased
8098           // (instead of counting all alias checks). This gives a better
8099           // balance between reduced runtime and accurate dependencies.
8100           numAliased++;
8101 
8102           DepDest->MemoryDependencies.push_back(BundleMember);
8103           BundleMember->Dependencies++;
8104           ScheduleData *DestBundle = DepDest->FirstInBundle;
8105           if (!DestBundle->IsScheduled) {
8106             BundleMember->incrementUnscheduledDeps(1);
8107           }
8108           if (!DestBundle->hasValidDependencies()) {
8109             WorkList.push_back(DestBundle);
8110           }
8111         }
8112 
8113         // Example, explaining the loop break condition: Let's assume our
8114         // starting instruction is i0 and MaxMemDepDistance = 3.
8115         //
8116         //                      +--------v--v--v
8117         //             i0,i1,i2,i3,i4,i5,i6,i7,i8
8118         //             +--------^--^--^
8119         //
8120         // MaxMemDepDistance let us stop alias-checking at i3 and we add
8121         // dependencies from i0 to i3,i4,.. (even if they are not aliased).
8122         // Previously we already added dependencies from i3 to i6,i7,i8
8123         // (because of MaxMemDepDistance). As we added a dependency from
8124         // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
8125         // and we can abort this loop at i6.
8126         if (DistToSrc >= 2 * MaxMemDepDistance)
8127           break;
8128         DistToSrc++;
8129       }
8130     }
8131     if (InsertInReadyList && SD->isReady()) {
8132       ReadyInsts.insert(SD);
8133       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
8134                         << "\n");
8135     }
8136   }
8137 }
8138 
8139 void BoUpSLP::BlockScheduling::resetSchedule() {
8140   assert(ScheduleStart &&
8141          "tried to reset schedule on block which has not been scheduled");
8142   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
8143     doForAllOpcodes(I, [&](ScheduleData *SD) {
8144       assert(isInSchedulingRegion(SD) &&
8145              "ScheduleData not in scheduling region");
8146       SD->IsScheduled = false;
8147       SD->resetUnscheduledDeps();
8148     });
8149   }
8150   ReadyInsts.clear();
8151 }
8152 
8153 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
8154   if (!BS->ScheduleStart)
8155     return;
8156 
8157   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
8158 
8159   BS->resetSchedule();
8160 
8161   // For the real scheduling we use a more sophisticated ready-list: it is
8162   // sorted by the original instruction location. This lets the final schedule
8163   // be as  close as possible to the original instruction order.
8164   struct ScheduleDataCompare {
8165     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
8166       return SD2->SchedulingPriority < SD1->SchedulingPriority;
8167     }
8168   };
8169   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
8170 
8171   // Ensure that all dependency data is updated and fill the ready-list with
8172   // initial instructions.
8173   int Idx = 0;
8174   int NumToSchedule = 0;
8175   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
8176        I = I->getNextNode()) {
8177     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
8178       TreeEntry *SDTE = getTreeEntry(SD->Inst);
8179       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
8180               SD->isPartOfBundle() ==
8181                   (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
8182              "scheduler and vectorizer bundle mismatch");
8183       SD->FirstInBundle->SchedulingPriority = Idx++;
8184       if (SD->isSchedulingEntity()) {
8185         BS->calculateDependencies(SD, false, this);
8186         NumToSchedule++;
8187       }
8188     });
8189   }
8190   BS->initialFillReadyList(ReadyInsts);
8191 
8192   Instruction *LastScheduledInst = BS->ScheduleEnd;
8193   MemoryAccess *MemInsertPt = nullptr;
8194   if (MSSA) {
8195     for (auto I = LastScheduledInst->getIterator(); I != BS->BB->end(); I++) {
8196       if (auto *Access = MSSA->getMemoryAccess(&*I)) {
8197         MemInsertPt = Access;
8198         break;
8199       }
8200     }
8201   }
8202 
8203   // Do the "real" scheduling.
8204   while (!ReadyInsts.empty()) {
8205     ScheduleData *picked = *ReadyInsts.begin();
8206     ReadyInsts.erase(ReadyInsts.begin());
8207 
8208     // Move the scheduled instruction(s) to their dedicated places, if not
8209     // there yet.
8210     for (ScheduleData *BundleMember = picked; BundleMember;
8211          BundleMember = BundleMember->NextInBundle) {
8212       Instruction *pickedInst = BundleMember->Inst;
8213       if (pickedInst->getNextNode() != LastScheduledInst) {
8214         pickedInst->moveBefore(LastScheduledInst);
8215         if (MSSA) {
8216           MemorySSAUpdater MSSAU(MSSA);
8217           if (auto *Access = MSSA->getMemoryAccess(pickedInst)) {
8218             if (MemInsertPt)
8219               MSSAU.moveBefore(Access, cast<MemoryUseOrDef>(MemInsertPt));
8220             else
8221               MSSAU.moveToPlace(Access, BS->BB,
8222                                 MemorySSA::InsertionPlace::End);
8223           }
8224         }
8225       }
8226 
8227       LastScheduledInst = pickedInst;
8228       if (MSSA)
8229         if (auto *Access = MSSA->getMemoryAccess(LastScheduledInst))
8230           MemInsertPt = Access;
8231     }
8232 
8233     BS->schedule(picked, ReadyInsts);
8234     NumToSchedule--;
8235   }
8236   assert(NumToSchedule == 0 && "could not schedule all instructions");
8237 
8238   // Check that we didn't break any of our invariants.
8239 #ifdef EXPENSIVE_CHECKS
8240   BS->verify();
8241 #endif
8242 
8243 #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
8244   // Check that all schedulable entities got scheduled
8245   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
8246     BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
8247       if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
8248         assert(SD->IsScheduled && "must be scheduled at this point");
8249       }
8250     });
8251   }
8252 #endif
8253 
8254   // Avoid duplicate scheduling of the block.
8255   BS->ScheduleStart = nullptr;
8256 }
8257 
8258 unsigned BoUpSLP::getVectorElementSize(Value *V) {
8259   // If V is a store, just return the width of the stored value (or value
8260   // truncated just before storing) without traversing the expression tree.
8261   // This is the common case.
8262   if (auto *Store = dyn_cast<StoreInst>(V)) {
8263     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
8264       return DL->getTypeSizeInBits(Trunc->getSrcTy());
8265     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
8266   }
8267 
8268   if (auto *IEI = dyn_cast<InsertElementInst>(V))
8269     return getVectorElementSize(IEI->getOperand(1));
8270 
8271   auto E = InstrElementSize.find(V);
8272   if (E != InstrElementSize.end())
8273     return E->second;
8274 
8275   // If V is not a store, we can traverse the expression tree to find loads
8276   // that feed it. The type of the loaded value may indicate a more suitable
8277   // width than V's type. We want to base the vector element size on the width
8278   // of memory operations where possible.
8279   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
8280   SmallPtrSet<Instruction *, 16> Visited;
8281   if (auto *I = dyn_cast<Instruction>(V)) {
8282     Worklist.emplace_back(I, I->getParent());
8283     Visited.insert(I);
8284   }
8285 
8286   // Traverse the expression tree in bottom-up order looking for loads. If we
8287   // encounter an instruction we don't yet handle, we give up.
8288   auto Width = 0u;
8289   while (!Worklist.empty()) {
8290     Instruction *I;
8291     BasicBlock *Parent;
8292     std::tie(I, Parent) = Worklist.pop_back_val();
8293 
8294     // We should only be looking at scalar instructions here. If the current
8295     // instruction has a vector type, skip.
8296     auto *Ty = I->getType();
8297     if (isa<VectorType>(Ty))
8298       continue;
8299 
8300     // If the current instruction is a load, update MaxWidth to reflect the
8301     // width of the loaded value.
8302     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
8303         isa<ExtractValueInst>(I))
8304       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
8305 
8306     // Otherwise, we need to visit the operands of the instruction. We only
8307     // handle the interesting cases from buildTree here. If an operand is an
8308     // instruction we haven't yet visited and from the same basic block as the
8309     // user or the use is a PHI node, we add it to the worklist.
8310     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
8311              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
8312              isa<UnaryOperator>(I)) {
8313       for (Use &U : I->operands())
8314         if (auto *J = dyn_cast<Instruction>(U.get()))
8315           if (Visited.insert(J).second &&
8316               (isa<PHINode>(I) || J->getParent() == Parent))
8317             Worklist.emplace_back(J, J->getParent());
8318     } else {
8319       break;
8320     }
8321   }
8322 
8323   // If we didn't encounter a memory access in the expression tree, or if we
8324   // gave up for some reason, just return the width of V. Otherwise, return the
8325   // maximum width we found.
8326   if (!Width) {
8327     if (auto *CI = dyn_cast<CmpInst>(V))
8328       V = CI->getOperand(0);
8329     Width = DL->getTypeSizeInBits(V->getType());
8330   }
8331 
8332   for (Instruction *I : Visited)
8333     InstrElementSize[I] = Width;
8334 
8335   return Width;
8336 }
8337 
8338 // Determine if a value V in a vectorizable expression Expr can be demoted to a
8339 // smaller type with a truncation. We collect the values that will be demoted
8340 // in ToDemote and additional roots that require investigating in Roots.
8341 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
8342                                   SmallVectorImpl<Value *> &ToDemote,
8343                                   SmallVectorImpl<Value *> &Roots) {
8344   // We can always demote constants.
8345   if (isa<Constant>(V)) {
8346     ToDemote.push_back(V);
8347     return true;
8348   }
8349 
8350   // If the value is not an instruction in the expression with only one use, it
8351   // cannot be demoted.
8352   auto *I = dyn_cast<Instruction>(V);
8353   if (!I || !I->hasOneUse() || !Expr.count(I))
8354     return false;
8355 
8356   switch (I->getOpcode()) {
8357 
8358   // We can always demote truncations and extensions. Since truncations can
8359   // seed additional demotion, we save the truncated value.
8360   case Instruction::Trunc:
8361     Roots.push_back(I->getOperand(0));
8362     break;
8363   case Instruction::ZExt:
8364   case Instruction::SExt:
8365     if (isa<ExtractElementInst>(I->getOperand(0)) ||
8366         isa<InsertElementInst>(I->getOperand(0)))
8367       return false;
8368     break;
8369 
8370   // We can demote certain binary operations if we can demote both of their
8371   // operands.
8372   case Instruction::Add:
8373   case Instruction::Sub:
8374   case Instruction::Mul:
8375   case Instruction::And:
8376   case Instruction::Or:
8377   case Instruction::Xor:
8378     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
8379         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
8380       return false;
8381     break;
8382 
8383   // We can demote selects if we can demote their true and false values.
8384   case Instruction::Select: {
8385     SelectInst *SI = cast<SelectInst>(I);
8386     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
8387         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
8388       return false;
8389     break;
8390   }
8391 
8392   // We can demote phis if we can demote all their incoming operands. Note that
8393   // we don't need to worry about cycles since we ensure single use above.
8394   case Instruction::PHI: {
8395     PHINode *PN = cast<PHINode>(I);
8396     for (Value *IncValue : PN->incoming_values())
8397       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
8398         return false;
8399     break;
8400   }
8401 
8402   // Otherwise, conservatively give up.
8403   default:
8404     return false;
8405   }
8406 
8407   // Record the value that we can demote.
8408   ToDemote.push_back(V);
8409   return true;
8410 }
8411 
8412 void BoUpSLP::computeMinimumValueSizes() {
8413   // If there are no external uses, the expression tree must be rooted by a
8414   // store. We can't demote in-memory values, so there is nothing to do here.
8415   if (ExternalUses.empty())
8416     return;
8417 
8418   // We only attempt to truncate integer expressions.
8419   auto &TreeRoot = VectorizableTree[0]->Scalars;
8420   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
8421   if (!TreeRootIT)
8422     return;
8423 
8424   // If the expression is not rooted by a store, these roots should have
8425   // external uses. We will rely on InstCombine to rewrite the expression in
8426   // the narrower type. However, InstCombine only rewrites single-use values.
8427   // This means that if a tree entry other than a root is used externally, it
8428   // must have multiple uses and InstCombine will not rewrite it. The code
8429   // below ensures that only the roots are used externally.
8430   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
8431   for (auto &EU : ExternalUses)
8432     if (!Expr.erase(EU.Scalar))
8433       return;
8434   if (!Expr.empty())
8435     return;
8436 
8437   // Collect the scalar values of the vectorizable expression. We will use this
8438   // context to determine which values can be demoted. If we see a truncation,
8439   // we mark it as seeding another demotion.
8440   for (auto &EntryPtr : VectorizableTree)
8441     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
8442 
8443   // Ensure the roots of the vectorizable tree don't form a cycle. They must
8444   // have a single external user that is not in the vectorizable tree.
8445   for (auto *Root : TreeRoot)
8446     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
8447       return;
8448 
8449   // Conservatively determine if we can actually truncate the roots of the
8450   // expression. Collect the values that can be demoted in ToDemote and
8451   // additional roots that require investigating in Roots.
8452   SmallVector<Value *, 32> ToDemote;
8453   SmallVector<Value *, 4> Roots;
8454   for (auto *Root : TreeRoot)
8455     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
8456       return;
8457 
8458   // The maximum bit width required to represent all the values that can be
8459   // demoted without loss of precision. It would be safe to truncate the roots
8460   // of the expression to this width.
8461   auto MaxBitWidth = 8u;
8462 
8463   // We first check if all the bits of the roots are demanded. If they're not,
8464   // we can truncate the roots to this narrower type.
8465   for (auto *Root : TreeRoot) {
8466     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
8467     MaxBitWidth = std::max<unsigned>(
8468         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
8469   }
8470 
8471   // True if the roots can be zero-extended back to their original type, rather
8472   // than sign-extended. We know that if the leading bits are not demanded, we
8473   // can safely zero-extend. So we initialize IsKnownPositive to True.
8474   bool IsKnownPositive = true;
8475 
8476   // If all the bits of the roots are demanded, we can try a little harder to
8477   // compute a narrower type. This can happen, for example, if the roots are
8478   // getelementptr indices. InstCombine promotes these indices to the pointer
8479   // width. Thus, all their bits are technically demanded even though the
8480   // address computation might be vectorized in a smaller type.
8481   //
8482   // We start by looking at each entry that can be demoted. We compute the
8483   // maximum bit width required to store the scalar by using ValueTracking to
8484   // compute the number of high-order bits we can truncate.
8485   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
8486       llvm::all_of(TreeRoot, [](Value *R) {
8487         assert(R->hasOneUse() && "Root should have only one use!");
8488         return isa<GetElementPtrInst>(R->user_back());
8489       })) {
8490     MaxBitWidth = 8u;
8491 
8492     // Determine if the sign bit of all the roots is known to be zero. If not,
8493     // IsKnownPositive is set to False.
8494     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
8495       KnownBits Known = computeKnownBits(R, *DL);
8496       return Known.isNonNegative();
8497     });
8498 
8499     // Determine the maximum number of bits required to store the scalar
8500     // values.
8501     for (auto *Scalar : ToDemote) {
8502       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
8503       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
8504       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
8505     }
8506 
8507     // If we can't prove that the sign bit is zero, we must add one to the
8508     // maximum bit width to account for the unknown sign bit. This preserves
8509     // the existing sign bit so we can safely sign-extend the root back to the
8510     // original type. Otherwise, if we know the sign bit is zero, we will
8511     // zero-extend the root instead.
8512     //
8513     // FIXME: This is somewhat suboptimal, as there will be cases where adding
8514     //        one to the maximum bit width will yield a larger-than-necessary
8515     //        type. In general, we need to add an extra bit only if we can't
8516     //        prove that the upper bit of the original type is equal to the
8517     //        upper bit of the proposed smaller type. If these two bits are the
8518     //        same (either zero or one) we know that sign-extending from the
8519     //        smaller type will result in the same value. Here, since we can't
8520     //        yet prove this, we are just making the proposed smaller type
8521     //        larger to ensure correctness.
8522     if (!IsKnownPositive)
8523       ++MaxBitWidth;
8524   }
8525 
8526   // Round MaxBitWidth up to the next power-of-two.
8527   if (!isPowerOf2_64(MaxBitWidth))
8528     MaxBitWidth = NextPowerOf2(MaxBitWidth);
8529 
8530   // If the maximum bit width we compute is less than the with of the roots'
8531   // type, we can proceed with the narrowing. Otherwise, do nothing.
8532   if (MaxBitWidth >= TreeRootIT->getBitWidth())
8533     return;
8534 
8535   // If we can truncate the root, we must collect additional values that might
8536   // be demoted as a result. That is, those seeded by truncations we will
8537   // modify.
8538   while (!Roots.empty())
8539     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
8540 
8541   // Finally, map the values we can demote to the maximum bit with we computed.
8542   for (auto *Scalar : ToDemote)
8543     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
8544 }
8545 
8546 namespace {
8547 
8548 /// The SLPVectorizer Pass.
8549 struct SLPVectorizer : public FunctionPass {
8550   SLPVectorizerPass Impl;
8551 
8552   /// Pass identification, replacement for typeid
8553   static char ID;
8554 
8555   explicit SLPVectorizer() : FunctionPass(ID) {
8556     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
8557   }
8558 
8559   bool doInitialization(Module &M) override { return false; }
8560 
8561   bool runOnFunction(Function &F) override {
8562     if (skipFunction(F))
8563       return false;
8564 
8565     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
8566     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
8567     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
8568     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
8569     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
8570     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
8571     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
8572     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
8573     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
8574     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
8575 
8576     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, /*MSSA*/nullptr, ORE);
8577   }
8578 
8579   void getAnalysisUsage(AnalysisUsage &AU) const override {
8580     FunctionPass::getAnalysisUsage(AU);
8581     AU.addRequired<AssumptionCacheTracker>();
8582     AU.addRequired<ScalarEvolutionWrapperPass>();
8583     AU.addRequired<AAResultsWrapperPass>();
8584     AU.addRequired<TargetTransformInfoWrapperPass>();
8585     AU.addRequired<LoopInfoWrapperPass>();
8586     AU.addRequired<DominatorTreeWrapperPass>();
8587     AU.addRequired<DemandedBitsWrapperPass>();
8588     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
8589     AU.addRequired<InjectTLIMappingsLegacy>();
8590     AU.addPreserved<LoopInfoWrapperPass>();
8591     AU.addPreserved<DominatorTreeWrapperPass>();
8592     AU.addPreserved<AAResultsWrapperPass>();
8593     AU.addPreserved<GlobalsAAWrapperPass>();
8594     AU.setPreservesCFG();
8595   }
8596 };
8597 
8598 } // end anonymous namespace
8599 
8600 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
8601   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
8602   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
8603   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
8604   auto *AA = &AM.getResult<AAManager>(F);
8605   auto *LI = &AM.getResult<LoopAnalysis>(F);
8606   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
8607   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
8608   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
8609   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
8610   auto *MSSA = EnableMSSAInSLPVectorizer ?
8611     &AM.getResult<MemorySSAAnalysis>(F).getMSSA() : (MemorySSA*)nullptr;
8612 
8613   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, MSSA, ORE);
8614   if (!Changed)
8615     return PreservedAnalyses::all();
8616 
8617   PreservedAnalyses PA;
8618   PA.preserveSet<CFGAnalyses>();
8619   if (MSSA) {
8620 #ifdef EXPENSIVE_CHECKS
8621     MSSA->verifyMemorySSA();
8622 #endif
8623     PA.preserve<MemorySSAAnalysis>();
8624   }
8625   return PA;
8626 }
8627 
8628 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
8629                                 TargetTransformInfo *TTI_,
8630                                 TargetLibraryInfo *TLI_, AAResults *AA_,
8631                                 LoopInfo *LI_, DominatorTree *DT_,
8632                                 AssumptionCache *AC_, DemandedBits *DB_,
8633                                 MemorySSA *MSSA,
8634                                 OptimizationRemarkEmitter *ORE_) {
8635   if (!RunSLPVectorization)
8636     return false;
8637   SE = SE_;
8638   TTI = TTI_;
8639   TLI = TLI_;
8640   AA = AA_;
8641   LI = LI_;
8642   DT = DT_;
8643   AC = AC_;
8644   DB = DB_;
8645   DL = &F.getParent()->getDataLayout();
8646 
8647   Stores.clear();
8648   GEPs.clear();
8649   bool Changed = false;
8650 
8651   // If the target claims to have no vector registers don't attempt
8652   // vectorization.
8653   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
8654     LLVM_DEBUG(
8655         dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
8656     return false;
8657   }
8658 
8659   // Don't vectorize when the attribute NoImplicitFloat is used.
8660   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
8661     return false;
8662 
8663   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
8664 
8665   // Use the bottom up slp vectorizer to construct chains that start with
8666   // store instructions.
8667   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, MSSA, DL, ORE_);
8668 
8669   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
8670   // delete instructions.
8671 
8672   // Update DFS numbers now so that we can use them for ordering.
8673   DT->updateDFSNumbers();
8674 
8675   // Scan the blocks in the function in post order.
8676   for (auto BB : post_order(&F.getEntryBlock())) {
8677     collectSeedInstructions(BB);
8678 
8679     // Vectorize trees that end at stores.
8680     if (!Stores.empty()) {
8681       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
8682                         << " underlying objects.\n");
8683       Changed |= vectorizeStoreChains(R);
8684     }
8685 
8686     // Vectorize trees that end at reductions.
8687     Changed |= vectorizeChainsInBlock(BB, R);
8688 
8689     // Vectorize the index computations of getelementptr instructions. This
8690     // is primarily intended to catch gather-like idioms ending at
8691     // non-consecutive loads.
8692     if (!GEPs.empty()) {
8693       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
8694                         << " underlying objects.\n");
8695       Changed |= vectorizeGEPIndices(BB, R);
8696     }
8697   }
8698 
8699   if (Changed) {
8700     R.optimizeGatherSequence();
8701     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
8702   }
8703   return Changed;
8704 }
8705 
8706 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
8707                                             unsigned Idx) {
8708   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
8709                     << "\n");
8710   const unsigned Sz = R.getVectorElementSize(Chain[0]);
8711   const unsigned MinVF = R.getMinVecRegSize() / Sz;
8712   unsigned VF = Chain.size();
8713 
8714   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
8715     return false;
8716 
8717   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
8718                     << "\n");
8719 
8720   R.buildTree(Chain);
8721   if (R.isTreeTinyAndNotFullyVectorizable())
8722     return false;
8723   if (R.isLoadCombineCandidate())
8724     return false;
8725   R.reorderTopToBottom();
8726   R.reorderBottomToTop();
8727   R.buildExternalUses();
8728 
8729   R.computeMinimumValueSizes();
8730 
8731   InstructionCost Cost = R.getTreeCost();
8732 
8733   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
8734   if (Cost < -SLPCostThreshold) {
8735     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
8736 
8737     using namespace ore;
8738 
8739     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
8740                                         cast<StoreInst>(Chain[0]))
8741                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
8742                      << " and with tree size "
8743                      << NV("TreeSize", R.getTreeSize()));
8744 
8745     R.vectorizeTree();
8746     return true;
8747   }
8748 
8749   return false;
8750 }
8751 
8752 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
8753                                         BoUpSLP &R) {
8754   // We may run into multiple chains that merge into a single chain. We mark the
8755   // stores that we vectorized so that we don't visit the same store twice.
8756   BoUpSLP::ValueSet VectorizedStores;
8757   bool Changed = false;
8758 
8759   int E = Stores.size();
8760   SmallBitVector Tails(E, false);
8761   int MaxIter = MaxStoreLookup.getValue();
8762   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
8763       E, std::make_pair(E, INT_MAX));
8764   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
8765   int IterCnt;
8766   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
8767                                   &CheckedPairs,
8768                                   &ConsecutiveChain](int K, int Idx) {
8769     if (IterCnt >= MaxIter)
8770       return true;
8771     if (CheckedPairs[Idx].test(K))
8772       return ConsecutiveChain[K].second == 1 &&
8773              ConsecutiveChain[K].first == Idx;
8774     ++IterCnt;
8775     CheckedPairs[Idx].set(K);
8776     CheckedPairs[K].set(Idx);
8777     Optional<int> Diff = getPointersDiff(
8778         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
8779         Stores[Idx]->getValueOperand()->getType(),
8780         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
8781     if (!Diff || *Diff == 0)
8782       return false;
8783     int Val = *Diff;
8784     if (Val < 0) {
8785       if (ConsecutiveChain[Idx].second > -Val) {
8786         Tails.set(K);
8787         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
8788       }
8789       return false;
8790     }
8791     if (ConsecutiveChain[K].second <= Val)
8792       return false;
8793 
8794     Tails.set(Idx);
8795     ConsecutiveChain[K] = std::make_pair(Idx, Val);
8796     return Val == 1;
8797   };
8798   // Do a quadratic search on all of the given stores in reverse order and find
8799   // all of the pairs of stores that follow each other.
8800   for (int Idx = E - 1; Idx >= 0; --Idx) {
8801     // If a store has multiple consecutive store candidates, search according
8802     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
8803     // This is because usually pairing with immediate succeeding or preceding
8804     // candidate create the best chance to find slp vectorization opportunity.
8805     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
8806     IterCnt = 0;
8807     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
8808       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
8809           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
8810         break;
8811   }
8812 
8813   // Tracks if we tried to vectorize stores starting from the given tail
8814   // already.
8815   SmallBitVector TriedTails(E, false);
8816   // For stores that start but don't end a link in the chain:
8817   for (int Cnt = E; Cnt > 0; --Cnt) {
8818     int I = Cnt - 1;
8819     if (ConsecutiveChain[I].first == E || Tails.test(I))
8820       continue;
8821     // We found a store instr that starts a chain. Now follow the chain and try
8822     // to vectorize it.
8823     BoUpSLP::ValueList Operands;
8824     // Collect the chain into a list.
8825     while (I != E && !VectorizedStores.count(Stores[I])) {
8826       Operands.push_back(Stores[I]);
8827       Tails.set(I);
8828       if (ConsecutiveChain[I].second != 1) {
8829         // Mark the new end in the chain and go back, if required. It might be
8830         // required if the original stores come in reversed order, for example.
8831         if (ConsecutiveChain[I].first != E &&
8832             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
8833             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
8834           TriedTails.set(I);
8835           Tails.reset(ConsecutiveChain[I].first);
8836           if (Cnt < ConsecutiveChain[I].first + 2)
8837             Cnt = ConsecutiveChain[I].first + 2;
8838         }
8839         break;
8840       }
8841       // Move to the next value in the chain.
8842       I = ConsecutiveChain[I].first;
8843     }
8844     assert(!Operands.empty() && "Expected non-empty list of stores.");
8845 
8846     unsigned MaxVecRegSize = R.getMaxVecRegSize();
8847     unsigned EltSize = R.getVectorElementSize(Operands[0]);
8848     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
8849 
8850     unsigned MinVF = R.getMinVF(EltSize);
8851     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
8852                               MaxElts);
8853 
8854     // FIXME: Is division-by-2 the correct step? Should we assert that the
8855     // register size is a power-of-2?
8856     unsigned StartIdx = 0;
8857     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
8858       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
8859         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
8860         if (!VectorizedStores.count(Slice.front()) &&
8861             !VectorizedStores.count(Slice.back()) &&
8862             vectorizeStoreChain(Slice, R, Cnt)) {
8863           // Mark the vectorized stores so that we don't vectorize them again.
8864           VectorizedStores.insert(Slice.begin(), Slice.end());
8865           Changed = true;
8866           // If we vectorized initial block, no need to try to vectorize it
8867           // again.
8868           if (Cnt == StartIdx)
8869             StartIdx += Size;
8870           Cnt += Size;
8871           continue;
8872         }
8873         ++Cnt;
8874       }
8875       // Check if the whole array was vectorized already - exit.
8876       if (StartIdx >= Operands.size())
8877         break;
8878     }
8879   }
8880 
8881   return Changed;
8882 }
8883 
8884 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
8885   // Initialize the collections. We will make a single pass over the block.
8886   Stores.clear();
8887   GEPs.clear();
8888 
8889   // Visit the store and getelementptr instructions in BB and organize them in
8890   // Stores and GEPs according to the underlying objects of their pointer
8891   // operands.
8892   for (Instruction &I : *BB) {
8893     // Ignore store instructions that are volatile or have a pointer operand
8894     // that doesn't point to a scalar type.
8895     if (auto *SI = dyn_cast<StoreInst>(&I)) {
8896       if (!SI->isSimple())
8897         continue;
8898       if (!isValidElementType(SI->getValueOperand()->getType()))
8899         continue;
8900       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
8901     }
8902 
8903     // Ignore getelementptr instructions that have more than one index, a
8904     // constant index, or a pointer operand that doesn't point to a scalar
8905     // type.
8906     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
8907       auto Idx = GEP->idx_begin()->get();
8908       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
8909         continue;
8910       if (!isValidElementType(Idx->getType()))
8911         continue;
8912       if (GEP->getType()->isVectorTy())
8913         continue;
8914       GEPs[GEP->getPointerOperand()].push_back(GEP);
8915     }
8916   }
8917 }
8918 
8919 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
8920   if (!A || !B)
8921     return false;
8922   if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
8923     return false;
8924   Value *VL[] = {A, B};
8925   return tryToVectorizeList(VL, R);
8926 }
8927 
8928 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
8929                                            bool LimitForRegisterSize) {
8930   if (VL.size() < 2)
8931     return false;
8932 
8933   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
8934                     << VL.size() << ".\n");
8935 
8936   // Check that all of the parts are instructions of the same type,
8937   // we permit an alternate opcode via InstructionsState.
8938   InstructionsState S = getSameOpcode(VL);
8939   if (!S.getOpcode())
8940     return false;
8941 
8942   Instruction *I0 = cast<Instruction>(S.OpValue);
8943   // Make sure invalid types (including vector type) are rejected before
8944   // determining vectorization factor for scalar instructions.
8945   for (Value *V : VL) {
8946     Type *Ty = V->getType();
8947     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
8948       // NOTE: the following will give user internal llvm type name, which may
8949       // not be useful.
8950       R.getORE()->emit([&]() {
8951         std::string type_str;
8952         llvm::raw_string_ostream rso(type_str);
8953         Ty->print(rso);
8954         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
8955                << "Cannot SLP vectorize list: type "
8956                << rso.str() + " is unsupported by vectorizer";
8957       });
8958       return false;
8959     }
8960   }
8961 
8962   unsigned Sz = R.getVectorElementSize(I0);
8963   unsigned MinVF = R.getMinVF(Sz);
8964   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
8965   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
8966   if (MaxVF < 2) {
8967     R.getORE()->emit([&]() {
8968       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
8969              << "Cannot SLP vectorize list: vectorization factor "
8970              << "less than 2 is not supported";
8971     });
8972     return false;
8973   }
8974 
8975   bool Changed = false;
8976   bool CandidateFound = false;
8977   InstructionCost MinCost = SLPCostThreshold.getValue();
8978   Type *ScalarTy = VL[0]->getType();
8979   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
8980     ScalarTy = IE->getOperand(1)->getType();
8981 
8982   unsigned NextInst = 0, MaxInst = VL.size();
8983   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
8984     // No actual vectorization should happen, if number of parts is the same as
8985     // provided vectorization factor (i.e. the scalar type is used for vector
8986     // code during codegen).
8987     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
8988     if (TTI->getNumberOfParts(VecTy) == VF)
8989       continue;
8990     for (unsigned I = NextInst; I < MaxInst; ++I) {
8991       unsigned OpsWidth = 0;
8992 
8993       if (I + VF > MaxInst)
8994         OpsWidth = MaxInst - I;
8995       else
8996         OpsWidth = VF;
8997 
8998       if (!isPowerOf2_32(OpsWidth))
8999         continue;
9000 
9001       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
9002           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
9003         break;
9004 
9005       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
9006       // Check that a previous iteration of this loop did not delete the Value.
9007       if (llvm::any_of(Ops, [&R](Value *V) {
9008             auto *I = dyn_cast<Instruction>(V);
9009             return I && R.isDeleted(I);
9010           }))
9011         continue;
9012 
9013       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
9014                         << "\n");
9015 
9016       R.buildTree(Ops);
9017       if (R.isTreeTinyAndNotFullyVectorizable())
9018         continue;
9019       R.reorderTopToBottom();
9020       R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
9021       R.buildExternalUses();
9022 
9023       R.computeMinimumValueSizes();
9024       InstructionCost Cost = R.getTreeCost();
9025       CandidateFound = true;
9026       MinCost = std::min(MinCost, Cost);
9027 
9028       if (Cost < -SLPCostThreshold) {
9029         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
9030         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
9031                                                     cast<Instruction>(Ops[0]))
9032                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
9033                                  << " and with tree size "
9034                                  << ore::NV("TreeSize", R.getTreeSize()));
9035 
9036         R.vectorizeTree();
9037         // Move to the next bundle.
9038         I += VF - 1;
9039         NextInst = I + 1;
9040         Changed = true;
9041       }
9042     }
9043   }
9044 
9045   if (!Changed && CandidateFound) {
9046     R.getORE()->emit([&]() {
9047       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
9048              << "List vectorization was possible but not beneficial with cost "
9049              << ore::NV("Cost", MinCost) << " >= "
9050              << ore::NV("Treshold", -SLPCostThreshold);
9051     });
9052   } else if (!Changed) {
9053     R.getORE()->emit([&]() {
9054       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
9055              << "Cannot SLP vectorize list: vectorization was impossible"
9056              << " with available vectorization factors";
9057     });
9058   }
9059   return Changed;
9060 }
9061 
9062 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
9063   if (!I)
9064     return false;
9065 
9066   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
9067     return false;
9068 
9069   Value *P = I->getParent();
9070 
9071   // Vectorize in current basic block only.
9072   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
9073   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
9074   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
9075     return false;
9076 
9077   // Try to vectorize V.
9078   if (tryToVectorizePair(Op0, Op1, R))
9079     return true;
9080 
9081   auto *A = dyn_cast<BinaryOperator>(Op0);
9082   auto *B = dyn_cast<BinaryOperator>(Op1);
9083   // Try to skip B.
9084   if (B && B->hasOneUse()) {
9085     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
9086     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
9087     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
9088       return true;
9089     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
9090       return true;
9091   }
9092 
9093   // Try to skip A.
9094   if (A && A->hasOneUse()) {
9095     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
9096     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
9097     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
9098       return true;
9099     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
9100       return true;
9101   }
9102   return false;
9103 }
9104 
9105 namespace {
9106 
9107 /// Model horizontal reductions.
9108 ///
9109 /// A horizontal reduction is a tree of reduction instructions that has values
9110 /// that can be put into a vector as its leaves. For example:
9111 ///
9112 /// mul mul mul mul
9113 ///  \  /    \  /
9114 ///   +       +
9115 ///    \     /
9116 ///       +
9117 /// This tree has "mul" as its leaf values and "+" as its reduction
9118 /// instructions. A reduction can feed into a store or a binary operation
9119 /// feeding a phi.
9120 ///    ...
9121 ///    \  /
9122 ///     +
9123 ///     |
9124 ///  phi +=
9125 ///
9126 ///  Or:
9127 ///    ...
9128 ///    \  /
9129 ///     +
9130 ///     |
9131 ///   *p =
9132 ///
9133 class HorizontalReduction {
9134   using ReductionOpsType = SmallVector<Value *, 16>;
9135   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
9136   ReductionOpsListType ReductionOps;
9137   SmallVector<Value *, 32> ReducedVals;
9138   // Use map vector to make stable output.
9139   MapVector<Instruction *, Value *> ExtraArgs;
9140   WeakTrackingVH ReductionRoot;
9141   /// The type of reduction operation.
9142   RecurKind RdxKind;
9143 
9144   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
9145 
9146   static bool isCmpSelMinMax(Instruction *I) {
9147     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
9148            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
9149   }
9150 
9151   // And/or are potentially poison-safe logical patterns like:
9152   // select x, y, false
9153   // select x, true, y
9154   static bool isBoolLogicOp(Instruction *I) {
9155     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
9156            match(I, m_LogicalOr(m_Value(), m_Value()));
9157   }
9158 
9159   /// Checks if instruction is associative and can be vectorized.
9160   static bool isVectorizable(RecurKind Kind, Instruction *I) {
9161     if (Kind == RecurKind::None)
9162       return false;
9163 
9164     // Integer ops that map to select instructions or intrinsics are fine.
9165     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
9166         isBoolLogicOp(I))
9167       return true;
9168 
9169     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
9170       // FP min/max are associative except for NaN and -0.0. We do not
9171       // have to rule out -0.0 here because the intrinsic semantics do not
9172       // specify a fixed result for it.
9173       return I->getFastMathFlags().noNaNs();
9174     }
9175 
9176     return I->isAssociative();
9177   }
9178 
9179   static Value *getRdxOperand(Instruction *I, unsigned Index) {
9180     // Poison-safe 'or' takes the form: select X, true, Y
9181     // To make that work with the normal operand processing, we skip the
9182     // true value operand.
9183     // TODO: Change the code and data structures to handle this without a hack.
9184     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
9185       return I->getOperand(2);
9186     return I->getOperand(Index);
9187   }
9188 
9189   /// Checks if the ParentStackElem.first should be marked as a reduction
9190   /// operation with an extra argument or as extra argument itself.
9191   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
9192                     Value *ExtraArg) {
9193     if (ExtraArgs.count(ParentStackElem.first)) {
9194       ExtraArgs[ParentStackElem.first] = nullptr;
9195       // We ran into something like:
9196       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
9197       // The whole ParentStackElem.first should be considered as an extra value
9198       // in this case.
9199       // Do not perform analysis of remaining operands of ParentStackElem.first
9200       // instruction, this whole instruction is an extra argument.
9201       ParentStackElem.second = INVALID_OPERAND_INDEX;
9202     } else {
9203       // We ran into something like:
9204       // ParentStackElem.first += ... + ExtraArg + ...
9205       ExtraArgs[ParentStackElem.first] = ExtraArg;
9206     }
9207   }
9208 
9209   /// Creates reduction operation with the current opcode.
9210   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
9211                          Value *RHS, const Twine &Name, bool UseSelect) {
9212     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
9213     switch (Kind) {
9214     case RecurKind::Or:
9215       if (UseSelect &&
9216           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9217         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
9218       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9219                                  Name);
9220     case RecurKind::And:
9221       if (UseSelect &&
9222           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
9223         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
9224       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9225                                  Name);
9226     case RecurKind::Add:
9227     case RecurKind::Mul:
9228     case RecurKind::Xor:
9229     case RecurKind::FAdd:
9230     case RecurKind::FMul:
9231       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
9232                                  Name);
9233     case RecurKind::FMax:
9234       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
9235     case RecurKind::FMin:
9236       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
9237     case RecurKind::SMax:
9238       if (UseSelect) {
9239         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
9240         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9241       }
9242       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
9243     case RecurKind::SMin:
9244       if (UseSelect) {
9245         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
9246         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9247       }
9248       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
9249     case RecurKind::UMax:
9250       if (UseSelect) {
9251         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
9252         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9253       }
9254       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
9255     case RecurKind::UMin:
9256       if (UseSelect) {
9257         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
9258         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
9259       }
9260       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
9261     default:
9262       llvm_unreachable("Unknown reduction operation.");
9263     }
9264   }
9265 
9266   /// Creates reduction operation with the current opcode with the IR flags
9267   /// from \p ReductionOps.
9268   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9269                          Value *RHS, const Twine &Name,
9270                          const ReductionOpsListType &ReductionOps) {
9271     bool UseSelect = ReductionOps.size() == 2 ||
9272                      // Logical or/and.
9273                      (ReductionOps.size() == 1 &&
9274                       isa<SelectInst>(ReductionOps.front().front()));
9275     assert((!UseSelect || ReductionOps.size() != 2 ||
9276             isa<SelectInst>(ReductionOps[1][0])) &&
9277            "Expected cmp + select pairs for reduction");
9278     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
9279     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9280       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
9281         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
9282         propagateIRFlags(Op, ReductionOps[1]);
9283         return Op;
9284       }
9285     }
9286     propagateIRFlags(Op, ReductionOps[0]);
9287     return Op;
9288   }
9289 
9290   /// Creates reduction operation with the current opcode with the IR flags
9291   /// from \p I.
9292   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
9293                          Value *RHS, const Twine &Name, Instruction *I) {
9294     auto *SelI = dyn_cast<SelectInst>(I);
9295     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
9296     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
9297       if (auto *Sel = dyn_cast<SelectInst>(Op))
9298         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
9299     }
9300     propagateIRFlags(Op, I);
9301     return Op;
9302   }
9303 
9304   static RecurKind getRdxKind(Instruction *I) {
9305     assert(I && "Expected instruction for reduction matching");
9306     if (match(I, m_Add(m_Value(), m_Value())))
9307       return RecurKind::Add;
9308     if (match(I, m_Mul(m_Value(), m_Value())))
9309       return RecurKind::Mul;
9310     if (match(I, m_And(m_Value(), m_Value())) ||
9311         match(I, m_LogicalAnd(m_Value(), m_Value())))
9312       return RecurKind::And;
9313     if (match(I, m_Or(m_Value(), m_Value())) ||
9314         match(I, m_LogicalOr(m_Value(), m_Value())))
9315       return RecurKind::Or;
9316     if (match(I, m_Xor(m_Value(), m_Value())))
9317       return RecurKind::Xor;
9318     if (match(I, m_FAdd(m_Value(), m_Value())))
9319       return RecurKind::FAdd;
9320     if (match(I, m_FMul(m_Value(), m_Value())))
9321       return RecurKind::FMul;
9322 
9323     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
9324       return RecurKind::FMax;
9325     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
9326       return RecurKind::FMin;
9327 
9328     // This matches either cmp+select or intrinsics. SLP is expected to handle
9329     // either form.
9330     // TODO: If we are canonicalizing to intrinsics, we can remove several
9331     //       special-case paths that deal with selects.
9332     if (match(I, m_SMax(m_Value(), m_Value())))
9333       return RecurKind::SMax;
9334     if (match(I, m_SMin(m_Value(), m_Value())))
9335       return RecurKind::SMin;
9336     if (match(I, m_UMax(m_Value(), m_Value())))
9337       return RecurKind::UMax;
9338     if (match(I, m_UMin(m_Value(), m_Value())))
9339       return RecurKind::UMin;
9340 
9341     if (auto *Select = dyn_cast<SelectInst>(I)) {
9342       // Try harder: look for min/max pattern based on instructions producing
9343       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
9344       // During the intermediate stages of SLP, it's very common to have
9345       // pattern like this (since optimizeGatherSequence is run only once
9346       // at the end):
9347       // %1 = extractelement <2 x i32> %a, i32 0
9348       // %2 = extractelement <2 x i32> %a, i32 1
9349       // %cond = icmp sgt i32 %1, %2
9350       // %3 = extractelement <2 x i32> %a, i32 0
9351       // %4 = extractelement <2 x i32> %a, i32 1
9352       // %select = select i1 %cond, i32 %3, i32 %4
9353       CmpInst::Predicate Pred;
9354       Instruction *L1;
9355       Instruction *L2;
9356 
9357       Value *LHS = Select->getTrueValue();
9358       Value *RHS = Select->getFalseValue();
9359       Value *Cond = Select->getCondition();
9360 
9361       // TODO: Support inverse predicates.
9362       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
9363         if (!isa<ExtractElementInst>(RHS) ||
9364             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9365           return RecurKind::None;
9366       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
9367         if (!isa<ExtractElementInst>(LHS) ||
9368             !L1->isIdenticalTo(cast<Instruction>(LHS)))
9369           return RecurKind::None;
9370       } else {
9371         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
9372           return RecurKind::None;
9373         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
9374             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
9375             !L2->isIdenticalTo(cast<Instruction>(RHS)))
9376           return RecurKind::None;
9377       }
9378 
9379       switch (Pred) {
9380       default:
9381         return RecurKind::None;
9382       case CmpInst::ICMP_SGT:
9383       case CmpInst::ICMP_SGE:
9384         return RecurKind::SMax;
9385       case CmpInst::ICMP_SLT:
9386       case CmpInst::ICMP_SLE:
9387         return RecurKind::SMin;
9388       case CmpInst::ICMP_UGT:
9389       case CmpInst::ICMP_UGE:
9390         return RecurKind::UMax;
9391       case CmpInst::ICMP_ULT:
9392       case CmpInst::ICMP_ULE:
9393         return RecurKind::UMin;
9394       }
9395     }
9396     return RecurKind::None;
9397   }
9398 
9399   /// Get the index of the first operand.
9400   static unsigned getFirstOperandIndex(Instruction *I) {
9401     return isCmpSelMinMax(I) ? 1 : 0;
9402   }
9403 
9404   /// Total number of operands in the reduction operation.
9405   static unsigned getNumberOfOperands(Instruction *I) {
9406     return isCmpSelMinMax(I) ? 3 : 2;
9407   }
9408 
9409   /// Checks if the instruction is in basic block \p BB.
9410   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
9411   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
9412     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
9413       auto *Sel = cast<SelectInst>(I);
9414       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
9415       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
9416     }
9417     return I->getParent() == BB;
9418   }
9419 
9420   /// Expected number of uses for reduction operations/reduced values.
9421   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
9422     if (IsCmpSelMinMax) {
9423       // SelectInst must be used twice while the condition op must have single
9424       // use only.
9425       if (auto *Sel = dyn_cast<SelectInst>(I))
9426         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
9427       return I->hasNUses(2);
9428     }
9429 
9430     // Arithmetic reduction operation must be used once only.
9431     return I->hasOneUse();
9432   }
9433 
9434   /// Initializes the list of reduction operations.
9435   void initReductionOps(Instruction *I) {
9436     if (isCmpSelMinMax(I))
9437       ReductionOps.assign(2, ReductionOpsType());
9438     else
9439       ReductionOps.assign(1, ReductionOpsType());
9440   }
9441 
9442   /// Add all reduction operations for the reduction instruction \p I.
9443   void addReductionOps(Instruction *I) {
9444     if (isCmpSelMinMax(I)) {
9445       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
9446       ReductionOps[1].emplace_back(I);
9447     } else {
9448       ReductionOps[0].emplace_back(I);
9449     }
9450   }
9451 
9452   static Value *getLHS(RecurKind Kind, Instruction *I) {
9453     if (Kind == RecurKind::None)
9454       return nullptr;
9455     return I->getOperand(getFirstOperandIndex(I));
9456   }
9457   static Value *getRHS(RecurKind Kind, Instruction *I) {
9458     if (Kind == RecurKind::None)
9459       return nullptr;
9460     return I->getOperand(getFirstOperandIndex(I) + 1);
9461   }
9462 
9463 public:
9464   HorizontalReduction() = default;
9465 
9466   /// Try to find a reduction tree.
9467   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
9468     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
9469            "Phi needs to use the binary operator");
9470     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
9471             isa<IntrinsicInst>(Inst)) &&
9472            "Expected binop, select, or intrinsic for reduction matching");
9473     RdxKind = getRdxKind(Inst);
9474 
9475     // We could have a initial reductions that is not an add.
9476     //  r *= v1 + v2 + v3 + v4
9477     // In such a case start looking for a tree rooted in the first '+'.
9478     if (Phi) {
9479       if (getLHS(RdxKind, Inst) == Phi) {
9480         Phi = nullptr;
9481         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
9482         if (!Inst)
9483           return false;
9484         RdxKind = getRdxKind(Inst);
9485       } else if (getRHS(RdxKind, Inst) == Phi) {
9486         Phi = nullptr;
9487         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
9488         if (!Inst)
9489           return false;
9490         RdxKind = getRdxKind(Inst);
9491       }
9492     }
9493 
9494     if (!isVectorizable(RdxKind, Inst))
9495       return false;
9496 
9497     // Analyze "regular" integer/FP types for reductions - no target-specific
9498     // types or pointers.
9499     Type *Ty = Inst->getType();
9500     if (!isValidElementType(Ty) || Ty->isPointerTy())
9501       return false;
9502 
9503     // Though the ultimate reduction may have multiple uses, its condition must
9504     // have only single use.
9505     if (auto *Sel = dyn_cast<SelectInst>(Inst))
9506       if (!Sel->getCondition()->hasOneUse())
9507         return false;
9508 
9509     ReductionRoot = Inst;
9510 
9511     // The opcode for leaf values that we perform a reduction on.
9512     // For example: load(x) + load(y) + load(z) + fptoui(w)
9513     // The leaf opcode for 'w' does not match, so we don't include it as a
9514     // potential candidate for the reduction.
9515     unsigned LeafOpcode = 0;
9516 
9517     // Post-order traverse the reduction tree starting at Inst. We only handle
9518     // true trees containing binary operators or selects.
9519     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
9520     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
9521     initReductionOps(Inst);
9522     while (!Stack.empty()) {
9523       Instruction *TreeN = Stack.back().first;
9524       unsigned EdgeToVisit = Stack.back().second++;
9525       const RecurKind TreeRdxKind = getRdxKind(TreeN);
9526       bool IsReducedValue = TreeRdxKind != RdxKind;
9527 
9528       // Postorder visit.
9529       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
9530         if (IsReducedValue)
9531           ReducedVals.push_back(TreeN);
9532         else {
9533           auto ExtraArgsIter = ExtraArgs.find(TreeN);
9534           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
9535             // Check if TreeN is an extra argument of its parent operation.
9536             if (Stack.size() <= 1) {
9537               // TreeN can't be an extra argument as it is a root reduction
9538               // operation.
9539               return false;
9540             }
9541             // Yes, TreeN is an extra argument, do not add it to a list of
9542             // reduction operations.
9543             // Stack[Stack.size() - 2] always points to the parent operation.
9544             markExtraArg(Stack[Stack.size() - 2], TreeN);
9545             ExtraArgs.erase(TreeN);
9546           } else
9547             addReductionOps(TreeN);
9548         }
9549         // Retract.
9550         Stack.pop_back();
9551         continue;
9552       }
9553 
9554       // Visit operands.
9555       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
9556       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
9557       if (!EdgeInst) {
9558         // Edge value is not a reduction instruction or a leaf instruction.
9559         // (It may be a constant, function argument, or something else.)
9560         markExtraArg(Stack.back(), EdgeVal);
9561         continue;
9562       }
9563       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
9564       // Continue analysis if the next operand is a reduction operation or
9565       // (possibly) a leaf value. If the leaf value opcode is not set,
9566       // the first met operation != reduction operation is considered as the
9567       // leaf opcode.
9568       // Only handle trees in the current basic block.
9569       // Each tree node needs to have minimal number of users except for the
9570       // ultimate reduction.
9571       const bool IsRdxInst = EdgeRdxKind == RdxKind;
9572       if (EdgeInst != Phi && EdgeInst != Inst &&
9573           hasSameParent(EdgeInst, Inst->getParent()) &&
9574           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
9575           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
9576         if (IsRdxInst) {
9577           // We need to be able to reassociate the reduction operations.
9578           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
9579             // I is an extra argument for TreeN (its parent operation).
9580             markExtraArg(Stack.back(), EdgeInst);
9581             continue;
9582           }
9583         } else if (!LeafOpcode) {
9584           LeafOpcode = EdgeInst->getOpcode();
9585         }
9586         Stack.push_back(
9587             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
9588         continue;
9589       }
9590       // I is an extra argument for TreeN (its parent operation).
9591       markExtraArg(Stack.back(), EdgeInst);
9592     }
9593     return true;
9594   }
9595 
9596   /// Attempt to vectorize the tree found by matchAssociativeReduction.
9597   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
9598     // If there are a sufficient number of reduction values, reduce
9599     // to a nearby power-of-2. We can safely generate oversized
9600     // vectors and rely on the backend to split them to legal sizes.
9601     unsigned NumReducedVals = ReducedVals.size();
9602     if (NumReducedVals < 4)
9603       return nullptr;
9604 
9605     // Intersect the fast-math-flags from all reduction operations.
9606     FastMathFlags RdxFMF;
9607     RdxFMF.set();
9608     for (ReductionOpsType &RdxOp : ReductionOps) {
9609       for (Value *RdxVal : RdxOp) {
9610         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
9611           RdxFMF &= FPMO->getFastMathFlags();
9612       }
9613     }
9614 
9615     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
9616     Builder.setFastMathFlags(RdxFMF);
9617 
9618     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
9619     // The same extra argument may be used several times, so log each attempt
9620     // to use it.
9621     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
9622       assert(Pair.first && "DebugLoc must be set.");
9623       ExternallyUsedValues[Pair.second].push_back(Pair.first);
9624     }
9625 
9626     // The compare instruction of a min/max is the insertion point for new
9627     // instructions and may be replaced with a new compare instruction.
9628     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
9629       assert(isa<SelectInst>(RdxRootInst) &&
9630              "Expected min/max reduction to have select root instruction");
9631       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
9632       assert(isa<Instruction>(ScalarCond) &&
9633              "Expected min/max reduction to have compare condition");
9634       return cast<Instruction>(ScalarCond);
9635     };
9636 
9637     // The reduction root is used as the insertion point for new instructions,
9638     // so set it as externally used to prevent it from being deleted.
9639     ExternallyUsedValues[ReductionRoot];
9640     SmallVector<Value *, 16> IgnoreList;
9641     for (ReductionOpsType &RdxOp : ReductionOps)
9642       IgnoreList.append(RdxOp.begin(), RdxOp.end());
9643 
9644     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
9645     if (NumReducedVals > ReduxWidth) {
9646       // In the loop below, we are building a tree based on a window of
9647       // 'ReduxWidth' values.
9648       // If the operands of those values have common traits (compare predicate,
9649       // constant operand, etc), then we want to group those together to
9650       // minimize the cost of the reduction.
9651 
9652       // TODO: This should be extended to count common operands for
9653       //       compares and binops.
9654 
9655       // Step 1: Count the number of times each compare predicate occurs.
9656       SmallDenseMap<unsigned, unsigned> PredCountMap;
9657       for (Value *RdxVal : ReducedVals) {
9658         CmpInst::Predicate Pred;
9659         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
9660           ++PredCountMap[Pred];
9661       }
9662       // Step 2: Sort the values so the most common predicates come first.
9663       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
9664         CmpInst::Predicate PredA, PredB;
9665         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
9666             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
9667           return PredCountMap[PredA] > PredCountMap[PredB];
9668         }
9669         return false;
9670       });
9671     }
9672 
9673     Value *VectorizedTree = nullptr;
9674     unsigned i = 0;
9675     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
9676       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
9677       V.buildTree(VL, IgnoreList);
9678       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
9679         break;
9680       if (V.isLoadCombineReductionCandidate(RdxKind))
9681         break;
9682       V.reorderTopToBottom();
9683       V.reorderBottomToTop(/*IgnoreReorder=*/true);
9684       V.buildExternalUses(ExternallyUsedValues);
9685 
9686       // For a poison-safe boolean logic reduction, do not replace select
9687       // instructions with logic ops. All reduced values will be frozen (see
9688       // below) to prevent leaking poison.
9689       if (isa<SelectInst>(ReductionRoot) &&
9690           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
9691           NumReducedVals != ReduxWidth)
9692         break;
9693 
9694       V.computeMinimumValueSizes();
9695 
9696       // Estimate cost.
9697       InstructionCost TreeCost =
9698           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
9699       InstructionCost ReductionCost =
9700           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
9701       InstructionCost Cost = TreeCost + ReductionCost;
9702       if (!Cost.isValid()) {
9703         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
9704         return nullptr;
9705       }
9706       if (Cost >= -SLPCostThreshold) {
9707         V.getORE()->emit([&]() {
9708           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
9709                                           cast<Instruction>(VL[0]))
9710                  << "Vectorizing horizontal reduction is possible"
9711                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
9712                  << " and threshold "
9713                  << ore::NV("Threshold", -SLPCostThreshold);
9714         });
9715         break;
9716       }
9717 
9718       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
9719                         << Cost << ". (HorRdx)\n");
9720       V.getORE()->emit([&]() {
9721         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
9722                                   cast<Instruction>(VL[0]))
9723                << "Vectorized horizontal reduction with cost "
9724                << ore::NV("Cost", Cost) << " and with tree size "
9725                << ore::NV("TreeSize", V.getTreeSize());
9726       });
9727 
9728       // Vectorize a tree.
9729       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
9730       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
9731 
9732       // Emit a reduction. If the root is a select (min/max idiom), the insert
9733       // point is the compare condition of that select.
9734       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
9735       if (isCmpSelMinMax(RdxRootInst))
9736         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
9737       else
9738         Builder.SetInsertPoint(RdxRootInst);
9739 
9740       // To prevent poison from leaking across what used to be sequential, safe,
9741       // scalar boolean logic operations, the reduction operand must be frozen.
9742       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
9743         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
9744 
9745       Value *ReducedSubTree =
9746           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
9747 
9748       if (!VectorizedTree) {
9749         // Initialize the final value in the reduction.
9750         VectorizedTree = ReducedSubTree;
9751       } else {
9752         // Update the final value in the reduction.
9753         Builder.SetCurrentDebugLocation(Loc);
9754         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9755                                   ReducedSubTree, "op.rdx", ReductionOps);
9756       }
9757       i += ReduxWidth;
9758       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
9759     }
9760 
9761     if (VectorizedTree) {
9762       // Finish the reduction.
9763       for (; i < NumReducedVals; ++i) {
9764         auto *I = cast<Instruction>(ReducedVals[i]);
9765         Builder.SetCurrentDebugLocation(I->getDebugLoc());
9766         VectorizedTree =
9767             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
9768       }
9769       for (auto &Pair : ExternallyUsedValues) {
9770         // Add each externally used value to the final reduction.
9771         for (auto *I : Pair.second) {
9772           Builder.SetCurrentDebugLocation(I->getDebugLoc());
9773           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
9774                                     Pair.first, "op.extra", I);
9775         }
9776       }
9777 
9778       ReductionRoot->replaceAllUsesWith(VectorizedTree);
9779 
9780       // Mark all scalar reduction ops for deletion, they are replaced by the
9781       // vector reductions.
9782       V.eraseInstructions(IgnoreList);
9783     }
9784     return VectorizedTree;
9785   }
9786 
9787   unsigned numReductionValues() const { return ReducedVals.size(); }
9788 
9789 private:
9790   /// Calculate the cost of a reduction.
9791   InstructionCost getReductionCost(TargetTransformInfo *TTI,
9792                                    Value *FirstReducedVal, unsigned ReduxWidth,
9793                                    FastMathFlags FMF) {
9794     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
9795     Type *ScalarTy = FirstReducedVal->getType();
9796     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
9797     InstructionCost VectorCost, ScalarCost;
9798     switch (RdxKind) {
9799     case RecurKind::Add:
9800     case RecurKind::Mul:
9801     case RecurKind::Or:
9802     case RecurKind::And:
9803     case RecurKind::Xor:
9804     case RecurKind::FAdd:
9805     case RecurKind::FMul: {
9806       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
9807       VectorCost =
9808           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
9809       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
9810       break;
9811     }
9812     case RecurKind::FMax:
9813     case RecurKind::FMin: {
9814       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9815       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9816       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
9817                                                /*IsUnsigned=*/false, CostKind);
9818       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9819       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
9820                                            SclCondTy, RdxPred, CostKind) +
9821                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9822                                            SclCondTy, RdxPred, CostKind);
9823       break;
9824     }
9825     case RecurKind::SMax:
9826     case RecurKind::SMin:
9827     case RecurKind::UMax:
9828     case RecurKind::UMin: {
9829       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
9830       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
9831       bool IsUnsigned =
9832           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
9833       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
9834                                                CostKind);
9835       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
9836       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
9837                                            SclCondTy, RdxPred, CostKind) +
9838                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
9839                                            SclCondTy, RdxPred, CostKind);
9840       break;
9841     }
9842     default:
9843       llvm_unreachable("Expected arithmetic or min/max reduction operation");
9844     }
9845 
9846     // Scalar cost is repeated for N-1 elements.
9847     ScalarCost *= (ReduxWidth - 1);
9848     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
9849                       << " for reduction that starts with " << *FirstReducedVal
9850                       << " (It is a splitting reduction)\n");
9851     return VectorCost - ScalarCost;
9852   }
9853 
9854   /// Emit a horizontal reduction of the vectorized value.
9855   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
9856                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
9857     assert(VectorizedValue && "Need to have a vectorized tree node");
9858     assert(isPowerOf2_32(ReduxWidth) &&
9859            "We only handle power-of-two reductions for now");
9860     assert(RdxKind != RecurKind::FMulAdd &&
9861            "A call to the llvm.fmuladd intrinsic is not handled yet");
9862 
9863     ++NumVectorInstructions;
9864     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
9865   }
9866 };
9867 
9868 } // end anonymous namespace
9869 
9870 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
9871   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
9872     return cast<FixedVectorType>(IE->getType())->getNumElements();
9873 
9874   unsigned AggregateSize = 1;
9875   auto *IV = cast<InsertValueInst>(InsertInst);
9876   Type *CurrentType = IV->getType();
9877   do {
9878     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
9879       for (auto *Elt : ST->elements())
9880         if (Elt != ST->getElementType(0)) // check homogeneity
9881           return None;
9882       AggregateSize *= ST->getNumElements();
9883       CurrentType = ST->getElementType(0);
9884     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
9885       AggregateSize *= AT->getNumElements();
9886       CurrentType = AT->getElementType();
9887     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
9888       AggregateSize *= VT->getNumElements();
9889       return AggregateSize;
9890     } else if (CurrentType->isSingleValueType()) {
9891       return AggregateSize;
9892     } else {
9893       return None;
9894     }
9895   } while (true);
9896 }
9897 
9898 static void findBuildAggregate_rec(Instruction *LastInsertInst,
9899                                    TargetTransformInfo *TTI,
9900                                    SmallVectorImpl<Value *> &BuildVectorOpds,
9901                                    SmallVectorImpl<Value *> &InsertElts,
9902                                    unsigned OperandOffset) {
9903   do {
9904     Value *InsertedOperand = LastInsertInst->getOperand(1);
9905     Optional<unsigned> OperandIndex =
9906         getInsertIndex(LastInsertInst, OperandOffset);
9907     if (!OperandIndex)
9908       return;
9909     if (isa<InsertElementInst>(InsertedOperand) ||
9910         isa<InsertValueInst>(InsertedOperand)) {
9911       findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
9912                              BuildVectorOpds, InsertElts, *OperandIndex);
9913 
9914     } else {
9915       BuildVectorOpds[*OperandIndex] = InsertedOperand;
9916       InsertElts[*OperandIndex] = LastInsertInst;
9917     }
9918     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
9919   } while (LastInsertInst != nullptr &&
9920            (isa<InsertValueInst>(LastInsertInst) ||
9921             isa<InsertElementInst>(LastInsertInst)) &&
9922            LastInsertInst->hasOneUse());
9923 }
9924 
9925 /// Recognize construction of vectors like
9926 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
9927 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
9928 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
9929 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
9930 ///  starting from the last insertelement or insertvalue instruction.
9931 ///
9932 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
9933 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
9934 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
9935 ///
9936 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
9937 ///
9938 /// \return true if it matches.
9939 static bool findBuildAggregate(Instruction *LastInsertInst,
9940                                TargetTransformInfo *TTI,
9941                                SmallVectorImpl<Value *> &BuildVectorOpds,
9942                                SmallVectorImpl<Value *> &InsertElts) {
9943 
9944   assert((isa<InsertElementInst>(LastInsertInst) ||
9945           isa<InsertValueInst>(LastInsertInst)) &&
9946          "Expected insertelement or insertvalue instruction!");
9947 
9948   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
9949          "Expected empty result vectors!");
9950 
9951   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
9952   if (!AggregateSize)
9953     return false;
9954   BuildVectorOpds.resize(*AggregateSize);
9955   InsertElts.resize(*AggregateSize);
9956 
9957   findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
9958   llvm::erase_value(BuildVectorOpds, nullptr);
9959   llvm::erase_value(InsertElts, nullptr);
9960   if (BuildVectorOpds.size() >= 2)
9961     return true;
9962 
9963   return false;
9964 }
9965 
9966 /// Try and get a reduction value from a phi node.
9967 ///
9968 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
9969 /// if they come from either \p ParentBB or a containing loop latch.
9970 ///
9971 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
9972 /// if not possible.
9973 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
9974                                 BasicBlock *ParentBB, LoopInfo *LI) {
9975   // There are situations where the reduction value is not dominated by the
9976   // reduction phi. Vectorizing such cases has been reported to cause
9977   // miscompiles. See PR25787.
9978   auto DominatedReduxValue = [&](Value *R) {
9979     return isa<Instruction>(R) &&
9980            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
9981   };
9982 
9983   Value *Rdx = nullptr;
9984 
9985   // Return the incoming value if it comes from the same BB as the phi node.
9986   if (P->getIncomingBlock(0) == ParentBB) {
9987     Rdx = P->getIncomingValue(0);
9988   } else if (P->getIncomingBlock(1) == ParentBB) {
9989     Rdx = P->getIncomingValue(1);
9990   }
9991 
9992   if (Rdx && DominatedReduxValue(Rdx))
9993     return Rdx;
9994 
9995   // Otherwise, check whether we have a loop latch to look at.
9996   Loop *BBL = LI->getLoopFor(ParentBB);
9997   if (!BBL)
9998     return nullptr;
9999   BasicBlock *BBLatch = BBL->getLoopLatch();
10000   if (!BBLatch)
10001     return nullptr;
10002 
10003   // There is a loop latch, return the incoming value if it comes from
10004   // that. This reduction pattern occasionally turns up.
10005   if (P->getIncomingBlock(0) == BBLatch) {
10006     Rdx = P->getIncomingValue(0);
10007   } else if (P->getIncomingBlock(1) == BBLatch) {
10008     Rdx = P->getIncomingValue(1);
10009   }
10010 
10011   if (Rdx && DominatedReduxValue(Rdx))
10012     return Rdx;
10013 
10014   return nullptr;
10015 }
10016 
10017 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
10018   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
10019     return true;
10020   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
10021     return true;
10022   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
10023     return true;
10024   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
10025     return true;
10026   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
10027     return true;
10028   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
10029     return true;
10030   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
10031     return true;
10032   return false;
10033 }
10034 
10035 /// Attempt to reduce a horizontal reduction.
10036 /// If it is legal to match a horizontal reduction feeding the phi node \a P
10037 /// with reduction operators \a Root (or one of its operands) in a basic block
10038 /// \a BB, then check if it can be done. If horizontal reduction is not found
10039 /// and root instruction is a binary operation, vectorization of the operands is
10040 /// attempted.
10041 /// \returns true if a horizontal reduction was matched and reduced or operands
10042 /// of one of the binary instruction were vectorized.
10043 /// \returns false if a horizontal reduction was not matched (or not possible)
10044 /// or no vectorization of any binary operation feeding \a Root instruction was
10045 /// performed.
10046 static bool tryToVectorizeHorReductionOrInstOperands(
10047     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
10048     TargetTransformInfo *TTI,
10049     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
10050   if (!ShouldVectorizeHor)
10051     return false;
10052 
10053   if (!Root)
10054     return false;
10055 
10056   if (Root->getParent() != BB || isa<PHINode>(Root))
10057     return false;
10058   // Start analysis starting from Root instruction. If horizontal reduction is
10059   // found, try to vectorize it. If it is not a horizontal reduction or
10060   // vectorization is not possible or not effective, and currently analyzed
10061   // instruction is a binary operation, try to vectorize the operands, using
10062   // pre-order DFS traversal order. If the operands were not vectorized, repeat
10063   // the same procedure considering each operand as a possible root of the
10064   // horizontal reduction.
10065   // Interrupt the process if the Root instruction itself was vectorized or all
10066   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
10067   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
10068   // CmpInsts so we can skip extra attempts in
10069   // tryToVectorizeHorReductionOrInstOperands and save compile time.
10070   std::queue<std::pair<Instruction *, unsigned>> Stack;
10071   Stack.emplace(Root, 0);
10072   SmallPtrSet<Value *, 8> VisitedInstrs;
10073   SmallVector<WeakTrackingVH> PostponedInsts;
10074   bool Res = false;
10075   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
10076                                      Value *&B1) -> Value * {
10077     bool IsBinop = matchRdxBop(Inst, B0, B1);
10078     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
10079     if (IsBinop || IsSelect) {
10080       HorizontalReduction HorRdx;
10081       if (HorRdx.matchAssociativeReduction(P, Inst))
10082         return HorRdx.tryToReduce(R, TTI);
10083     }
10084     return nullptr;
10085   };
10086   while (!Stack.empty()) {
10087     Instruction *Inst;
10088     unsigned Level;
10089     std::tie(Inst, Level) = Stack.front();
10090     Stack.pop();
10091     // Do not try to analyze instruction that has already been vectorized.
10092     // This may happen when we vectorize instruction operands on a previous
10093     // iteration while stack was populated before that happened.
10094     if (R.isDeleted(Inst))
10095       continue;
10096     Value *B0 = nullptr, *B1 = nullptr;
10097     if (Value *V = TryToReduce(Inst, B0, B1)) {
10098       Res = true;
10099       // Set P to nullptr to avoid re-analysis of phi node in
10100       // matchAssociativeReduction function unless this is the root node.
10101       P = nullptr;
10102       if (auto *I = dyn_cast<Instruction>(V)) {
10103         // Try to find another reduction.
10104         Stack.emplace(I, Level);
10105         continue;
10106       }
10107     } else {
10108       bool IsBinop = B0 && B1;
10109       if (P && IsBinop) {
10110         Inst = dyn_cast<Instruction>(B0);
10111         if (Inst == P)
10112           Inst = dyn_cast<Instruction>(B1);
10113         if (!Inst) {
10114           // Set P to nullptr to avoid re-analysis of phi node in
10115           // matchAssociativeReduction function unless this is the root node.
10116           P = nullptr;
10117           continue;
10118         }
10119       }
10120       // Set P to nullptr to avoid re-analysis of phi node in
10121       // matchAssociativeReduction function unless this is the root node.
10122       P = nullptr;
10123       // Do not try to vectorize CmpInst operands, this is done separately.
10124       // Final attempt for binop args vectorization should happen after the loop
10125       // to try to find reductions.
10126       if (!isa<CmpInst>(Inst))
10127         PostponedInsts.push_back(Inst);
10128     }
10129 
10130     // Try to vectorize operands.
10131     // Continue analysis for the instruction from the same basic block only to
10132     // save compile time.
10133     if (++Level < RecursionMaxDepth)
10134       for (auto *Op : Inst->operand_values())
10135         if (VisitedInstrs.insert(Op).second)
10136           if (auto *I = dyn_cast<Instruction>(Op))
10137             // Do not try to vectorize CmpInst operands,  this is done
10138             // separately.
10139             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
10140                 I->getParent() == BB)
10141               Stack.emplace(I, Level);
10142   }
10143   // Try to vectorized binops where reductions were not found.
10144   for (Value *V : PostponedInsts)
10145     if (auto *Inst = dyn_cast<Instruction>(V))
10146       if (!R.isDeleted(Inst))
10147         Res |= Vectorize(Inst, R);
10148   return Res;
10149 }
10150 
10151 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
10152                                                  BasicBlock *BB, BoUpSLP &R,
10153                                                  TargetTransformInfo *TTI) {
10154   auto *I = dyn_cast_or_null<Instruction>(V);
10155   if (!I)
10156     return false;
10157 
10158   if (!isa<BinaryOperator>(I))
10159     P = nullptr;
10160   // Try to match and vectorize a horizontal reduction.
10161   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
10162     return tryToVectorize(I, R);
10163   };
10164   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
10165                                                   ExtraVectorization);
10166 }
10167 
10168 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
10169                                                  BasicBlock *BB, BoUpSLP &R) {
10170   const DataLayout &DL = BB->getModule()->getDataLayout();
10171   if (!R.canMapToVector(IVI->getType(), DL))
10172     return false;
10173 
10174   SmallVector<Value *, 16> BuildVectorOpds;
10175   SmallVector<Value *, 16> BuildVectorInsts;
10176   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
10177     return false;
10178 
10179   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
10180   // Aggregate value is unlikely to be processed in vector register.
10181   return tryToVectorizeList(BuildVectorOpds, R);
10182 }
10183 
10184 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
10185                                                    BasicBlock *BB, BoUpSLP &R) {
10186   SmallVector<Value *, 16> BuildVectorInsts;
10187   SmallVector<Value *, 16> BuildVectorOpds;
10188   SmallVector<int> Mask;
10189   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
10190       (llvm::all_of(
10191            BuildVectorOpds,
10192            [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
10193        isFixedVectorShuffle(BuildVectorOpds, Mask)))
10194     return false;
10195 
10196   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
10197   return tryToVectorizeList(BuildVectorInsts, R);
10198 }
10199 
10200 template <typename T>
10201 static bool
10202 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
10203                        function_ref<unsigned(T *)> Limit,
10204                        function_ref<bool(T *, T *)> Comparator,
10205                        function_ref<bool(T *, T *)> AreCompatible,
10206                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
10207                        bool LimitForRegisterSize) {
10208   bool Changed = false;
10209   // Sort by type, parent, operands.
10210   stable_sort(Incoming, Comparator);
10211 
10212   // Try to vectorize elements base on their type.
10213   SmallVector<T *> Candidates;
10214   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
10215     // Look for the next elements with the same type, parent and operand
10216     // kinds.
10217     auto *SameTypeIt = IncIt;
10218     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
10219       ++SameTypeIt;
10220 
10221     // Try to vectorize them.
10222     unsigned NumElts = (SameTypeIt - IncIt);
10223     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
10224                       << NumElts << ")\n");
10225     // The vectorization is a 3-state attempt:
10226     // 1. Try to vectorize instructions with the same/alternate opcodes with the
10227     // size of maximal register at first.
10228     // 2. Try to vectorize remaining instructions with the same type, if
10229     // possible. This may result in the better vectorization results rather than
10230     // if we try just to vectorize instructions with the same/alternate opcodes.
10231     // 3. Final attempt to try to vectorize all instructions with the
10232     // same/alternate ops only, this may result in some extra final
10233     // vectorization.
10234     if (NumElts > 1 &&
10235         TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
10236       // Success start over because instructions might have been changed.
10237       Changed = true;
10238     } else if (NumElts < Limit(*IncIt) &&
10239                (Candidates.empty() ||
10240                 Candidates.front()->getType() == (*IncIt)->getType())) {
10241       Candidates.append(IncIt, std::next(IncIt, NumElts));
10242     }
10243     // Final attempt to vectorize instructions with the same types.
10244     if (Candidates.size() > 1 &&
10245         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
10246       if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
10247         // Success start over because instructions might have been changed.
10248         Changed = true;
10249       } else if (LimitForRegisterSize) {
10250         // Try to vectorize using small vectors.
10251         for (auto *It = Candidates.begin(), *End = Candidates.end();
10252              It != End;) {
10253           auto *SameTypeIt = It;
10254           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
10255             ++SameTypeIt;
10256           unsigned NumElts = (SameTypeIt - It);
10257           if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
10258                                             /*LimitForRegisterSize=*/false))
10259             Changed = true;
10260           It = SameTypeIt;
10261         }
10262       }
10263       Candidates.clear();
10264     }
10265 
10266     // Start over at the next instruction of a different type (or the end).
10267     IncIt = SameTypeIt;
10268   }
10269   return Changed;
10270 }
10271 
10272 /// Compare two cmp instructions. If IsCompatibility is true, function returns
10273 /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
10274 /// operands. If IsCompatibility is false, function implements strict weak
10275 /// ordering relation between two cmp instructions, returning true if the first
10276 /// instruction is "less" than the second, i.e. its predicate is less than the
10277 /// predicate of the second or the operands IDs are less than the operands IDs
10278 /// of the second cmp instruction.
10279 template <bool IsCompatibility>
10280 static bool compareCmp(Value *V, Value *V2,
10281                        function_ref<bool(Instruction *)> IsDeleted) {
10282   auto *CI1 = cast<CmpInst>(V);
10283   auto *CI2 = cast<CmpInst>(V2);
10284   if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
10285     return false;
10286   if (CI1->getOperand(0)->getType()->getTypeID() <
10287       CI2->getOperand(0)->getType()->getTypeID())
10288     return !IsCompatibility;
10289   if (CI1->getOperand(0)->getType()->getTypeID() >
10290       CI2->getOperand(0)->getType()->getTypeID())
10291     return false;
10292   CmpInst::Predicate Pred1 = CI1->getPredicate();
10293   CmpInst::Predicate Pred2 = CI2->getPredicate();
10294   CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
10295   CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
10296   CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
10297   CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
10298   if (BasePred1 < BasePred2)
10299     return !IsCompatibility;
10300   if (BasePred1 > BasePred2)
10301     return false;
10302   // Compare operands.
10303   bool LEPreds = Pred1 <= Pred2;
10304   bool GEPreds = Pred1 >= Pred2;
10305   for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
10306     auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
10307     auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
10308     if (Op1->getValueID() < Op2->getValueID())
10309       return !IsCompatibility;
10310     if (Op1->getValueID() > Op2->getValueID())
10311       return false;
10312     if (auto *I1 = dyn_cast<Instruction>(Op1))
10313       if (auto *I2 = dyn_cast<Instruction>(Op2)) {
10314         if (I1->getParent() != I2->getParent())
10315           return false;
10316         InstructionsState S = getSameOpcode({I1, I2});
10317         if (S.getOpcode())
10318           continue;
10319         return false;
10320       }
10321   }
10322   return IsCompatibility;
10323 }
10324 
10325 bool SLPVectorizerPass::vectorizeSimpleInstructions(
10326     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
10327     bool AtTerminator) {
10328   bool OpsChanged = false;
10329   SmallVector<Instruction *, 4> PostponedCmps;
10330   for (auto *I : reverse(Instructions)) {
10331     if (R.isDeleted(I))
10332       continue;
10333     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
10334       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
10335     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
10336       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
10337     else if (isa<CmpInst>(I))
10338       PostponedCmps.push_back(I);
10339   }
10340   if (AtTerminator) {
10341     // Try to find reductions first.
10342     for (Instruction *I : PostponedCmps) {
10343       if (R.isDeleted(I))
10344         continue;
10345       for (Value *Op : I->operands())
10346         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
10347     }
10348     // Try to vectorize operands as vector bundles.
10349     for (Instruction *I : PostponedCmps) {
10350       if (R.isDeleted(I))
10351         continue;
10352       OpsChanged |= tryToVectorize(I, R);
10353     }
10354     // Try to vectorize list of compares.
10355     // Sort by type, compare predicate, etc.
10356     auto &&CompareSorter = [&R](Value *V, Value *V2) {
10357       return compareCmp<false>(V, V2,
10358                                [&R](Instruction *I) { return R.isDeleted(I); });
10359     };
10360 
10361     auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
10362       if (V1 == V2)
10363         return true;
10364       return compareCmp<true>(V1, V2,
10365                               [&R](Instruction *I) { return R.isDeleted(I); });
10366     };
10367     auto Limit = [&R](Value *V) {
10368       unsigned EltSize = R.getVectorElementSize(V);
10369       return std::max(2U, R.getMaxVecRegSize() / EltSize);
10370     };
10371 
10372     SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
10373     OpsChanged |= tryToVectorizeSequence<Value>(
10374         Vals, Limit, CompareSorter, AreCompatibleCompares,
10375         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10376           // Exclude possible reductions from other blocks.
10377           bool ArePossiblyReducedInOtherBlock =
10378               any_of(Candidates, [](Value *V) {
10379                 return any_of(V->users(), [V](User *U) {
10380                   return isa<SelectInst>(U) &&
10381                          cast<SelectInst>(U)->getParent() !=
10382                              cast<Instruction>(V)->getParent();
10383                 });
10384               });
10385           if (ArePossiblyReducedInOtherBlock)
10386             return false;
10387           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10388         },
10389         /*LimitForRegisterSize=*/true);
10390     Instructions.clear();
10391   } else {
10392     // Insert in reverse order since the PostponedCmps vector was filled in
10393     // reverse order.
10394     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
10395   }
10396   return OpsChanged;
10397 }
10398 
10399 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
10400   bool Changed = false;
10401   SmallVector<Value *, 4> Incoming;
10402   SmallPtrSet<Value *, 16> VisitedInstrs;
10403   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
10404   // node. Allows better to identify the chains that can be vectorized in the
10405   // better way.
10406   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
10407   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
10408     assert(isValidElementType(V1->getType()) &&
10409            isValidElementType(V2->getType()) &&
10410            "Expected vectorizable types only.");
10411     // It is fine to compare type IDs here, since we expect only vectorizable
10412     // types, like ints, floats and pointers, we don't care about other type.
10413     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
10414       return true;
10415     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
10416       return false;
10417     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10418     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10419     if (Opcodes1.size() < Opcodes2.size())
10420       return true;
10421     if (Opcodes1.size() > Opcodes2.size())
10422       return false;
10423     Optional<bool> ConstOrder;
10424     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10425       // Undefs are compatible with any other value.
10426       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
10427         if (!ConstOrder)
10428           ConstOrder =
10429               !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
10430         continue;
10431       }
10432       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10433         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10434           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
10435           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
10436           if (!NodeI1)
10437             return NodeI2 != nullptr;
10438           if (!NodeI2)
10439             return false;
10440           assert((NodeI1 == NodeI2) ==
10441                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10442                  "Different nodes should have different DFS numbers");
10443           if (NodeI1 != NodeI2)
10444             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10445           InstructionsState S = getSameOpcode({I1, I2});
10446           if (S.getOpcode())
10447             continue;
10448           return I1->getOpcode() < I2->getOpcode();
10449         }
10450       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
10451         if (!ConstOrder)
10452           ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
10453         continue;
10454       }
10455       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
10456         return true;
10457       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
10458         return false;
10459     }
10460     return ConstOrder && *ConstOrder;
10461   };
10462   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
10463     if (V1 == V2)
10464       return true;
10465     if (V1->getType() != V2->getType())
10466       return false;
10467     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
10468     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
10469     if (Opcodes1.size() != Opcodes2.size())
10470       return false;
10471     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
10472       // Undefs are compatible with any other value.
10473       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
10474         continue;
10475       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
10476         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
10477           if (I1->getParent() != I2->getParent())
10478             return false;
10479           InstructionsState S = getSameOpcode({I1, I2});
10480           if (S.getOpcode())
10481             continue;
10482           return false;
10483         }
10484       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
10485         continue;
10486       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
10487         return false;
10488     }
10489     return true;
10490   };
10491   auto Limit = [&R](Value *V) {
10492     unsigned EltSize = R.getVectorElementSize(V);
10493     return std::max(2U, R.getMaxVecRegSize() / EltSize);
10494   };
10495 
10496   bool HaveVectorizedPhiNodes = false;
10497   do {
10498     // Collect the incoming values from the PHIs.
10499     Incoming.clear();
10500     for (Instruction &I : *BB) {
10501       PHINode *P = dyn_cast<PHINode>(&I);
10502       if (!P)
10503         break;
10504 
10505       // No need to analyze deleted, vectorized and non-vectorizable
10506       // instructions.
10507       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
10508           isValidElementType(P->getType()))
10509         Incoming.push_back(P);
10510     }
10511 
10512     // Find the corresponding non-phi nodes for better matching when trying to
10513     // build the tree.
10514     for (Value *V : Incoming) {
10515       SmallVectorImpl<Value *> &Opcodes =
10516           PHIToOpcodes.try_emplace(V).first->getSecond();
10517       if (!Opcodes.empty())
10518         continue;
10519       SmallVector<Value *, 4> Nodes(1, V);
10520       SmallPtrSet<Value *, 4> Visited;
10521       while (!Nodes.empty()) {
10522         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
10523         if (!Visited.insert(PHI).second)
10524           continue;
10525         for (Value *V : PHI->incoming_values()) {
10526           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
10527             Nodes.push_back(PHI1);
10528             continue;
10529           }
10530           Opcodes.emplace_back(V);
10531         }
10532       }
10533     }
10534 
10535     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
10536         Incoming, Limit, PHICompare, AreCompatiblePHIs,
10537         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
10538           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
10539         },
10540         /*LimitForRegisterSize=*/true);
10541     Changed |= HaveVectorizedPhiNodes;
10542     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
10543   } while (HaveVectorizedPhiNodes);
10544 
10545   VisitedInstrs.clear();
10546 
10547   SmallVector<Instruction *, 8> PostProcessInstructions;
10548   SmallDenseSet<Instruction *, 4> KeyNodes;
10549   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
10550     // Skip instructions with scalable type. The num of elements is unknown at
10551     // compile-time for scalable type.
10552     if (isa<ScalableVectorType>(it->getType()))
10553       continue;
10554 
10555     // Skip instructions marked for the deletion.
10556     if (R.isDeleted(&*it))
10557       continue;
10558     // We may go through BB multiple times so skip the one we have checked.
10559     if (!VisitedInstrs.insert(&*it).second) {
10560       if (it->use_empty() && KeyNodes.contains(&*it) &&
10561           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10562                                       it->isTerminator())) {
10563         // We would like to start over since some instructions are deleted
10564         // and the iterator may become invalid value.
10565         Changed = true;
10566         it = BB->begin();
10567         e = BB->end();
10568       }
10569       continue;
10570     }
10571 
10572     if (isa<DbgInfoIntrinsic>(it))
10573       continue;
10574 
10575     // Try to vectorize reductions that use PHINodes.
10576     if (PHINode *P = dyn_cast<PHINode>(it)) {
10577       // Check that the PHI is a reduction PHI.
10578       if (P->getNumIncomingValues() == 2) {
10579         // Try to match and vectorize a horizontal reduction.
10580         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
10581                                      TTI)) {
10582           Changed = true;
10583           it = BB->begin();
10584           e = BB->end();
10585           continue;
10586         }
10587       }
10588       // Try to vectorize the incoming values of the PHI, to catch reductions
10589       // that feed into PHIs.
10590       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
10591         // Skip if the incoming block is the current BB for now. Also, bypass
10592         // unreachable IR for efficiency and to avoid crashing.
10593         // TODO: Collect the skipped incoming values and try to vectorize them
10594         // after processing BB.
10595         if (BB == P->getIncomingBlock(I) ||
10596             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
10597           continue;
10598 
10599         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
10600                                             P->getIncomingBlock(I), R, TTI);
10601       }
10602       continue;
10603     }
10604 
10605     // Ran into an instruction without users, like terminator, or function call
10606     // with ignored return value, store. Ignore unused instructions (basing on
10607     // instruction type, except for CallInst and InvokeInst).
10608     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
10609                             isa<InvokeInst>(it))) {
10610       KeyNodes.insert(&*it);
10611       bool OpsChanged = false;
10612       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
10613         for (auto *V : it->operand_values()) {
10614           // Try to match and vectorize a horizontal reduction.
10615           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
10616         }
10617       }
10618       // Start vectorization of post-process list of instructions from the
10619       // top-tree instructions to try to vectorize as many instructions as
10620       // possible.
10621       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
10622                                                 it->isTerminator());
10623       if (OpsChanged) {
10624         // We would like to start over since some instructions are deleted
10625         // and the iterator may become invalid value.
10626         Changed = true;
10627         it = BB->begin();
10628         e = BB->end();
10629         continue;
10630       }
10631     }
10632 
10633     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
10634         isa<InsertValueInst>(it))
10635       PostProcessInstructions.push_back(&*it);
10636   }
10637 
10638   return Changed;
10639 }
10640 
10641 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
10642   auto Changed = false;
10643   for (auto &Entry : GEPs) {
10644     // If the getelementptr list has fewer than two elements, there's nothing
10645     // to do.
10646     if (Entry.second.size() < 2)
10647       continue;
10648 
10649     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
10650                       << Entry.second.size() << ".\n");
10651 
10652     // Process the GEP list in chunks suitable for the target's supported
10653     // vector size. If a vector register can't hold 1 element, we are done. We
10654     // are trying to vectorize the index computations, so the maximum number of
10655     // elements is based on the size of the index expression, rather than the
10656     // size of the GEP itself (the target's pointer size).
10657     unsigned MaxVecRegSize = R.getMaxVecRegSize();
10658     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
10659     if (MaxVecRegSize < EltSize)
10660       continue;
10661 
10662     unsigned MaxElts = MaxVecRegSize / EltSize;
10663     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
10664       auto Len = std::min<unsigned>(BE - BI, MaxElts);
10665       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
10666 
10667       // Initialize a set a candidate getelementptrs. Note that we use a
10668       // SetVector here to preserve program order. If the index computations
10669       // are vectorizable and begin with loads, we want to minimize the chance
10670       // of having to reorder them later.
10671       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
10672 
10673       // Some of the candidates may have already been vectorized after we
10674       // initially collected them. If so, they are marked as deleted, so remove
10675       // them from the set of candidates.
10676       Candidates.remove_if(
10677           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
10678 
10679       // Remove from the set of candidates all pairs of getelementptrs with
10680       // constant differences. Such getelementptrs are likely not good
10681       // candidates for vectorization in a bottom-up phase since one can be
10682       // computed from the other. We also ensure all candidate getelementptr
10683       // indices are unique.
10684       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
10685         auto *GEPI = GEPList[I];
10686         if (!Candidates.count(GEPI))
10687           continue;
10688         auto *SCEVI = SE->getSCEV(GEPList[I]);
10689         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
10690           auto *GEPJ = GEPList[J];
10691           auto *SCEVJ = SE->getSCEV(GEPList[J]);
10692           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
10693             Candidates.remove(GEPI);
10694             Candidates.remove(GEPJ);
10695           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
10696             Candidates.remove(GEPJ);
10697           }
10698         }
10699       }
10700 
10701       // We break out of the above computation as soon as we know there are
10702       // fewer than two candidates remaining.
10703       if (Candidates.size() < 2)
10704         continue;
10705 
10706       // Add the single, non-constant index of each candidate to the bundle. We
10707       // ensured the indices met these constraints when we originally collected
10708       // the getelementptrs.
10709       SmallVector<Value *, 16> Bundle(Candidates.size());
10710       auto BundleIndex = 0u;
10711       for (auto *V : Candidates) {
10712         auto *GEP = cast<GetElementPtrInst>(V);
10713         auto *GEPIdx = GEP->idx_begin()->get();
10714         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
10715         Bundle[BundleIndex++] = GEPIdx;
10716       }
10717 
10718       // Try and vectorize the indices. We are currently only interested in
10719       // gather-like cases of the form:
10720       //
10721       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
10722       //
10723       // where the loads of "a", the loads of "b", and the subtractions can be
10724       // performed in parallel. It's likely that detecting this pattern in a
10725       // bottom-up phase will be simpler and less costly than building a
10726       // full-blown top-down phase beginning at the consecutive loads.
10727       Changed |= tryToVectorizeList(Bundle, R);
10728     }
10729   }
10730   return Changed;
10731 }
10732 
10733 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
10734   bool Changed = false;
10735   // Sort by type, base pointers and values operand. Value operands must be
10736   // compatible (have the same opcode, same parent), otherwise it is
10737   // definitely not profitable to try to vectorize them.
10738   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
10739     if (V->getPointerOperandType()->getTypeID() <
10740         V2->getPointerOperandType()->getTypeID())
10741       return true;
10742     if (V->getPointerOperandType()->getTypeID() >
10743         V2->getPointerOperandType()->getTypeID())
10744       return false;
10745     // UndefValues are compatible with all other values.
10746     if (isa<UndefValue>(V->getValueOperand()) ||
10747         isa<UndefValue>(V2->getValueOperand()))
10748       return false;
10749     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
10750       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10751         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
10752             DT->getNode(I1->getParent());
10753         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
10754             DT->getNode(I2->getParent());
10755         assert(NodeI1 && "Should only process reachable instructions");
10756         assert(NodeI1 && "Should only process reachable instructions");
10757         assert((NodeI1 == NodeI2) ==
10758                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
10759                "Different nodes should have different DFS numbers");
10760         if (NodeI1 != NodeI2)
10761           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
10762         InstructionsState S = getSameOpcode({I1, I2});
10763         if (S.getOpcode())
10764           return false;
10765         return I1->getOpcode() < I2->getOpcode();
10766       }
10767     if (isa<Constant>(V->getValueOperand()) &&
10768         isa<Constant>(V2->getValueOperand()))
10769       return false;
10770     return V->getValueOperand()->getValueID() <
10771            V2->getValueOperand()->getValueID();
10772   };
10773 
10774   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
10775     if (V1 == V2)
10776       return true;
10777     if (V1->getPointerOperandType() != V2->getPointerOperandType())
10778       return false;
10779     // Undefs are compatible with any other value.
10780     if (isa<UndefValue>(V1->getValueOperand()) ||
10781         isa<UndefValue>(V2->getValueOperand()))
10782       return true;
10783     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
10784       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
10785         if (I1->getParent() != I2->getParent())
10786           return false;
10787         InstructionsState S = getSameOpcode({I1, I2});
10788         return S.getOpcode() > 0;
10789       }
10790     if (isa<Constant>(V1->getValueOperand()) &&
10791         isa<Constant>(V2->getValueOperand()))
10792       return true;
10793     return V1->getValueOperand()->getValueID() ==
10794            V2->getValueOperand()->getValueID();
10795   };
10796   auto Limit = [&R, this](StoreInst *SI) {
10797     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
10798     return R.getMinVF(EltSize);
10799   };
10800 
10801   // Attempt to sort and vectorize each of the store-groups.
10802   for (auto &Pair : Stores) {
10803     if (Pair.second.size() < 2)
10804       continue;
10805 
10806     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
10807                       << Pair.second.size() << ".\n");
10808 
10809     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
10810       continue;
10811 
10812     Changed |= tryToVectorizeSequence<StoreInst>(
10813         Pair.second, Limit, StoreSorter, AreCompatibleStores,
10814         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
10815           return vectorizeStores(Candidates, R);
10816         },
10817         /*LimitForRegisterSize=*/false);
10818   }
10819   return Changed;
10820 }
10821 
10822 char SLPVectorizer::ID = 0;
10823 
10824 static const char lv_name[] = "SLP Vectorizer";
10825 
10826 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
10827 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
10828 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
10829 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
10830 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
10831 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
10832 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
10833 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
10834 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
10835 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
10836 
10837 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
10838