1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/PriorityQueue.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SetOperations.h"
27 #include "llvm/ADT/SetVector.h"
28 #include "llvm/ADT/SmallBitVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallSet.h"
31 #include "llvm/ADT/SmallString.h"
32 #include "llvm/ADT/Statistic.h"
33 #include "llvm/ADT/iterator.h"
34 #include "llvm/ADT/iterator_range.h"
35 #include "llvm/Analysis/AliasAnalysis.h"
36 #include "llvm/Analysis/AssumptionCache.h"
37 #include "llvm/Analysis/CodeMetrics.h"
38 #include "llvm/Analysis/DemandedBits.h"
39 #include "llvm/Analysis/GlobalsModRef.h"
40 #include "llvm/Analysis/IVDescriptors.h"
41 #include "llvm/Analysis/LoopAccessAnalysis.h"
42 #include "llvm/Analysis/LoopInfo.h"
43 #include "llvm/Analysis/MemoryLocation.h"
44 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
45 #include "llvm/Analysis/ScalarEvolution.h"
46 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
47 #include "llvm/Analysis/TargetLibraryInfo.h"
48 #include "llvm/Analysis/TargetTransformInfo.h"
49 #include "llvm/Analysis/ValueTracking.h"
50 #include "llvm/Analysis/VectorUtils.h"
51 #include "llvm/IR/Attributes.h"
52 #include "llvm/IR/BasicBlock.h"
53 #include "llvm/IR/Constant.h"
54 #include "llvm/IR/Constants.h"
55 #include "llvm/IR/DataLayout.h"
56 #include "llvm/IR/DebugLoc.h"
57 #include "llvm/IR/DerivedTypes.h"
58 #include "llvm/IR/Dominators.h"
59 #include "llvm/IR/Function.h"
60 #include "llvm/IR/IRBuilder.h"
61 #include "llvm/IR/InstrTypes.h"
62 #include "llvm/IR/Instruction.h"
63 #include "llvm/IR/Instructions.h"
64 #include "llvm/IR/IntrinsicInst.h"
65 #include "llvm/IR/Intrinsics.h"
66 #include "llvm/IR/Module.h"
67 #include "llvm/IR/NoFolder.h"
68 #include "llvm/IR/Operator.h"
69 #include "llvm/IR/PatternMatch.h"
70 #include "llvm/IR/Type.h"
71 #include "llvm/IR/Use.h"
72 #include "llvm/IR/User.h"
73 #include "llvm/IR/Value.h"
74 #include "llvm/IR/ValueHandle.h"
75 #include "llvm/IR/Verifier.h"
76 #include "llvm/InitializePasses.h"
77 #include "llvm/Pass.h"
78 #include "llvm/Support/Casting.h"
79 #include "llvm/Support/CommandLine.h"
80 #include "llvm/Support/Compiler.h"
81 #include "llvm/Support/DOTGraphTraits.h"
82 #include "llvm/Support/Debug.h"
83 #include "llvm/Support/ErrorHandling.h"
84 #include "llvm/Support/GraphWriter.h"
85 #include "llvm/Support/InstructionCost.h"
86 #include "llvm/Support/KnownBits.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/raw_ostream.h"
89 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
90 #include "llvm/Transforms/Utils/LoopUtils.h"
91 #include "llvm/Transforms/Vectorize.h"
92 #include <algorithm>
93 #include <cassert>
94 #include <cstdint>
95 #include <iterator>
96 #include <memory>
97 #include <set>
98 #include <string>
99 #include <tuple>
100 #include <utility>
101 #include <vector>
102 
103 using namespace llvm;
104 using namespace llvm::PatternMatch;
105 using namespace slpvectorizer;
106 
107 #define SV_NAME "slp-vectorizer"
108 #define DEBUG_TYPE "SLP"
109 
110 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111 
112 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
113                                   cl::desc("Run the SLP vectorization passes"));
114 
115 static cl::opt<int>
116     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
117                      cl::desc("Only vectorize if you gain more than this "
118                               "number "));
119 
120 static cl::opt<bool>
121 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122                    cl::desc("Attempt to vectorize horizontal reductions"));
123 
124 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
125     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126     cl::desc(
127         "Attempt to vectorize horizontal reductions feeding into a store"));
128 
129 static cl::opt<int>
130 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
131     cl::desc("Attempt to vectorize for this register size in bits"));
132 
133 static cl::opt<unsigned>
134 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
135     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136 
137 static cl::opt<int>
138 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139     cl::desc("Maximum depth of the lookup for consecutive stores."));
140 
141 /// Limits the size of scheduling regions in a block.
142 /// It avoid long compile times for _very_ large blocks where vector
143 /// instructions are spread over a wide range.
144 /// This limit is way higher than needed by real-world functions.
145 static cl::opt<int>
146 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147     cl::desc("Limit the size of the SLP scheduling region per block"));
148 
149 static cl::opt<int> MinVectorRegSizeOption(
150     "slp-min-reg-size", cl::init(128), cl::Hidden,
151     cl::desc("Attempt to vectorize for this register size in bits"));
152 
153 static cl::opt<unsigned> RecursionMaxDepth(
154     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155     cl::desc("Limit the recursion depth when building a vectorizable tree"));
156 
157 static cl::opt<unsigned> MinTreeSize(
158     "slp-min-tree-size", cl::init(3), cl::Hidden,
159     cl::desc("Only vectorize small trees if they are fully vectorizable"));
160 
161 // The maximum depth that the look-ahead score heuristic will explore.
162 // The higher this value, the higher the compilation time overhead.
163 static cl::opt<int> LookAheadMaxDepth(
164     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165     cl::desc("The maximum look-ahead depth for operand reordering scores"));
166 
167 // The Look-ahead heuristic goes through the users of the bundle to calculate
168 // the users cost in getExternalUsesCost(). To avoid compilation time increase
169 // we limit the number of users visited to this value.
170 static cl::opt<unsigned> LookAheadUsersBudget(
171     "slp-look-ahead-users-budget", cl::init(2), cl::Hidden,
172     cl::desc("The maximum number of users to visit while visiting the "
173              "predecessors. This prevents compilation time increase."));
174 
175 static cl::opt<bool>
176     ViewSLPTree("view-slp-tree", cl::Hidden,
177                 cl::desc("Display the SLP trees with Graphviz"));
178 
179 // Limit the number of alias checks. The limit is chosen so that
180 // it has no negative effect on the llvm benchmarks.
181 static const unsigned AliasedCheckLimit = 10;
182 
183 // Another limit for the alias checks: The maximum distance between load/store
184 // instructions where alias checks are done.
185 // This limit is useful for very large basic blocks.
186 static const unsigned MaxMemDepDistance = 160;
187 
188 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
189 /// regions to be handled.
190 static const int MinScheduleRegionSize = 16;
191 
192 /// Predicate for the element types that the SLP vectorizer supports.
193 ///
194 /// The most important thing to filter here are types which are invalid in LLVM
195 /// vectors. We also filter target specific types which have absolutely no
196 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
197 /// avoids spending time checking the cost model and realizing that they will
198 /// be inevitably scalarized.
199 static bool isValidElementType(Type *Ty) {
200   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
201          !Ty->isPPC_FP128Ty();
202 }
203 
204 /// \returns True if the value is a constant (but not globals/constant
205 /// expressions).
206 static bool isConstant(Value *V) {
207   return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
208 }
209 
210 /// Checks if \p V is one of vector-like instructions, i.e. undef,
211 /// insertelement/extractelement with constant indices for fixed vector type or
212 /// extractvalue instruction.
213 static bool isVectorLikeInstWithConstOps(Value *V) {
214   if (!isa<InsertElementInst, ExtractElementInst>(V) &&
215       !isa<ExtractValueInst, UndefValue>(V))
216     return false;
217   auto *I = dyn_cast<Instruction>(V);
218   if (!I || isa<ExtractValueInst>(I))
219     return true;
220   if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
221     return false;
222   if (isa<ExtractElementInst>(I))
223     return isConstant(I->getOperand(1));
224   assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
225   return isConstant(I->getOperand(2));
226 }
227 
228 /// \returns true if all of the instructions in \p VL are in the same block or
229 /// false otherwise.
230 static bool allSameBlock(ArrayRef<Value *> VL) {
231   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
232   if (!I0)
233     return false;
234   if (all_of(VL, isVectorLikeInstWithConstOps))
235     return true;
236 
237   BasicBlock *BB = I0->getParent();
238   for (int I = 1, E = VL.size(); I < E; I++) {
239     auto *II = dyn_cast<Instruction>(VL[I]);
240     if (!II)
241       return false;
242 
243     if (BB != II->getParent())
244       return false;
245   }
246   return true;
247 }
248 
249 /// \returns True if all of the values in \p VL are constants (but not
250 /// globals/constant expressions).
251 static bool allConstant(ArrayRef<Value *> VL) {
252   // Constant expressions and globals can't be vectorized like normal integer/FP
253   // constants.
254   return all_of(VL, isConstant);
255 }
256 
257 /// \returns True if all of the values in \p VL are identical.
258 static bool isSplat(ArrayRef<Value *> VL) {
259   for (unsigned i = 1, e = VL.size(); i < e; ++i)
260     if (VL[i] != VL[0])
261       return false;
262   return true;
263 }
264 
265 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
266 static bool isCommutative(Instruction *I) {
267   if (auto *Cmp = dyn_cast<CmpInst>(I))
268     return Cmp->isCommutative();
269   if (auto *BO = dyn_cast<BinaryOperator>(I))
270     return BO->isCommutative();
271   // TODO: This should check for generic Instruction::isCommutative(), but
272   //       we need to confirm that the caller code correctly handles Intrinsics
273   //       for example (does not have 2 operands).
274   return false;
275 }
276 
277 /// Checks if the vector of instructions can be represented as a shuffle, like:
278 /// %x0 = extractelement <4 x i8> %x, i32 0
279 /// %x3 = extractelement <4 x i8> %x, i32 3
280 /// %y1 = extractelement <4 x i8> %y, i32 1
281 /// %y2 = extractelement <4 x i8> %y, i32 2
282 /// %x0x0 = mul i8 %x0, %x0
283 /// %x3x3 = mul i8 %x3, %x3
284 /// %y1y1 = mul i8 %y1, %y1
285 /// %y2y2 = mul i8 %y2, %y2
286 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
287 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
288 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
289 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
290 /// ret <4 x i8> %ins4
291 /// can be transformed into:
292 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
293 ///                                                         i32 6>
294 /// %2 = mul <4 x i8> %1, %1
295 /// ret <4 x i8> %2
296 /// We convert this initially to something like:
297 /// %x0 = extractelement <4 x i8> %x, i32 0
298 /// %x3 = extractelement <4 x i8> %x, i32 3
299 /// %y1 = extractelement <4 x i8> %y, i32 1
300 /// %y2 = extractelement <4 x i8> %y, i32 2
301 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
302 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
303 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
304 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
305 /// %5 = mul <4 x i8> %4, %4
306 /// %6 = extractelement <4 x i8> %5, i32 0
307 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
308 /// %7 = extractelement <4 x i8> %5, i32 1
309 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
310 /// %8 = extractelement <4 x i8> %5, i32 2
311 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
312 /// %9 = extractelement <4 x i8> %5, i32 3
313 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
314 /// ret <4 x i8> %ins4
315 /// InstCombiner transforms this into a shuffle and vector mul
316 /// Mask will return the Shuffle Mask equivalent to the extracted elements.
317 /// TODO: Can we split off and reuse the shuffle mask detection from
318 /// TargetTransformInfo::getInstructionThroughput?
319 static Optional<TargetTransformInfo::ShuffleKind>
320 isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
321   auto *EI0 = cast<ExtractElementInst>(VL[0]);
322   if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
323     return None;
324   unsigned Size =
325       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
326   Value *Vec1 = nullptr;
327   Value *Vec2 = nullptr;
328   enum ShuffleMode { Unknown, Select, Permute };
329   ShuffleMode CommonShuffleMode = Unknown;
330   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
331     auto *EI = cast<ExtractElementInst>(VL[I]);
332     auto *Vec = EI->getVectorOperand();
333     // All vector operands must have the same number of vector elements.
334     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
335       return None;
336     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
337     if (!Idx)
338       return None;
339     // Undefined behavior if Idx is negative or >= Size.
340     if (Idx->getValue().uge(Size)) {
341       Mask.push_back(UndefMaskElem);
342       continue;
343     }
344     unsigned IntIdx = Idx->getValue().getZExtValue();
345     Mask.push_back(IntIdx);
346     // We can extractelement from undef or poison vector.
347     if (isa<UndefValue>(Vec))
348       continue;
349     // For correct shuffling we have to have at most 2 different vector operands
350     // in all extractelement instructions.
351     if (!Vec1 || Vec1 == Vec)
352       Vec1 = Vec;
353     else if (!Vec2 || Vec2 == Vec)
354       Vec2 = Vec;
355     else
356       return None;
357     if (CommonShuffleMode == Permute)
358       continue;
359     // If the extract index is not the same as the operation number, it is a
360     // permutation.
361     if (IntIdx != I) {
362       CommonShuffleMode = Permute;
363       continue;
364     }
365     CommonShuffleMode = Select;
366   }
367   // If we're not crossing lanes in different vectors, consider it as blending.
368   if (CommonShuffleMode == Select && Vec2)
369     return TargetTransformInfo::SK_Select;
370   // If Vec2 was never used, we have a permutation of a single vector, otherwise
371   // we have permutation of 2 vectors.
372   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
373               : TargetTransformInfo::SK_PermuteSingleSrc;
374 }
375 
376 namespace {
377 
378 /// Main data required for vectorization of instructions.
379 struct InstructionsState {
380   /// The very first instruction in the list with the main opcode.
381   Value *OpValue = nullptr;
382 
383   /// The main/alternate instruction.
384   Instruction *MainOp = nullptr;
385   Instruction *AltOp = nullptr;
386 
387   /// The main/alternate opcodes for the list of instructions.
388   unsigned getOpcode() const {
389     return MainOp ? MainOp->getOpcode() : 0;
390   }
391 
392   unsigned getAltOpcode() const {
393     return AltOp ? AltOp->getOpcode() : 0;
394   }
395 
396   /// Some of the instructions in the list have alternate opcodes.
397   bool isAltShuffle() const { return getOpcode() != getAltOpcode(); }
398 
399   bool isOpcodeOrAlt(Instruction *I) const {
400     unsigned CheckedOpcode = I->getOpcode();
401     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
402   }
403 
404   InstructionsState() = delete;
405   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
406       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
407 };
408 
409 } // end anonymous namespace
410 
411 /// Chooses the correct key for scheduling data. If \p Op has the same (or
412 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
413 /// OpValue.
414 static Value *isOneOf(const InstructionsState &S, Value *Op) {
415   auto *I = dyn_cast<Instruction>(Op);
416   if (I && S.isOpcodeOrAlt(I))
417     return Op;
418   return S.OpValue;
419 }
420 
421 /// \returns true if \p Opcode is allowed as part of of the main/alternate
422 /// instruction for SLP vectorization.
423 ///
424 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
425 /// "shuffled out" lane would result in division by zero.
426 static bool isValidForAlternation(unsigned Opcode) {
427   if (Instruction::isIntDivRem(Opcode))
428     return false;
429 
430   return true;
431 }
432 
433 /// \returns analysis of the Instructions in \p VL described in
434 /// InstructionsState, the Opcode that we suppose the whole list
435 /// could be vectorized even if its structure is diverse.
436 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
437                                        unsigned BaseIndex = 0) {
438   // Make sure these are all Instructions.
439   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
440     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
441 
442   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
443   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
444   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
445   unsigned AltOpcode = Opcode;
446   unsigned AltIndex = BaseIndex;
447 
448   // Check for one alternate opcode from another BinaryOperator.
449   // TODO - generalize to support all operators (types, calls etc.).
450   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
451     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
452     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
453       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
454         continue;
455       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
456           isValidForAlternation(Opcode)) {
457         AltOpcode = InstOpcode;
458         AltIndex = Cnt;
459         continue;
460       }
461     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
462       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
463       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
464       if (Ty0 == Ty1) {
465         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
466           continue;
467         if (Opcode == AltOpcode) {
468           assert(isValidForAlternation(Opcode) &&
469                  isValidForAlternation(InstOpcode) &&
470                  "Cast isn't safe for alternation, logic needs to be updated!");
471           AltOpcode = InstOpcode;
472           AltIndex = Cnt;
473           continue;
474         }
475       }
476     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
477       continue;
478     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
479   }
480 
481   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
482                            cast<Instruction>(VL[AltIndex]));
483 }
484 
485 /// \returns true if all of the values in \p VL have the same type or false
486 /// otherwise.
487 static bool allSameType(ArrayRef<Value *> VL) {
488   Type *Ty = VL[0]->getType();
489   for (int i = 1, e = VL.size(); i < e; i++)
490     if (VL[i]->getType() != Ty)
491       return false;
492 
493   return true;
494 }
495 
496 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
497 static Optional<unsigned> getExtractIndex(Instruction *E) {
498   unsigned Opcode = E->getOpcode();
499   assert((Opcode == Instruction::ExtractElement ||
500           Opcode == Instruction::ExtractValue) &&
501          "Expected extractelement or extractvalue instruction.");
502   if (Opcode == Instruction::ExtractElement) {
503     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
504     if (!CI)
505       return None;
506     return CI->getZExtValue();
507   }
508   ExtractValueInst *EI = cast<ExtractValueInst>(E);
509   if (EI->getNumIndices() != 1)
510     return None;
511   return *EI->idx_begin();
512 }
513 
514 /// \returns True if in-tree use also needs extract. This refers to
515 /// possible scalar operand in vectorized instruction.
516 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
517                                     TargetLibraryInfo *TLI) {
518   unsigned Opcode = UserInst->getOpcode();
519   switch (Opcode) {
520   case Instruction::Load: {
521     LoadInst *LI = cast<LoadInst>(UserInst);
522     return (LI->getPointerOperand() == Scalar);
523   }
524   case Instruction::Store: {
525     StoreInst *SI = cast<StoreInst>(UserInst);
526     return (SI->getPointerOperand() == Scalar);
527   }
528   case Instruction::Call: {
529     CallInst *CI = cast<CallInst>(UserInst);
530     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
531     for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
532       if (hasVectorInstrinsicScalarOpd(ID, i))
533         return (CI->getArgOperand(i) == Scalar);
534     }
535     LLVM_FALLTHROUGH;
536   }
537   default:
538     return false;
539   }
540 }
541 
542 /// \returns the AA location that is being access by the instruction.
543 static MemoryLocation getLocation(Instruction *I, AAResults *AA) {
544   if (StoreInst *SI = dyn_cast<StoreInst>(I))
545     return MemoryLocation::get(SI);
546   if (LoadInst *LI = dyn_cast<LoadInst>(I))
547     return MemoryLocation::get(LI);
548   return MemoryLocation();
549 }
550 
551 /// \returns True if the instruction is not a volatile or atomic load/store.
552 static bool isSimple(Instruction *I) {
553   if (LoadInst *LI = dyn_cast<LoadInst>(I))
554     return LI->isSimple();
555   if (StoreInst *SI = dyn_cast<StoreInst>(I))
556     return SI->isSimple();
557   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
558     return !MI->isVolatile();
559   return true;
560 }
561 
562 /// Shuffles \p Mask in accordance with the given \p SubMask.
563 static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
564   if (SubMask.empty())
565     return;
566   if (Mask.empty()) {
567     Mask.append(SubMask.begin(), SubMask.end());
568     return;
569   }
570   SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
571   int TermValue = std::min(Mask.size(), SubMask.size());
572   for (int I = 0, E = SubMask.size(); I < E; ++I) {
573     if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
574         Mask[SubMask[I]] >= TermValue)
575       continue;
576     NewMask[I] = Mask[SubMask[I]];
577   }
578   Mask.swap(NewMask);
579 }
580 
581 /// Order may have elements assigned special value (size) which is out of
582 /// bounds. Such indices only appear on places which correspond to undef values
583 /// (see canReuseExtract for details) and used in order to avoid undef values
584 /// have effect on operands ordering.
585 /// The first loop below simply finds all unused indices and then the next loop
586 /// nest assigns these indices for undef values positions.
587 /// As an example below Order has two undef positions and they have assigned
588 /// values 3 and 7 respectively:
589 /// before:  6 9 5 4 9 2 1 0
590 /// after:   6 3 5 4 7 2 1 0
591 /// \returns Fixed ordering.
592 static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
593   const unsigned Sz = Order.size();
594   SmallBitVector UsedIndices(Sz);
595   SmallVector<int> MaskedIndices;
596   for (unsigned I = 0; I < Sz; ++I) {
597     if (Order[I] < Sz)
598       UsedIndices.set(Order[I]);
599     else
600       MaskedIndices.push_back(I);
601   }
602   if (MaskedIndices.empty())
603     return;
604   SmallVector<int> AvailableIndices(MaskedIndices.size());
605   unsigned Cnt = 0;
606   int Idx = UsedIndices.find_first();
607   do {
608     AvailableIndices[Cnt] = Idx;
609     Idx = UsedIndices.find_next(Idx);
610     ++Cnt;
611   } while (Idx > 0);
612   assert(Cnt == MaskedIndices.size() && "Non-synced masked/available indices.");
613   for (int I = 0, E = MaskedIndices.size(); I < E; ++I)
614     Order[MaskedIndices[I]] = AvailableIndices[I];
615 }
616 
617 namespace llvm {
618 
619 static void inversePermutation(ArrayRef<unsigned> Indices,
620                                SmallVectorImpl<int> &Mask) {
621   Mask.clear();
622   const unsigned E = Indices.size();
623   Mask.resize(E, UndefMaskElem);
624   for (unsigned I = 0; I < E; ++I)
625     Mask[Indices[I]] = I;
626 }
627 
628 /// \returns inserting index of InsertElement or InsertValue instruction,
629 /// using Offset as base offset for index.
630 static Optional<int> getInsertIndex(Value *InsertInst, unsigned Offset) {
631   int Index = Offset;
632   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
633     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
634       auto *VT = cast<FixedVectorType>(IE->getType());
635       if (CI->getValue().uge(VT->getNumElements()))
636         return UndefMaskElem;
637       Index *= VT->getNumElements();
638       Index += CI->getZExtValue();
639       return Index;
640     }
641     if (isa<UndefValue>(IE->getOperand(2)))
642       return UndefMaskElem;
643     return None;
644   }
645 
646   auto *IV = cast<InsertValueInst>(InsertInst);
647   Type *CurrentType = IV->getType();
648   for (unsigned I : IV->indices()) {
649     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
650       Index *= ST->getNumElements();
651       CurrentType = ST->getElementType(I);
652     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
653       Index *= AT->getNumElements();
654       CurrentType = AT->getElementType();
655     } else {
656       return None;
657     }
658     Index += I;
659   }
660   return Index;
661 }
662 
663 /// Reorders the list of scalars in accordance with the given \p Order and then
664 /// the \p Mask. \p Order - is the original order of the scalars, need to
665 /// reorder scalars into an unordered state at first according to the given
666 /// order. Then the ordered scalars are shuffled once again in accordance with
667 /// the provided mask.
668 static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
669                            ArrayRef<int> Mask) {
670   assert(!Mask.empty() && "Expected non-empty mask.");
671   SmallVector<Value *> Prev(Scalars.size(),
672                             UndefValue::get(Scalars.front()->getType()));
673   Prev.swap(Scalars);
674   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
675     if (Mask[I] != UndefMaskElem)
676       Scalars[Mask[I]] = Prev[I];
677 }
678 
679 namespace slpvectorizer {
680 
681 /// Bottom Up SLP Vectorizer.
682 class BoUpSLP {
683   struct TreeEntry;
684   struct ScheduleData;
685 
686 public:
687   using ValueList = SmallVector<Value *, 8>;
688   using InstrList = SmallVector<Instruction *, 16>;
689   using ValueSet = SmallPtrSet<Value *, 16>;
690   using StoreList = SmallVector<StoreInst *, 8>;
691   using ExtraValueToDebugLocsMap =
692       MapVector<Value *, SmallVector<Instruction *, 2>>;
693   using OrdersType = SmallVector<unsigned, 4>;
694 
695   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
696           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
697           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
698           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
699       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
700         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
701     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
702     // Use the vector register size specified by the target unless overridden
703     // by a command-line option.
704     // TODO: It would be better to limit the vectorization factor based on
705     //       data type rather than just register size. For example, x86 AVX has
706     //       256-bit registers, but it does not support integer operations
707     //       at that width (that requires AVX2).
708     if (MaxVectorRegSizeOption.getNumOccurrences())
709       MaxVecRegSize = MaxVectorRegSizeOption;
710     else
711       MaxVecRegSize =
712           TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
713               .getFixedSize();
714 
715     if (MinVectorRegSizeOption.getNumOccurrences())
716       MinVecRegSize = MinVectorRegSizeOption;
717     else
718       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
719   }
720 
721   /// Vectorize the tree that starts with the elements in \p VL.
722   /// Returns the vectorized root.
723   Value *vectorizeTree();
724 
725   /// Vectorize the tree but with the list of externally used values \p
726   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
727   /// generated extractvalue instructions.
728   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
729 
730   /// \returns the cost incurred by unwanted spills and fills, caused by
731   /// holding live values over call sites.
732   InstructionCost getSpillCost() const;
733 
734   /// \returns the vectorization cost of the subtree that starts at \p VL.
735   /// A negative number means that this is profitable.
736   InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
737 
738   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
739   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
740   void buildTree(ArrayRef<Value *> Roots,
741                  ArrayRef<Value *> UserIgnoreLst = None);
742 
743   /// Builds external uses of the vectorized scalars, i.e. the list of
744   /// vectorized scalars to be extracted, their lanes and their scalar users. \p
745   /// ExternallyUsedValues contains additional list of external uses to handle
746   /// vectorization of reductions.
747   void
748   buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
749 
750   /// Clear the internal data structures that are created by 'buildTree'.
751   void deleteTree() {
752     VectorizableTree.clear();
753     ScalarToTreeEntry.clear();
754     MustGather.clear();
755     ExternalUses.clear();
756     for (auto &Iter : BlocksSchedules) {
757       BlockScheduling *BS = Iter.second.get();
758       BS->clear();
759     }
760     MinBWs.clear();
761     InstrElementSize.clear();
762   }
763 
764   unsigned getTreeSize() const { return VectorizableTree.size(); }
765 
766   /// Perform LICM and CSE on the newly generated gather sequences.
767   void optimizeGatherSequence();
768 
769   /// Checks if the specified gather tree entry \p TE can be represented as a
770   /// shuffled vector entry + (possibly) permutation with other gathers. It
771   /// implements the checks only for possibly ordered scalars (Loads,
772   /// ExtractElement, ExtractValue), which can be part of the graph.
773   Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
774 
775   /// Reorders the current graph to the most profitable order starting from the
776   /// root node to the leaf nodes. The best order is chosen only from the nodes
777   /// of the same size (vectorization factor). Smaller nodes are considered
778   /// parts of subgraph with smaller VF and they are reordered independently. We
779   /// can make it because we still need to extend smaller nodes to the wider VF
780   /// and we can merge reordering shuffles with the widening shuffles.
781   void reorderTopToBottom();
782 
783   /// Reorders the current graph to the most profitable order starting from
784   /// leaves to the root. It allows to rotate small subgraphs and reduce the
785   /// number of reshuffles if the leaf nodes use the same order. In this case we
786   /// can merge the orders and just shuffle user node instead of shuffling its
787   /// operands. Plus, even the leaf nodes have different orders, it allows to
788   /// sink reordering in the graph closer to the root node and merge it later
789   /// during analysis.
790   void reorderBottomToTop(bool IgnoreReorder = false);
791 
792   /// \return The vector element size in bits to use when vectorizing the
793   /// expression tree ending at \p V. If V is a store, the size is the width of
794   /// the stored value. Otherwise, the size is the width of the largest loaded
795   /// value reaching V. This method is used by the vectorizer to calculate
796   /// vectorization factors.
797   unsigned getVectorElementSize(Value *V);
798 
799   /// Compute the minimum type sizes required to represent the entries in a
800   /// vectorizable tree.
801   void computeMinimumValueSizes();
802 
803   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
804   unsigned getMaxVecRegSize() const {
805     return MaxVecRegSize;
806   }
807 
808   // \returns minimum vector register size as set by cl::opt.
809   unsigned getMinVecRegSize() const {
810     return MinVecRegSize;
811   }
812 
813   unsigned getMinVF(unsigned Sz) const {
814     return std::max(2U, getMinVecRegSize() / Sz);
815   }
816 
817   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
818     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
819       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
820     return MaxVF ? MaxVF : UINT_MAX;
821   }
822 
823   /// Check if homogeneous aggregate is isomorphic to some VectorType.
824   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
825   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
826   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
827   ///
828   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
829   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
830 
831   /// \returns True if the VectorizableTree is both tiny and not fully
832   /// vectorizable. We do not vectorize such trees.
833   bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
834 
835   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
836   /// can be load combined in the backend. Load combining may not be allowed in
837   /// the IR optimizer, so we do not want to alter the pattern. For example,
838   /// partially transforming a scalar bswap() pattern into vector code is
839   /// effectively impossible for the backend to undo.
840   /// TODO: If load combining is allowed in the IR optimizer, this analysis
841   ///       may not be necessary.
842   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
843 
844   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
845   /// can be load combined in the backend. Load combining may not be allowed in
846   /// the IR optimizer, so we do not want to alter the pattern. For example,
847   /// partially transforming a scalar bswap() pattern into vector code is
848   /// effectively impossible for the backend to undo.
849   /// TODO: If load combining is allowed in the IR optimizer, this analysis
850   ///       may not be necessary.
851   bool isLoadCombineCandidate() const;
852 
853   OptimizationRemarkEmitter *getORE() { return ORE; }
854 
855   /// This structure holds any data we need about the edges being traversed
856   /// during buildTree_rec(). We keep track of:
857   /// (i) the user TreeEntry index, and
858   /// (ii) the index of the edge.
859   struct EdgeInfo {
860     EdgeInfo() = default;
861     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
862         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
863     /// The user TreeEntry.
864     TreeEntry *UserTE = nullptr;
865     /// The operand index of the use.
866     unsigned EdgeIdx = UINT_MAX;
867 #ifndef NDEBUG
868     friend inline raw_ostream &operator<<(raw_ostream &OS,
869                                           const BoUpSLP::EdgeInfo &EI) {
870       EI.dump(OS);
871       return OS;
872     }
873     /// Debug print.
874     void dump(raw_ostream &OS) const {
875       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
876          << " EdgeIdx:" << EdgeIdx << "}";
877     }
878     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
879 #endif
880   };
881 
882   /// A helper data structure to hold the operands of a vector of instructions.
883   /// This supports a fixed vector length for all operand vectors.
884   class VLOperands {
885     /// For each operand we need (i) the value, and (ii) the opcode that it
886     /// would be attached to if the expression was in a left-linearized form.
887     /// This is required to avoid illegal operand reordering.
888     /// For example:
889     /// \verbatim
890     ///                         0 Op1
891     ///                         |/
892     /// Op1 Op2   Linearized    + Op2
893     ///   \ /     ---------->   |/
894     ///    -                    -
895     ///
896     /// Op1 - Op2            (0 + Op1) - Op2
897     /// \endverbatim
898     ///
899     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
900     ///
901     /// Another way to think of this is to track all the operations across the
902     /// path from the operand all the way to the root of the tree and to
903     /// calculate the operation that corresponds to this path. For example, the
904     /// path from Op2 to the root crosses the RHS of the '-', therefore the
905     /// corresponding operation is a '-' (which matches the one in the
906     /// linearized tree, as shown above).
907     ///
908     /// For lack of a better term, we refer to this operation as Accumulated
909     /// Path Operation (APO).
910     struct OperandData {
911       OperandData() = default;
912       OperandData(Value *V, bool APO, bool IsUsed)
913           : V(V), APO(APO), IsUsed(IsUsed) {}
914       /// The operand value.
915       Value *V = nullptr;
916       /// TreeEntries only allow a single opcode, or an alternate sequence of
917       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
918       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
919       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
920       /// (e.g., Add/Mul)
921       bool APO = false;
922       /// Helper data for the reordering function.
923       bool IsUsed = false;
924     };
925 
926     /// During operand reordering, we are trying to select the operand at lane
927     /// that matches best with the operand at the neighboring lane. Our
928     /// selection is based on the type of value we are looking for. For example,
929     /// if the neighboring lane has a load, we need to look for a load that is
930     /// accessing a consecutive address. These strategies are summarized in the
931     /// 'ReorderingMode' enumerator.
932     enum class ReorderingMode {
933       Load,     ///< Matching loads to consecutive memory addresses
934       Opcode,   ///< Matching instructions based on opcode (same or alternate)
935       Constant, ///< Matching constants
936       Splat,    ///< Matching the same instruction multiple times (broadcast)
937       Failed,   ///< We failed to create a vectorizable group
938     };
939 
940     using OperandDataVec = SmallVector<OperandData, 2>;
941 
942     /// A vector of operand vectors.
943     SmallVector<OperandDataVec, 4> OpsVec;
944 
945     const DataLayout &DL;
946     ScalarEvolution &SE;
947     const BoUpSLP &R;
948 
949     /// \returns the operand data at \p OpIdx and \p Lane.
950     OperandData &getData(unsigned OpIdx, unsigned Lane) {
951       return OpsVec[OpIdx][Lane];
952     }
953 
954     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
955     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
956       return OpsVec[OpIdx][Lane];
957     }
958 
959     /// Clears the used flag for all entries.
960     void clearUsed() {
961       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
962            OpIdx != NumOperands; ++OpIdx)
963         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
964              ++Lane)
965           OpsVec[OpIdx][Lane].IsUsed = false;
966     }
967 
968     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
969     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
970       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
971     }
972 
973     // The hard-coded scores listed here are not very important. When computing
974     // the scores of matching one sub-tree with another, we are basically
975     // counting the number of values that are matching. So even if all scores
976     // are set to 1, we would still get a decent matching result.
977     // However, sometimes we have to break ties. For example we may have to
978     // choose between matching loads vs matching opcodes. This is what these
979     // scores are helping us with: they provide the order of preference.
980 
981     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
982     static const int ScoreConsecutiveLoads = 3;
983     /// ExtractElementInst from same vector and consecutive indexes.
984     static const int ScoreConsecutiveExtracts = 3;
985     /// Constants.
986     static const int ScoreConstants = 2;
987     /// Instructions with the same opcode.
988     static const int ScoreSameOpcode = 2;
989     /// Instructions with alt opcodes (e.g, add + sub).
990     static const int ScoreAltOpcodes = 1;
991     /// Identical instructions (a.k.a. splat or broadcast).
992     static const int ScoreSplat = 1;
993     /// Matching with an undef is preferable to failing.
994     static const int ScoreUndef = 1;
995     /// Score for failing to find a decent match.
996     static const int ScoreFail = 0;
997     /// User exteranl to the vectorized code.
998     static const int ExternalUseCost = 1;
999     /// The user is internal but in a different lane.
1000     static const int UserInDiffLaneCost = ExternalUseCost;
1001 
1002     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1003     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
1004                                ScalarEvolution &SE) {
1005       auto *LI1 = dyn_cast<LoadInst>(V1);
1006       auto *LI2 = dyn_cast<LoadInst>(V2);
1007       if (LI1 && LI2) {
1008         if (LI1->getParent() != LI2->getParent())
1009           return VLOperands::ScoreFail;
1010 
1011         Optional<int> Dist = getPointersDiff(
1012             LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1013             LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1014         return (Dist && *Dist == 1) ? VLOperands::ScoreConsecutiveLoads
1015                                     : VLOperands::ScoreFail;
1016       }
1017 
1018       auto *C1 = dyn_cast<Constant>(V1);
1019       auto *C2 = dyn_cast<Constant>(V2);
1020       if (C1 && C2)
1021         return VLOperands::ScoreConstants;
1022 
1023       // Extracts from consecutive indexes of the same vector better score as
1024       // the extracts could be optimized away.
1025       Value *EV;
1026       ConstantInt *Ex1Idx, *Ex2Idx;
1027       if (match(V1, m_ExtractElt(m_Value(EV), m_ConstantInt(Ex1Idx))) &&
1028           match(V2, m_ExtractElt(m_Deferred(EV), m_ConstantInt(Ex2Idx))) &&
1029           Ex1Idx->getZExtValue() + 1 == Ex2Idx->getZExtValue())
1030         return VLOperands::ScoreConsecutiveExtracts;
1031 
1032       auto *I1 = dyn_cast<Instruction>(V1);
1033       auto *I2 = dyn_cast<Instruction>(V2);
1034       if (I1 && I2) {
1035         if (I1 == I2)
1036           return VLOperands::ScoreSplat;
1037         InstructionsState S = getSameOpcode({I1, I2});
1038         // Note: Only consider instructions with <= 2 operands to avoid
1039         // complexity explosion.
1040         if (S.getOpcode() && S.MainOp->getNumOperands() <= 2)
1041           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
1042                                   : VLOperands::ScoreSameOpcode;
1043       }
1044 
1045       if (isa<UndefValue>(V2))
1046         return VLOperands::ScoreUndef;
1047 
1048       return VLOperands::ScoreFail;
1049     }
1050 
1051     /// Holds the values and their lane that are taking part in the look-ahead
1052     /// score calculation. This is used in the external uses cost calculation.
1053     SmallDenseMap<Value *, int> InLookAheadValues;
1054 
1055     /// \Returns the additinal cost due to uses of \p LHS and \p RHS that are
1056     /// either external to the vectorized code, or require shuffling.
1057     int getExternalUsesCost(const std::pair<Value *, int> &LHS,
1058                             const std::pair<Value *, int> &RHS) {
1059       int Cost = 0;
1060       std::array<std::pair<Value *, int>, 2> Values = {{LHS, RHS}};
1061       for (int Idx = 0, IdxE = Values.size(); Idx != IdxE; ++Idx) {
1062         Value *V = Values[Idx].first;
1063         if (isa<Constant>(V)) {
1064           // Since this is a function pass, it doesn't make semantic sense to
1065           // walk the users of a subclass of Constant. The users could be in
1066           // another function, or even another module that happens to be in
1067           // the same LLVMContext.
1068           continue;
1069         }
1070 
1071         // Calculate the absolute lane, using the minimum relative lane of LHS
1072         // and RHS as base and Idx as the offset.
1073         int Ln = std::min(LHS.second, RHS.second) + Idx;
1074         assert(Ln >= 0 && "Bad lane calculation");
1075         unsigned UsersBudget = LookAheadUsersBudget;
1076         for (User *U : V->users()) {
1077           if (const TreeEntry *UserTE = R.getTreeEntry(U)) {
1078             // The user is in the VectorizableTree. Check if we need to insert.
1079             auto It = llvm::find(UserTE->Scalars, U);
1080             assert(It != UserTE->Scalars.end() && "U is in UserTE");
1081             int UserLn = std::distance(UserTE->Scalars.begin(), It);
1082             assert(UserLn >= 0 && "Bad lane");
1083             if (UserLn != Ln)
1084               Cost += UserInDiffLaneCost;
1085           } else {
1086             // Check if the user is in the look-ahead code.
1087             auto It2 = InLookAheadValues.find(U);
1088             if (It2 != InLookAheadValues.end()) {
1089               // The user is in the look-ahead code. Check the lane.
1090               if (It2->second != Ln)
1091                 Cost += UserInDiffLaneCost;
1092             } else {
1093               // The user is neither in SLP tree nor in the look-ahead code.
1094               Cost += ExternalUseCost;
1095             }
1096           }
1097           // Limit the number of visited uses to cap compilation time.
1098           if (--UsersBudget == 0)
1099             break;
1100         }
1101       }
1102       return Cost;
1103     }
1104 
1105     /// Go through the operands of \p LHS and \p RHS recursively until \p
1106     /// MaxLevel, and return the cummulative score. For example:
1107     /// \verbatim
1108     ///  A[0]  B[0]  A[1]  B[1]  C[0] D[0]  B[1] A[1]
1109     ///     \ /         \ /         \ /        \ /
1110     ///      +           +           +          +
1111     ///     G1          G2          G3         G4
1112     /// \endverbatim
1113     /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1114     /// each level recursively, accumulating the score. It starts from matching
1115     /// the additions at level 0, then moves on to the loads (level 1). The
1116     /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1117     /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
1118     /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
1119     /// Please note that the order of the operands does not matter, as we
1120     /// evaluate the score of all profitable combinations of operands. In
1121     /// other words the score of G1 and G4 is the same as G1 and G2. This
1122     /// heuristic is based on ideas described in:
1123     ///   Look-ahead SLP: Auto-vectorization in the presence of commutative
1124     ///   operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1125     ///   Luís F. W. Góes
1126     int getScoreAtLevelRec(const std::pair<Value *, int> &LHS,
1127                            const std::pair<Value *, int> &RHS, int CurrLevel,
1128                            int MaxLevel) {
1129 
1130       Value *V1 = LHS.first;
1131       Value *V2 = RHS.first;
1132       // Get the shallow score of V1 and V2.
1133       int ShallowScoreAtThisLevel =
1134           std::max((int)ScoreFail, getShallowScore(V1, V2, DL, SE) -
1135                                        getExternalUsesCost(LHS, RHS));
1136       int Lane1 = LHS.second;
1137       int Lane2 = RHS.second;
1138 
1139       // If reached MaxLevel,
1140       //  or if V1 and V2 are not instructions,
1141       //  or if they are SPLAT,
1142       //  or if they are not consecutive, early return the current cost.
1143       auto *I1 = dyn_cast<Instruction>(V1);
1144       auto *I2 = dyn_cast<Instruction>(V2);
1145       if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1146           ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
1147           (isa<LoadInst>(I1) && isa<LoadInst>(I2) && ShallowScoreAtThisLevel))
1148         return ShallowScoreAtThisLevel;
1149       assert(I1 && I2 && "Should have early exited.");
1150 
1151       // Keep track of in-tree values for determining the external-use cost.
1152       InLookAheadValues[V1] = Lane1;
1153       InLookAheadValues[V2] = Lane2;
1154 
1155       // Contains the I2 operand indexes that got matched with I1 operands.
1156       SmallSet<unsigned, 4> Op2Used;
1157 
1158       // Recursion towards the operands of I1 and I2. We are trying all possbile
1159       // operand pairs, and keeping track of the best score.
1160       for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1161            OpIdx1 != NumOperands1; ++OpIdx1) {
1162         // Try to pair op1I with the best operand of I2.
1163         int MaxTmpScore = 0;
1164         unsigned MaxOpIdx2 = 0;
1165         bool FoundBest = false;
1166         // If I2 is commutative try all combinations.
1167         unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1168         unsigned ToIdx = isCommutative(I2)
1169                              ? I2->getNumOperands()
1170                              : std::min(I2->getNumOperands(), OpIdx1 + 1);
1171         assert(FromIdx <= ToIdx && "Bad index");
1172         for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1173           // Skip operands already paired with OpIdx1.
1174           if (Op2Used.count(OpIdx2))
1175             continue;
1176           // Recursively calculate the cost at each level
1177           int TmpScore = getScoreAtLevelRec({I1->getOperand(OpIdx1), Lane1},
1178                                             {I2->getOperand(OpIdx2), Lane2},
1179                                             CurrLevel + 1, MaxLevel);
1180           // Look for the best score.
1181           if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
1182             MaxTmpScore = TmpScore;
1183             MaxOpIdx2 = OpIdx2;
1184             FoundBest = true;
1185           }
1186         }
1187         if (FoundBest) {
1188           // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1189           Op2Used.insert(MaxOpIdx2);
1190           ShallowScoreAtThisLevel += MaxTmpScore;
1191         }
1192       }
1193       return ShallowScoreAtThisLevel;
1194     }
1195 
1196     /// \Returns the look-ahead score, which tells us how much the sub-trees
1197     /// rooted at \p LHS and \p RHS match, the more they match the higher the
1198     /// score. This helps break ties in an informed way when we cannot decide on
1199     /// the order of the operands by just considering the immediate
1200     /// predecessors.
1201     int getLookAheadScore(const std::pair<Value *, int> &LHS,
1202                           const std::pair<Value *, int> &RHS) {
1203       InLookAheadValues.clear();
1204       return getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth);
1205     }
1206 
1207     // Search all operands in Ops[*][Lane] for the one that matches best
1208     // Ops[OpIdx][LastLane] and return its opreand index.
1209     // If no good match can be found, return None.
1210     Optional<unsigned>
1211     getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1212                    ArrayRef<ReorderingMode> ReorderingModes) {
1213       unsigned NumOperands = getNumOperands();
1214 
1215       // The operand of the previous lane at OpIdx.
1216       Value *OpLastLane = getData(OpIdx, LastLane).V;
1217 
1218       // Our strategy mode for OpIdx.
1219       ReorderingMode RMode = ReorderingModes[OpIdx];
1220 
1221       // The linearized opcode of the operand at OpIdx, Lane.
1222       bool OpIdxAPO = getData(OpIdx, Lane).APO;
1223 
1224       // The best operand index and its score.
1225       // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1226       // are using the score to differentiate between the two.
1227       struct BestOpData {
1228         Optional<unsigned> Idx = None;
1229         unsigned Score = 0;
1230       } BestOp;
1231 
1232       // Iterate through all unused operands and look for the best.
1233       for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1234         // Get the operand at Idx and Lane.
1235         OperandData &OpData = getData(Idx, Lane);
1236         Value *Op = OpData.V;
1237         bool OpAPO = OpData.APO;
1238 
1239         // Skip already selected operands.
1240         if (OpData.IsUsed)
1241           continue;
1242 
1243         // Skip if we are trying to move the operand to a position with a
1244         // different opcode in the linearized tree form. This would break the
1245         // semantics.
1246         if (OpAPO != OpIdxAPO)
1247           continue;
1248 
1249         // Look for an operand that matches the current mode.
1250         switch (RMode) {
1251         case ReorderingMode::Load:
1252         case ReorderingMode::Constant:
1253         case ReorderingMode::Opcode: {
1254           bool LeftToRight = Lane > LastLane;
1255           Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1256           Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1257           unsigned Score =
1258               getLookAheadScore({OpLeft, LastLane}, {OpRight, Lane});
1259           if (Score > BestOp.Score) {
1260             BestOp.Idx = Idx;
1261             BestOp.Score = Score;
1262           }
1263           break;
1264         }
1265         case ReorderingMode::Splat:
1266           if (Op == OpLastLane)
1267             BestOp.Idx = Idx;
1268           break;
1269         case ReorderingMode::Failed:
1270           return None;
1271         }
1272       }
1273 
1274       if (BestOp.Idx) {
1275         getData(BestOp.Idx.getValue(), Lane).IsUsed = true;
1276         return BestOp.Idx;
1277       }
1278       // If we could not find a good match return None.
1279       return None;
1280     }
1281 
1282     /// Helper for reorderOperandVecs. \Returns the lane that we should start
1283     /// reordering from. This is the one which has the least number of operands
1284     /// that can freely move about.
1285     unsigned getBestLaneToStartReordering() const {
1286       unsigned BestLane = 0;
1287       unsigned Min = UINT_MAX;
1288       for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1289            ++Lane) {
1290         unsigned NumFreeOps = getMaxNumOperandsThatCanBeReordered(Lane);
1291         if (NumFreeOps < Min) {
1292           Min = NumFreeOps;
1293           BestLane = Lane;
1294         }
1295       }
1296       return BestLane;
1297     }
1298 
1299     /// \Returns the maximum number of operands that are allowed to be reordered
1300     /// for \p Lane. This is used as a heuristic for selecting the first lane to
1301     /// start operand reordering.
1302     unsigned getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1303       unsigned CntTrue = 0;
1304       unsigned NumOperands = getNumOperands();
1305       // Operands with the same APO can be reordered. We therefore need to count
1306       // how many of them we have for each APO, like this: Cnt[APO] = x.
1307       // Since we only have two APOs, namely true and false, we can avoid using
1308       // a map. Instead we can simply count the number of operands that
1309       // correspond to one of them (in this case the 'true' APO), and calculate
1310       // the other by subtracting it from the total number of operands.
1311       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx)
1312         if (getData(OpIdx, Lane).APO)
1313           ++CntTrue;
1314       unsigned CntFalse = NumOperands - CntTrue;
1315       return std::max(CntTrue, CntFalse);
1316     }
1317 
1318     /// Go through the instructions in VL and append their operands.
1319     void appendOperandsOfVL(ArrayRef<Value *> VL) {
1320       assert(!VL.empty() && "Bad VL");
1321       assert((empty() || VL.size() == getNumLanes()) &&
1322              "Expected same number of lanes");
1323       assert(isa<Instruction>(VL[0]) && "Expected instruction");
1324       unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1325       OpsVec.resize(NumOperands);
1326       unsigned NumLanes = VL.size();
1327       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1328         OpsVec[OpIdx].resize(NumLanes);
1329         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1330           assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1331           // Our tree has just 3 nodes: the root and two operands.
1332           // It is therefore trivial to get the APO. We only need to check the
1333           // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1334           // RHS operand. The LHS operand of both add and sub is never attached
1335           // to an inversese operation in the linearized form, therefore its APO
1336           // is false. The RHS is true only if VL[Lane] is an inverse operation.
1337 
1338           // Since operand reordering is performed on groups of commutative
1339           // operations or alternating sequences (e.g., +, -), we can safely
1340           // tell the inverse operations by checking commutativity.
1341           bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1342           bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1343           OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1344                                  APO, false};
1345         }
1346       }
1347     }
1348 
1349     /// \returns the number of operands.
1350     unsigned getNumOperands() const { return OpsVec.size(); }
1351 
1352     /// \returns the number of lanes.
1353     unsigned getNumLanes() const { return OpsVec[0].size(); }
1354 
1355     /// \returns the operand value at \p OpIdx and \p Lane.
1356     Value *getValue(unsigned OpIdx, unsigned Lane) const {
1357       return getData(OpIdx, Lane).V;
1358     }
1359 
1360     /// \returns true if the data structure is empty.
1361     bool empty() const { return OpsVec.empty(); }
1362 
1363     /// Clears the data.
1364     void clear() { OpsVec.clear(); }
1365 
1366     /// \Returns true if there are enough operands identical to \p Op to fill
1367     /// the whole vector.
1368     /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1369     bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1370       bool OpAPO = getData(OpIdx, Lane).APO;
1371       for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1372         if (Ln == Lane)
1373           continue;
1374         // This is set to true if we found a candidate for broadcast at Lane.
1375         bool FoundCandidate = false;
1376         for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1377           OperandData &Data = getData(OpI, Ln);
1378           if (Data.APO != OpAPO || Data.IsUsed)
1379             continue;
1380           if (Data.V == Op) {
1381             FoundCandidate = true;
1382             Data.IsUsed = true;
1383             break;
1384           }
1385         }
1386         if (!FoundCandidate)
1387           return false;
1388       }
1389       return true;
1390     }
1391 
1392   public:
1393     /// Initialize with all the operands of the instruction vector \p RootVL.
1394     VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
1395                ScalarEvolution &SE, const BoUpSLP &R)
1396         : DL(DL), SE(SE), R(R) {
1397       // Append all the operands of RootVL.
1398       appendOperandsOfVL(RootVL);
1399     }
1400 
1401     /// \Returns a value vector with the operands across all lanes for the
1402     /// opearnd at \p OpIdx.
1403     ValueList getVL(unsigned OpIdx) const {
1404       ValueList OpVL(OpsVec[OpIdx].size());
1405       assert(OpsVec[OpIdx].size() == getNumLanes() &&
1406              "Expected same num of lanes across all operands");
1407       for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1408         OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1409       return OpVL;
1410     }
1411 
1412     // Performs operand reordering for 2 or more operands.
1413     // The original operands are in OrigOps[OpIdx][Lane].
1414     // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1415     void reorder() {
1416       unsigned NumOperands = getNumOperands();
1417       unsigned NumLanes = getNumLanes();
1418       // Each operand has its own mode. We are using this mode to help us select
1419       // the instructions for each lane, so that they match best with the ones
1420       // we have selected so far.
1421       SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1422 
1423       // This is a greedy single-pass algorithm. We are going over each lane
1424       // once and deciding on the best order right away with no back-tracking.
1425       // However, in order to increase its effectiveness, we start with the lane
1426       // that has operands that can move the least. For example, given the
1427       // following lanes:
1428       //  Lane 0 : A[0] = B[0] + C[0]   // Visited 3rd
1429       //  Lane 1 : A[1] = C[1] - B[1]   // Visited 1st
1430       //  Lane 2 : A[2] = B[2] + C[2]   // Visited 2nd
1431       //  Lane 3 : A[3] = C[3] - B[3]   // Visited 4th
1432       // we will start at Lane 1, since the operands of the subtraction cannot
1433       // be reordered. Then we will visit the rest of the lanes in a circular
1434       // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
1435 
1436       // Find the first lane that we will start our search from.
1437       unsigned FirstLane = getBestLaneToStartReordering();
1438 
1439       // Initialize the modes.
1440       for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1441         Value *OpLane0 = getValue(OpIdx, FirstLane);
1442         // Keep track if we have instructions with all the same opcode on one
1443         // side.
1444         if (isa<LoadInst>(OpLane0))
1445           ReorderingModes[OpIdx] = ReorderingMode::Load;
1446         else if (isa<Instruction>(OpLane0)) {
1447           // Check if OpLane0 should be broadcast.
1448           if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
1449             ReorderingModes[OpIdx] = ReorderingMode::Splat;
1450           else
1451             ReorderingModes[OpIdx] = ReorderingMode::Opcode;
1452         }
1453         else if (isa<Constant>(OpLane0))
1454           ReorderingModes[OpIdx] = ReorderingMode::Constant;
1455         else if (isa<Argument>(OpLane0))
1456           // Our best hope is a Splat. It may save some cost in some cases.
1457           ReorderingModes[OpIdx] = ReorderingMode::Splat;
1458         else
1459           // NOTE: This should be unreachable.
1460           ReorderingModes[OpIdx] = ReorderingMode::Failed;
1461       }
1462 
1463       // If the initial strategy fails for any of the operand indexes, then we
1464       // perform reordering again in a second pass. This helps avoid assigning
1465       // high priority to the failed strategy, and should improve reordering for
1466       // the non-failed operand indexes.
1467       for (int Pass = 0; Pass != 2; ++Pass) {
1468         // Skip the second pass if the first pass did not fail.
1469         bool StrategyFailed = false;
1470         // Mark all operand data as free to use.
1471         clearUsed();
1472         // We keep the original operand order for the FirstLane, so reorder the
1473         // rest of the lanes. We are visiting the nodes in a circular fashion,
1474         // using FirstLane as the center point and increasing the radius
1475         // distance.
1476         for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
1477           // Visit the lane on the right and then the lane on the left.
1478           for (int Direction : {+1, -1}) {
1479             int Lane = FirstLane + Direction * Distance;
1480             if (Lane < 0 || Lane >= (int)NumLanes)
1481               continue;
1482             int LastLane = Lane - Direction;
1483             assert(LastLane >= 0 && LastLane < (int)NumLanes &&
1484                    "Out of bounds");
1485             // Look for a good match for each operand.
1486             for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1487               // Search for the operand that matches SortedOps[OpIdx][Lane-1].
1488               Optional<unsigned> BestIdx =
1489                   getBestOperand(OpIdx, Lane, LastLane, ReorderingModes);
1490               // By not selecting a value, we allow the operands that follow to
1491               // select a better matching value. We will get a non-null value in
1492               // the next run of getBestOperand().
1493               if (BestIdx) {
1494                 // Swap the current operand with the one returned by
1495                 // getBestOperand().
1496                 swap(OpIdx, BestIdx.getValue(), Lane);
1497               } else {
1498                 // We failed to find a best operand, set mode to 'Failed'.
1499                 ReorderingModes[OpIdx] = ReorderingMode::Failed;
1500                 // Enable the second pass.
1501                 StrategyFailed = true;
1502               }
1503             }
1504           }
1505         }
1506         // Skip second pass if the strategy did not fail.
1507         if (!StrategyFailed)
1508           break;
1509       }
1510     }
1511 
1512 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1513     LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
1514       switch (RMode) {
1515       case ReorderingMode::Load:
1516         return "Load";
1517       case ReorderingMode::Opcode:
1518         return "Opcode";
1519       case ReorderingMode::Constant:
1520         return "Constant";
1521       case ReorderingMode::Splat:
1522         return "Splat";
1523       case ReorderingMode::Failed:
1524         return "Failed";
1525       }
1526       llvm_unreachable("Unimplemented Reordering Type");
1527     }
1528 
1529     LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
1530                                                    raw_ostream &OS) {
1531       return OS << getModeStr(RMode);
1532     }
1533 
1534     /// Debug print.
1535     LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
1536       printMode(RMode, dbgs());
1537     }
1538 
1539     friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
1540       return printMode(RMode, OS);
1541     }
1542 
1543     LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
1544       const unsigned Indent = 2;
1545       unsigned Cnt = 0;
1546       for (const OperandDataVec &OpDataVec : OpsVec) {
1547         OS << "Operand " << Cnt++ << "\n";
1548         for (const OperandData &OpData : OpDataVec) {
1549           OS.indent(Indent) << "{";
1550           if (Value *V = OpData.V)
1551             OS << *V;
1552           else
1553             OS << "null";
1554           OS << ", APO:" << OpData.APO << "}\n";
1555         }
1556         OS << "\n";
1557       }
1558       return OS;
1559     }
1560 
1561     /// Debug print.
1562     LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
1563 #endif
1564   };
1565 
1566   /// Checks if the instruction is marked for deletion.
1567   bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
1568 
1569   /// Marks values operands for later deletion by replacing them with Undefs.
1570   void eraseInstructions(ArrayRef<Value *> AV);
1571 
1572   ~BoUpSLP();
1573 
1574 private:
1575   /// Checks if all users of \p I are the part of the vectorization tree.
1576   bool areAllUsersVectorized(Instruction *I,
1577                              ArrayRef<Value *> VectorizedVals) const;
1578 
1579   /// \returns the cost of the vectorizable entry.
1580   InstructionCost getEntryCost(const TreeEntry *E,
1581                                ArrayRef<Value *> VectorizedVals);
1582 
1583   /// This is the recursive part of buildTree.
1584   void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
1585                      const EdgeInfo &EI);
1586 
1587   /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
1588   /// be vectorized to use the original vector (or aggregate "bitcast" to a
1589   /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
1590   /// returns false, setting \p CurrentOrder to either an empty vector or a
1591   /// non-identity permutation that allows to reuse extract instructions.
1592   bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
1593                        SmallVectorImpl<unsigned> &CurrentOrder) const;
1594 
1595   /// Vectorize a single entry in the tree.
1596   Value *vectorizeTree(TreeEntry *E);
1597 
1598   /// Vectorize a single entry in the tree, starting in \p VL.
1599   Value *vectorizeTree(ArrayRef<Value *> VL);
1600 
1601   /// \returns the scalarization cost for this type. Scalarization in this
1602   /// context means the creation of vectors from a group of scalars.
1603   InstructionCost
1604   getGatherCost(FixedVectorType *Ty,
1605                 const DenseSet<unsigned> &ShuffledIndices) const;
1606 
1607   /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
1608   /// tree entries.
1609   /// \returns ShuffleKind, if gathered values can be represented as shuffles of
1610   /// previous tree entries. \p Mask is filled with the shuffle mask.
1611   Optional<TargetTransformInfo::ShuffleKind>
1612   isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
1613                         SmallVectorImpl<const TreeEntry *> &Entries);
1614 
1615   /// \returns the scalarization cost for this list of values. Assuming that
1616   /// this subtree gets vectorized, we may need to extract the values from the
1617   /// roots. This method calculates the cost of extracting the values.
1618   InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
1619 
1620   /// Set the Builder insert point to one after the last instruction in
1621   /// the bundle
1622   void setInsertPointAfterBundle(const TreeEntry *E);
1623 
1624   /// \returns a vector from a collection of scalars in \p VL.
1625   Value *gather(ArrayRef<Value *> VL);
1626 
1627   /// \returns whether the VectorizableTree is fully vectorizable and will
1628   /// be beneficial even the tree height is tiny.
1629   bool isFullyVectorizableTinyTree(bool ForReduction) const;
1630 
1631   /// Reorder commutative or alt operands to get better probability of
1632   /// generating vectorized code.
1633   static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
1634                                              SmallVectorImpl<Value *> &Left,
1635                                              SmallVectorImpl<Value *> &Right,
1636                                              const DataLayout &DL,
1637                                              ScalarEvolution &SE,
1638                                              const BoUpSLP &R);
1639   struct TreeEntry {
1640     using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
1641     TreeEntry(VecTreeTy &Container) : Container(Container) {}
1642 
1643     /// \returns true if the scalars in VL are equal to this entry.
1644     bool isSame(ArrayRef<Value *> VL) const {
1645       auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
1646         if (Mask.size() != VL.size() && VL.size() == Scalars.size())
1647           return std::equal(VL.begin(), VL.end(), Scalars.begin());
1648         return VL.size() == Mask.size() &&
1649                std::equal(VL.begin(), VL.end(), Mask.begin(),
1650                           [Scalars](Value *V, int Idx) {
1651                             return (isa<UndefValue>(V) &&
1652                                     Idx == UndefMaskElem) ||
1653                                    (Idx != UndefMaskElem && V == Scalars[Idx]);
1654                           });
1655       };
1656       if (!ReorderIndices.empty()) {
1657         // TODO: implement matching if the nodes are just reordered, still can
1658         // treat the vector as the same if the list of scalars matches VL
1659         // directly, without reordering.
1660         SmallVector<int> Mask;
1661         inversePermutation(ReorderIndices, Mask);
1662         if (VL.size() == Scalars.size())
1663           return IsSame(Scalars, Mask);
1664         if (VL.size() == ReuseShuffleIndices.size()) {
1665           ::addMask(Mask, ReuseShuffleIndices);
1666           return IsSame(Scalars, Mask);
1667         }
1668         return false;
1669       }
1670       return IsSame(Scalars, ReuseShuffleIndices);
1671     }
1672 
1673     /// A vector of scalars.
1674     ValueList Scalars;
1675 
1676     /// The Scalars are vectorized into this value. It is initialized to Null.
1677     Value *VectorizedValue = nullptr;
1678 
1679     /// Do we need to gather this sequence or vectorize it
1680     /// (either with vector instruction or with scatter/gather
1681     /// intrinsics for store/load)?
1682     enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
1683     EntryState State;
1684 
1685     /// Does this sequence require some shuffling?
1686     SmallVector<int, 4> ReuseShuffleIndices;
1687 
1688     /// Does this entry require reordering?
1689     SmallVector<unsigned, 4> ReorderIndices;
1690 
1691     /// Points back to the VectorizableTree.
1692     ///
1693     /// Only used for Graphviz right now.  Unfortunately GraphTrait::NodeRef has
1694     /// to be a pointer and needs to be able to initialize the child iterator.
1695     /// Thus we need a reference back to the container to translate the indices
1696     /// to entries.
1697     VecTreeTy &Container;
1698 
1699     /// The TreeEntry index containing the user of this entry.  We can actually
1700     /// have multiple users so the data structure is not truly a tree.
1701     SmallVector<EdgeInfo, 1> UserTreeIndices;
1702 
1703     /// The index of this treeEntry in VectorizableTree.
1704     int Idx = -1;
1705 
1706   private:
1707     /// The operands of each instruction in each lane Operands[op_index][lane].
1708     /// Note: This helps avoid the replication of the code that performs the
1709     /// reordering of operands during buildTree_rec() and vectorizeTree().
1710     SmallVector<ValueList, 2> Operands;
1711 
1712     /// The main/alternate instruction.
1713     Instruction *MainOp = nullptr;
1714     Instruction *AltOp = nullptr;
1715 
1716   public:
1717     /// Set this bundle's \p OpIdx'th operand to \p OpVL.
1718     void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
1719       if (Operands.size() < OpIdx + 1)
1720         Operands.resize(OpIdx + 1);
1721       assert(Operands[OpIdx].empty() && "Already resized?");
1722       Operands[OpIdx].resize(Scalars.size());
1723       for (unsigned Lane = 0, E = Scalars.size(); Lane != E; ++Lane)
1724         Operands[OpIdx][Lane] = OpVL[Lane];
1725     }
1726 
1727     /// Set the operands of this bundle in their original order.
1728     void setOperandsInOrder() {
1729       assert(Operands.empty() && "Already initialized?");
1730       auto *I0 = cast<Instruction>(Scalars[0]);
1731       Operands.resize(I0->getNumOperands());
1732       unsigned NumLanes = Scalars.size();
1733       for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
1734            OpIdx != NumOperands; ++OpIdx) {
1735         Operands[OpIdx].resize(NumLanes);
1736         for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1737           auto *I = cast<Instruction>(Scalars[Lane]);
1738           assert(I->getNumOperands() == NumOperands &&
1739                  "Expected same number of operands");
1740           Operands[OpIdx][Lane] = I->getOperand(OpIdx);
1741         }
1742       }
1743     }
1744 
1745     /// Reorders operands of the node to the given mask \p Mask.
1746     void reorderOperands(ArrayRef<int> Mask) {
1747       for (ValueList &Operand : Operands)
1748         reorderScalars(Operand, Mask);
1749     }
1750 
1751     /// \returns the \p OpIdx operand of this TreeEntry.
1752     ValueList &getOperand(unsigned OpIdx) {
1753       assert(OpIdx < Operands.size() && "Off bounds");
1754       return Operands[OpIdx];
1755     }
1756 
1757     /// \returns the number of operands.
1758     unsigned getNumOperands() const { return Operands.size(); }
1759 
1760     /// \return the single \p OpIdx operand.
1761     Value *getSingleOperand(unsigned OpIdx) const {
1762       assert(OpIdx < Operands.size() && "Off bounds");
1763       assert(!Operands[OpIdx].empty() && "No operand available");
1764       return Operands[OpIdx][0];
1765     }
1766 
1767     /// Some of the instructions in the list have alternate opcodes.
1768     bool isAltShuffle() const {
1769       return getOpcode() != getAltOpcode();
1770     }
1771 
1772     bool isOpcodeOrAlt(Instruction *I) const {
1773       unsigned CheckedOpcode = I->getOpcode();
1774       return (getOpcode() == CheckedOpcode ||
1775               getAltOpcode() == CheckedOpcode);
1776     }
1777 
1778     /// Chooses the correct key for scheduling data. If \p Op has the same (or
1779     /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
1780     /// \p OpValue.
1781     Value *isOneOf(Value *Op) const {
1782       auto *I = dyn_cast<Instruction>(Op);
1783       if (I && isOpcodeOrAlt(I))
1784         return Op;
1785       return MainOp;
1786     }
1787 
1788     void setOperations(const InstructionsState &S) {
1789       MainOp = S.MainOp;
1790       AltOp = S.AltOp;
1791     }
1792 
1793     Instruction *getMainOp() const {
1794       return MainOp;
1795     }
1796 
1797     Instruction *getAltOp() const {
1798       return AltOp;
1799     }
1800 
1801     /// The main/alternate opcodes for the list of instructions.
1802     unsigned getOpcode() const {
1803       return MainOp ? MainOp->getOpcode() : 0;
1804     }
1805 
1806     unsigned getAltOpcode() const {
1807       return AltOp ? AltOp->getOpcode() : 0;
1808     }
1809 
1810     /// When ReuseReorderShuffleIndices is empty it just returns position of \p
1811     /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
1812     int findLaneForValue(Value *V) const {
1813       unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
1814       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
1815       if (!ReorderIndices.empty())
1816         FoundLane = ReorderIndices[FoundLane];
1817       assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
1818       if (!ReuseShuffleIndices.empty()) {
1819         FoundLane = std::distance(ReuseShuffleIndices.begin(),
1820                                   find(ReuseShuffleIndices, FoundLane));
1821       }
1822       return FoundLane;
1823     }
1824 
1825 #ifndef NDEBUG
1826     /// Debug printer.
1827     LLVM_DUMP_METHOD void dump() const {
1828       dbgs() << Idx << ".\n";
1829       for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
1830         dbgs() << "Operand " << OpI << ":\n";
1831         for (const Value *V : Operands[OpI])
1832           dbgs().indent(2) << *V << "\n";
1833       }
1834       dbgs() << "Scalars: \n";
1835       for (Value *V : Scalars)
1836         dbgs().indent(2) << *V << "\n";
1837       dbgs() << "State: ";
1838       switch (State) {
1839       case Vectorize:
1840         dbgs() << "Vectorize\n";
1841         break;
1842       case ScatterVectorize:
1843         dbgs() << "ScatterVectorize\n";
1844         break;
1845       case NeedToGather:
1846         dbgs() << "NeedToGather\n";
1847         break;
1848       }
1849       dbgs() << "MainOp: ";
1850       if (MainOp)
1851         dbgs() << *MainOp << "\n";
1852       else
1853         dbgs() << "NULL\n";
1854       dbgs() << "AltOp: ";
1855       if (AltOp)
1856         dbgs() << *AltOp << "\n";
1857       else
1858         dbgs() << "NULL\n";
1859       dbgs() << "VectorizedValue: ";
1860       if (VectorizedValue)
1861         dbgs() << *VectorizedValue << "\n";
1862       else
1863         dbgs() << "NULL\n";
1864       dbgs() << "ReuseShuffleIndices: ";
1865       if (ReuseShuffleIndices.empty())
1866         dbgs() << "Empty";
1867       else
1868         for (unsigned ReuseIdx : ReuseShuffleIndices)
1869           dbgs() << ReuseIdx << ", ";
1870       dbgs() << "\n";
1871       dbgs() << "ReorderIndices: ";
1872       for (unsigned ReorderIdx : ReorderIndices)
1873         dbgs() << ReorderIdx << ", ";
1874       dbgs() << "\n";
1875       dbgs() << "UserTreeIndices: ";
1876       for (const auto &EInfo : UserTreeIndices)
1877         dbgs() << EInfo << ", ";
1878       dbgs() << "\n";
1879     }
1880 #endif
1881   };
1882 
1883 #ifndef NDEBUG
1884   void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
1885                      InstructionCost VecCost,
1886                      InstructionCost ScalarCost) const {
1887     dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
1888     dbgs() << "SLP: Costs:\n";
1889     dbgs() << "SLP:     ReuseShuffleCost = " << ReuseShuffleCost << "\n";
1890     dbgs() << "SLP:     VectorCost = " << VecCost << "\n";
1891     dbgs() << "SLP:     ScalarCost = " << ScalarCost << "\n";
1892     dbgs() << "SLP:     ReuseShuffleCost + VecCost - ScalarCost = " <<
1893                ReuseShuffleCost + VecCost - ScalarCost << "\n";
1894   }
1895 #endif
1896 
1897   /// Create a new VectorizableTree entry.
1898   TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
1899                           const InstructionsState &S,
1900                           const EdgeInfo &UserTreeIdx,
1901                           ArrayRef<int> ReuseShuffleIndices = None,
1902                           ArrayRef<unsigned> ReorderIndices = None) {
1903     TreeEntry::EntryState EntryState =
1904         Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
1905     return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
1906                         ReuseShuffleIndices, ReorderIndices);
1907   }
1908 
1909   TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
1910                           TreeEntry::EntryState EntryState,
1911                           Optional<ScheduleData *> Bundle,
1912                           const InstructionsState &S,
1913                           const EdgeInfo &UserTreeIdx,
1914                           ArrayRef<int> ReuseShuffleIndices = None,
1915                           ArrayRef<unsigned> ReorderIndices = None) {
1916     assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
1917             (Bundle && EntryState != TreeEntry::NeedToGather)) &&
1918            "Need to vectorize gather entry?");
1919     VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
1920     TreeEntry *Last = VectorizableTree.back().get();
1921     Last->Idx = VectorizableTree.size() - 1;
1922     Last->State = EntryState;
1923     Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
1924                                      ReuseShuffleIndices.end());
1925     if (ReorderIndices.empty()) {
1926       Last->Scalars.assign(VL.begin(), VL.end());
1927       Last->setOperations(S);
1928     } else {
1929       // Reorder scalars and build final mask.
1930       Last->Scalars.assign(VL.size(), nullptr);
1931       transform(ReorderIndices, Last->Scalars.begin(),
1932                 [VL](unsigned Idx) -> Value * {
1933                   if (Idx >= VL.size())
1934                     return UndefValue::get(VL.front()->getType());
1935                   return VL[Idx];
1936                 });
1937       InstructionsState S = getSameOpcode(Last->Scalars);
1938       Last->setOperations(S);
1939       Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
1940     }
1941     if (Last->State != TreeEntry::NeedToGather) {
1942       for (Value *V : VL) {
1943         assert(!getTreeEntry(V) && "Scalar already in tree!");
1944         ScalarToTreeEntry[V] = Last;
1945       }
1946       // Update the scheduler bundle to point to this TreeEntry.
1947       unsigned Lane = 0;
1948       for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
1949            BundleMember = BundleMember->NextInBundle) {
1950         BundleMember->TE = Last;
1951         BundleMember->Lane = Lane;
1952         ++Lane;
1953       }
1954       assert((!Bundle.getValue() || Lane == VL.size()) &&
1955              "Bundle and VL out of sync");
1956     } else {
1957       MustGather.insert(VL.begin(), VL.end());
1958     }
1959 
1960     if (UserTreeIdx.UserTE)
1961       Last->UserTreeIndices.push_back(UserTreeIdx);
1962 
1963     return Last;
1964   }
1965 
1966   /// -- Vectorization State --
1967   /// Holds all of the tree entries.
1968   TreeEntry::VecTreeTy VectorizableTree;
1969 
1970 #ifndef NDEBUG
1971   /// Debug printer.
1972   LLVM_DUMP_METHOD void dumpVectorizableTree() const {
1973     for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
1974       VectorizableTree[Id]->dump();
1975       dbgs() << "\n";
1976     }
1977   }
1978 #endif
1979 
1980   TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
1981 
1982   const TreeEntry *getTreeEntry(Value *V) const {
1983     return ScalarToTreeEntry.lookup(V);
1984   }
1985 
1986   /// Maps a specific scalar to its tree entry.
1987   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
1988 
1989   /// Maps a value to the proposed vectorizable size.
1990   SmallDenseMap<Value *, unsigned> InstrElementSize;
1991 
1992   /// A list of scalars that we found that we need to keep as scalars.
1993   ValueSet MustGather;
1994 
1995   /// This POD struct describes one external user in the vectorized tree.
1996   struct ExternalUser {
1997     ExternalUser(Value *S, llvm::User *U, int L)
1998         : Scalar(S), User(U), Lane(L) {}
1999 
2000     // Which scalar in our function.
2001     Value *Scalar;
2002 
2003     // Which user that uses the scalar.
2004     llvm::User *User;
2005 
2006     // Which lane does the scalar belong to.
2007     int Lane;
2008   };
2009   using UserList = SmallVector<ExternalUser, 16>;
2010 
2011   /// Checks if two instructions may access the same memory.
2012   ///
2013   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2014   /// is invariant in the calling loop.
2015   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2016                  Instruction *Inst2) {
2017     // First check if the result is already in the cache.
2018     AliasCacheKey key = std::make_pair(Inst1, Inst2);
2019     Optional<bool> &result = AliasCache[key];
2020     if (result.hasValue()) {
2021       return result.getValue();
2022     }
2023     bool aliased = true;
2024     if (Loc1.Ptr && isSimple(Inst1))
2025       aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
2026     // Store the result in the cache.
2027     result = aliased;
2028     return aliased;
2029   }
2030 
2031   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2032 
2033   /// Cache for alias results.
2034   /// TODO: consider moving this to the AliasAnalysis itself.
2035   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
2036 
2037   /// Removes an instruction from its block and eventually deletes it.
2038   /// It's like Instruction::eraseFromParent() except that the actual deletion
2039   /// is delayed until BoUpSLP is destructed.
2040   /// This is required to ensure that there are no incorrect collisions in the
2041   /// AliasCache, which can happen if a new instruction is allocated at the
2042   /// same address as a previously deleted instruction.
2043   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
2044     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
2045     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
2046   }
2047 
2048   /// Temporary store for deleted instructions. Instructions will be deleted
2049   /// eventually when the BoUpSLP is destructed.
2050   DenseMap<Instruction *, bool> DeletedInstructions;
2051 
2052   /// A list of values that need to extracted out of the tree.
2053   /// This list holds pairs of (Internal Scalar : External User). External User
2054   /// can be nullptr, it means that this Internal Scalar will be used later,
2055   /// after vectorization.
2056   UserList ExternalUses;
2057 
2058   /// Values used only by @llvm.assume calls.
2059   SmallPtrSet<const Value *, 32> EphValues;
2060 
2061   /// Holds all of the instructions that we gathered.
2062   SetVector<Instruction *> GatherSeq;
2063 
2064   /// A list of blocks that we are going to CSE.
2065   SetVector<BasicBlock *> CSEBlocks;
2066 
2067   /// Contains all scheduling relevant data for an instruction.
2068   /// A ScheduleData either represents a single instruction or a member of an
2069   /// instruction bundle (= a group of instructions which is combined into a
2070   /// vector instruction).
2071   struct ScheduleData {
2072     // The initial value for the dependency counters. It means that the
2073     // dependencies are not calculated yet.
2074     enum { InvalidDeps = -1 };
2075 
2076     ScheduleData() = default;
2077 
2078     void init(int BlockSchedulingRegionID, Value *OpVal) {
2079       FirstInBundle = this;
2080       NextInBundle = nullptr;
2081       NextLoadStore = nullptr;
2082       IsScheduled = false;
2083       SchedulingRegionID = BlockSchedulingRegionID;
2084       UnscheduledDepsInBundle = UnscheduledDeps;
2085       clearDependencies();
2086       OpValue = OpVal;
2087       TE = nullptr;
2088       Lane = -1;
2089     }
2090 
2091     /// Returns true if the dependency information has been calculated.
2092     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2093 
2094     /// Returns true for single instructions and for bundle representatives
2095     /// (= the head of a bundle).
2096     bool isSchedulingEntity() const { return FirstInBundle == this; }
2097 
2098     /// Returns true if it represents an instruction bundle and not only a
2099     /// single instruction.
2100     bool isPartOfBundle() const {
2101       return NextInBundle != nullptr || FirstInBundle != this;
2102     }
2103 
2104     /// Returns true if it is ready for scheduling, i.e. it has no more
2105     /// unscheduled depending instructions/bundles.
2106     bool isReady() const {
2107       assert(isSchedulingEntity() &&
2108              "can't consider non-scheduling entity for ready list");
2109       return UnscheduledDepsInBundle == 0 && !IsScheduled;
2110     }
2111 
2112     /// Modifies the number of unscheduled dependencies, also updating it for
2113     /// the whole bundle.
2114     int incrementUnscheduledDeps(int Incr) {
2115       UnscheduledDeps += Incr;
2116       return FirstInBundle->UnscheduledDepsInBundle += Incr;
2117     }
2118 
2119     /// Sets the number of unscheduled dependencies to the number of
2120     /// dependencies.
2121     void resetUnscheduledDeps() {
2122       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
2123     }
2124 
2125     /// Clears all dependency information.
2126     void clearDependencies() {
2127       Dependencies = InvalidDeps;
2128       resetUnscheduledDeps();
2129       MemoryDependencies.clear();
2130     }
2131 
2132     void dump(raw_ostream &os) const {
2133       if (!isSchedulingEntity()) {
2134         os << "/ " << *Inst;
2135       } else if (NextInBundle) {
2136         os << '[' << *Inst;
2137         ScheduleData *SD = NextInBundle;
2138         while (SD) {
2139           os << ';' << *SD->Inst;
2140           SD = SD->NextInBundle;
2141         }
2142         os << ']';
2143       } else {
2144         os << *Inst;
2145       }
2146     }
2147 
2148     Instruction *Inst = nullptr;
2149 
2150     /// Points to the head in an instruction bundle (and always to this for
2151     /// single instructions).
2152     ScheduleData *FirstInBundle = nullptr;
2153 
2154     /// Single linked list of all instructions in a bundle. Null if it is a
2155     /// single instruction.
2156     ScheduleData *NextInBundle = nullptr;
2157 
2158     /// Single linked list of all memory instructions (e.g. load, store, call)
2159     /// in the block - until the end of the scheduling region.
2160     ScheduleData *NextLoadStore = nullptr;
2161 
2162     /// The dependent memory instructions.
2163     /// This list is derived on demand in calculateDependencies().
2164     SmallVector<ScheduleData *, 4> MemoryDependencies;
2165 
2166     /// This ScheduleData is in the current scheduling region if this matches
2167     /// the current SchedulingRegionID of BlockScheduling.
2168     int SchedulingRegionID = 0;
2169 
2170     /// Used for getting a "good" final ordering of instructions.
2171     int SchedulingPriority = 0;
2172 
2173     /// The number of dependencies. Constitutes of the number of users of the
2174     /// instruction plus the number of dependent memory instructions (if any).
2175     /// This value is calculated on demand.
2176     /// If InvalidDeps, the number of dependencies is not calculated yet.
2177     int Dependencies = InvalidDeps;
2178 
2179     /// The number of dependencies minus the number of dependencies of scheduled
2180     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2181     /// for scheduling.
2182     /// Note that this is negative as long as Dependencies is not calculated.
2183     int UnscheduledDeps = InvalidDeps;
2184 
2185     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
2186     /// single instructions.
2187     int UnscheduledDepsInBundle = InvalidDeps;
2188 
2189     /// True if this instruction is scheduled (or considered as scheduled in the
2190     /// dry-run).
2191     bool IsScheduled = false;
2192 
2193     /// Opcode of the current instruction in the schedule data.
2194     Value *OpValue = nullptr;
2195 
2196     /// The TreeEntry that this instruction corresponds to.
2197     TreeEntry *TE = nullptr;
2198 
2199     /// The lane of this node in the TreeEntry.
2200     int Lane = -1;
2201   };
2202 
2203 #ifndef NDEBUG
2204   friend inline raw_ostream &operator<<(raw_ostream &os,
2205                                         const BoUpSLP::ScheduleData &SD) {
2206     SD.dump(os);
2207     return os;
2208   }
2209 #endif
2210 
2211   friend struct GraphTraits<BoUpSLP *>;
2212   friend struct DOTGraphTraits<BoUpSLP *>;
2213 
2214   /// Contains all scheduling data for a basic block.
2215   struct BlockScheduling {
2216     BlockScheduling(BasicBlock *BB)
2217         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2218 
2219     void clear() {
2220       ReadyInsts.clear();
2221       ScheduleStart = nullptr;
2222       ScheduleEnd = nullptr;
2223       FirstLoadStoreInRegion = nullptr;
2224       LastLoadStoreInRegion = nullptr;
2225 
2226       // Reduce the maximum schedule region size by the size of the
2227       // previous scheduling run.
2228       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2229       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2230         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2231       ScheduleRegionSize = 0;
2232 
2233       // Make a new scheduling region, i.e. all existing ScheduleData is not
2234       // in the new region yet.
2235       ++SchedulingRegionID;
2236     }
2237 
2238     ScheduleData *getScheduleData(Value *V) {
2239       ScheduleData *SD = ScheduleDataMap[V];
2240       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2241         return SD;
2242       return nullptr;
2243     }
2244 
2245     ScheduleData *getScheduleData(Value *V, Value *Key) {
2246       if (V == Key)
2247         return getScheduleData(V);
2248       auto I = ExtraScheduleDataMap.find(V);
2249       if (I != ExtraScheduleDataMap.end()) {
2250         ScheduleData *SD = I->second[Key];
2251         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2252           return SD;
2253       }
2254       return nullptr;
2255     }
2256 
2257     bool isInSchedulingRegion(ScheduleData *SD) const {
2258       return SD->SchedulingRegionID == SchedulingRegionID;
2259     }
2260 
2261     /// Marks an instruction as scheduled and puts all dependent ready
2262     /// instructions into the ready-list.
2263     template <typename ReadyListType>
2264     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2265       SD->IsScheduled = true;
2266       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2267 
2268       ScheduleData *BundleMember = SD;
2269       while (BundleMember) {
2270         if (BundleMember->Inst != BundleMember->OpValue) {
2271           BundleMember = BundleMember->NextInBundle;
2272           continue;
2273         }
2274         // Handle the def-use chain dependencies.
2275 
2276         // Decrement the unscheduled counter and insert to ready list if ready.
2277         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2278           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2279             if (OpDef && OpDef->hasValidDependencies() &&
2280                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2281               // There are no more unscheduled dependencies after
2282               // decrementing, so we can put the dependent instruction
2283               // into the ready list.
2284               ScheduleData *DepBundle = OpDef->FirstInBundle;
2285               assert(!DepBundle->IsScheduled &&
2286                      "already scheduled bundle gets ready");
2287               ReadyList.insert(DepBundle);
2288               LLVM_DEBUG(dbgs()
2289                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2290             }
2291           });
2292         };
2293 
2294         // If BundleMember is a vector bundle, its operands may have been
2295         // reordered duiring buildTree(). We therefore need to get its operands
2296         // through the TreeEntry.
2297         if (TreeEntry *TE = BundleMember->TE) {
2298           int Lane = BundleMember->Lane;
2299           assert(Lane >= 0 && "Lane not set");
2300 
2301           // Since vectorization tree is being built recursively this assertion
2302           // ensures that the tree entry has all operands set before reaching
2303           // this code. Couple of exceptions known at the moment are extracts
2304           // where their second (immediate) operand is not added. Since
2305           // immediates do not affect scheduler behavior this is considered
2306           // okay.
2307           auto *In = TE->getMainOp();
2308           assert(In &&
2309                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2310                   In->getNumOperands() == TE->getNumOperands()) &&
2311                  "Missed TreeEntry operands?");
2312           (void)In; // fake use to avoid build failure when assertions disabled
2313 
2314           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2315                OpIdx != NumOperands; ++OpIdx)
2316             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2317               DecrUnsched(I);
2318         } else {
2319           // If BundleMember is a stand-alone instruction, no operand reordering
2320           // has taken place, so we directly access its operands.
2321           for (Use &U : BundleMember->Inst->operands())
2322             if (auto *I = dyn_cast<Instruction>(U.get()))
2323               DecrUnsched(I);
2324         }
2325         // Handle the memory dependencies.
2326         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2327           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2328             // There are no more unscheduled dependencies after decrementing,
2329             // so we can put the dependent instruction into the ready list.
2330             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2331             assert(!DepBundle->IsScheduled &&
2332                    "already scheduled bundle gets ready");
2333             ReadyList.insert(DepBundle);
2334             LLVM_DEBUG(dbgs()
2335                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2336           }
2337         }
2338         BundleMember = BundleMember->NextInBundle;
2339       }
2340     }
2341 
2342     void doForAllOpcodes(Value *V,
2343                          function_ref<void(ScheduleData *SD)> Action) {
2344       if (ScheduleData *SD = getScheduleData(V))
2345         Action(SD);
2346       auto I = ExtraScheduleDataMap.find(V);
2347       if (I != ExtraScheduleDataMap.end())
2348         for (auto &P : I->second)
2349           if (P.second->SchedulingRegionID == SchedulingRegionID)
2350             Action(P.second);
2351     }
2352 
2353     /// Put all instructions into the ReadyList which are ready for scheduling.
2354     template <typename ReadyListType>
2355     void initialFillReadyList(ReadyListType &ReadyList) {
2356       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2357         doForAllOpcodes(I, [&](ScheduleData *SD) {
2358           if (SD->isSchedulingEntity() && SD->isReady()) {
2359             ReadyList.insert(SD);
2360             LLVM_DEBUG(dbgs()
2361                        << "SLP:    initially in ready list: " << *I << "\n");
2362           }
2363         });
2364       }
2365     }
2366 
2367     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2368     /// cyclic dependencies. This is only a dry-run, no instructions are
2369     /// actually moved at this stage.
2370     /// \returns the scheduling bundle. The returned Optional value is non-None
2371     /// if \p VL is allowed to be scheduled.
2372     Optional<ScheduleData *>
2373     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2374                       const InstructionsState &S);
2375 
2376     /// Un-bundles a group of instructions.
2377     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2378 
2379     /// Allocates schedule data chunk.
2380     ScheduleData *allocateScheduleDataChunks();
2381 
2382     /// Extends the scheduling region so that V is inside the region.
2383     /// \returns true if the region size is within the limit.
2384     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2385 
2386     /// Initialize the ScheduleData structures for new instructions in the
2387     /// scheduling region.
2388     void initScheduleData(Instruction *FromI, Instruction *ToI,
2389                           ScheduleData *PrevLoadStore,
2390                           ScheduleData *NextLoadStore);
2391 
2392     /// Updates the dependency information of a bundle and of all instructions/
2393     /// bundles which depend on the original bundle.
2394     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2395                                BoUpSLP *SLP);
2396 
2397     /// Sets all instruction in the scheduling region to un-scheduled.
2398     void resetSchedule();
2399 
2400     BasicBlock *BB;
2401 
2402     /// Simple memory allocation for ScheduleData.
2403     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2404 
2405     /// The size of a ScheduleData array in ScheduleDataChunks.
2406     int ChunkSize;
2407 
2408     /// The allocator position in the current chunk, which is the last entry
2409     /// of ScheduleDataChunks.
2410     int ChunkPos;
2411 
2412     /// Attaches ScheduleData to Instruction.
2413     /// Note that the mapping survives during all vectorization iterations, i.e.
2414     /// ScheduleData structures are recycled.
2415     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2416 
2417     /// Attaches ScheduleData to Instruction with the leading key.
2418     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2419         ExtraScheduleDataMap;
2420 
2421     struct ReadyList : SmallVector<ScheduleData *, 8> {
2422       void insert(ScheduleData *SD) { push_back(SD); }
2423     };
2424 
2425     /// The ready-list for scheduling (only used for the dry-run).
2426     ReadyList ReadyInsts;
2427 
2428     /// The first instruction of the scheduling region.
2429     Instruction *ScheduleStart = nullptr;
2430 
2431     /// The first instruction _after_ the scheduling region.
2432     Instruction *ScheduleEnd = nullptr;
2433 
2434     /// The first memory accessing instruction in the scheduling region
2435     /// (can be null).
2436     ScheduleData *FirstLoadStoreInRegion = nullptr;
2437 
2438     /// The last memory accessing instruction in the scheduling region
2439     /// (can be null).
2440     ScheduleData *LastLoadStoreInRegion = nullptr;
2441 
2442     /// The current size of the scheduling region.
2443     int ScheduleRegionSize = 0;
2444 
2445     /// The maximum size allowed for the scheduling region.
2446     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2447 
2448     /// The ID of the scheduling region. For a new vectorization iteration this
2449     /// is incremented which "removes" all ScheduleData from the region.
2450     // Make sure that the initial SchedulingRegionID is greater than the
2451     // initial SchedulingRegionID in ScheduleData (which is 0).
2452     int SchedulingRegionID = 1;
2453   };
2454 
2455   /// Attaches the BlockScheduling structures to basic blocks.
2456   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2457 
2458   /// Performs the "real" scheduling. Done before vectorization is actually
2459   /// performed in a basic block.
2460   void scheduleBlock(BlockScheduling *BS);
2461 
2462   /// List of users to ignore during scheduling and that don't need extracting.
2463   ArrayRef<Value *> UserIgnoreList;
2464 
2465   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2466   /// sorted SmallVectors of unsigned.
2467   struct OrdersTypeDenseMapInfo {
2468     static OrdersType getEmptyKey() {
2469       OrdersType V;
2470       V.push_back(~1U);
2471       return V;
2472     }
2473 
2474     static OrdersType getTombstoneKey() {
2475       OrdersType V;
2476       V.push_back(~2U);
2477       return V;
2478     }
2479 
2480     static unsigned getHashValue(const OrdersType &V) {
2481       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2482     }
2483 
2484     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2485       return LHS == RHS;
2486     }
2487   };
2488 
2489   // Analysis and block reference.
2490   Function *F;
2491   ScalarEvolution *SE;
2492   TargetTransformInfo *TTI;
2493   TargetLibraryInfo *TLI;
2494   AAResults *AA;
2495   LoopInfo *LI;
2496   DominatorTree *DT;
2497   AssumptionCache *AC;
2498   DemandedBits *DB;
2499   const DataLayout *DL;
2500   OptimizationRemarkEmitter *ORE;
2501 
2502   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2503   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2504 
2505   /// Instruction builder to construct the vectorized tree.
2506   IRBuilder<> Builder;
2507 
2508   /// A map of scalar integer values to the smallest bit width with which they
2509   /// can legally be represented. The values map to (width, signed) pairs,
2510   /// where "width" indicates the minimum bit width and "signed" is True if the
2511   /// value must be signed-extended, rather than zero-extended, back to its
2512   /// original width.
2513   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2514 };
2515 
2516 } // end namespace slpvectorizer
2517 
2518 template <> struct GraphTraits<BoUpSLP *> {
2519   using TreeEntry = BoUpSLP::TreeEntry;
2520 
2521   /// NodeRef has to be a pointer per the GraphWriter.
2522   using NodeRef = TreeEntry *;
2523 
2524   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2525 
2526   /// Add the VectorizableTree to the index iterator to be able to return
2527   /// TreeEntry pointers.
2528   struct ChildIteratorType
2529       : public iterator_adaptor_base<
2530             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2531     ContainerTy &VectorizableTree;
2532 
2533     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2534                       ContainerTy &VT)
2535         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2536 
2537     NodeRef operator*() { return I->UserTE; }
2538   };
2539 
2540   static NodeRef getEntryNode(BoUpSLP &R) {
2541     return R.VectorizableTree[0].get();
2542   }
2543 
2544   static ChildIteratorType child_begin(NodeRef N) {
2545     return {N->UserTreeIndices.begin(), N->Container};
2546   }
2547 
2548   static ChildIteratorType child_end(NodeRef N) {
2549     return {N->UserTreeIndices.end(), N->Container};
2550   }
2551 
2552   /// For the node iterator we just need to turn the TreeEntry iterator into a
2553   /// TreeEntry* iterator so that it dereferences to NodeRef.
2554   class nodes_iterator {
2555     using ItTy = ContainerTy::iterator;
2556     ItTy It;
2557 
2558   public:
2559     nodes_iterator(const ItTy &It2) : It(It2) {}
2560     NodeRef operator*() { return It->get(); }
2561     nodes_iterator operator++() {
2562       ++It;
2563       return *this;
2564     }
2565     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2566   };
2567 
2568   static nodes_iterator nodes_begin(BoUpSLP *R) {
2569     return nodes_iterator(R->VectorizableTree.begin());
2570   }
2571 
2572   static nodes_iterator nodes_end(BoUpSLP *R) {
2573     return nodes_iterator(R->VectorizableTree.end());
2574   }
2575 
2576   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2577 };
2578 
2579 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2580   using TreeEntry = BoUpSLP::TreeEntry;
2581 
2582   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2583 
2584   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2585     std::string Str;
2586     raw_string_ostream OS(Str);
2587     if (isSplat(Entry->Scalars)) {
2588       OS << "<splat> " << *Entry->Scalars[0];
2589       return Str;
2590     }
2591     for (auto V : Entry->Scalars) {
2592       OS << *V;
2593       if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
2594             return EU.Scalar == V;
2595           }))
2596         OS << " <extract>";
2597       OS << "\n";
2598     }
2599     return Str;
2600   }
2601 
2602   static std::string getNodeAttributes(const TreeEntry *Entry,
2603                                        const BoUpSLP *) {
2604     if (Entry->State == TreeEntry::NeedToGather)
2605       return "color=red";
2606     return "";
2607   }
2608 };
2609 
2610 } // end namespace llvm
2611 
2612 BoUpSLP::~BoUpSLP() {
2613   for (const auto &Pair : DeletedInstructions) {
2614     // Replace operands of ignored instructions with Undefs in case if they were
2615     // marked for deletion.
2616     if (Pair.getSecond()) {
2617       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
2618       Pair.getFirst()->replaceAllUsesWith(Undef);
2619     }
2620     Pair.getFirst()->dropAllReferences();
2621   }
2622   for (const auto &Pair : DeletedInstructions) {
2623     assert(Pair.getFirst()->use_empty() &&
2624            "trying to erase instruction with users.");
2625     Pair.getFirst()->eraseFromParent();
2626   }
2627 #ifdef EXPENSIVE_CHECKS
2628   // If we could guarantee that this call is not extremely slow, we could
2629   // remove the ifdef limitation (see PR47712).
2630   assert(!verifyFunction(*F, &dbgs()));
2631 #endif
2632 }
2633 
2634 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
2635   for (auto *V : AV) {
2636     if (auto *I = dyn_cast<Instruction>(V))
2637       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
2638   };
2639 }
2640 
2641 /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
2642 /// contains original mask for the scalars reused in the node. Procedure
2643 /// transform this mask in accordance with the given \p Mask.
2644 static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
2645   assert(!Mask.empty() && Reuses.size() == Mask.size() &&
2646          "Expected non-empty mask.");
2647   SmallVector<int> Prev(Reuses.begin(), Reuses.end());
2648   Prev.swap(Reuses);
2649   for (unsigned I = 0, E = Prev.size(); I < E; ++I)
2650     if (Mask[I] != UndefMaskElem)
2651       Reuses[Mask[I]] = Prev[I];
2652 }
2653 
2654 /// Reorders the given \p Order according to the given \p Mask. \p Order - is
2655 /// the original order of the scalars. Procedure transforms the provided order
2656 /// in accordance with the given \p Mask. If the resulting \p Order is just an
2657 /// identity order, \p Order is cleared.
2658 static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
2659   assert(!Mask.empty() && "Expected non-empty mask.");
2660   SmallVector<int> MaskOrder;
2661   if (Order.empty()) {
2662     MaskOrder.resize(Mask.size());
2663     std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
2664   } else {
2665     inversePermutation(Order, MaskOrder);
2666   }
2667   reorderReuses(MaskOrder, Mask);
2668   if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
2669     Order.clear();
2670     return;
2671   }
2672   Order.assign(Mask.size(), Mask.size());
2673   for (unsigned I = 0, E = Mask.size(); I < E; ++I)
2674     if (MaskOrder[I] != UndefMaskElem)
2675       Order[MaskOrder[I]] = I;
2676   fixupOrderingIndices(Order);
2677 }
2678 
2679 Optional<BoUpSLP::OrdersType>
2680 BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
2681   assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
2682   unsigned NumScalars = TE.Scalars.size();
2683   OrdersType CurrentOrder(NumScalars, NumScalars);
2684   SmallVector<int> Positions;
2685   SmallBitVector UsedPositions(NumScalars);
2686   const TreeEntry *STE = nullptr;
2687   // Try to find all gathered scalars that are gets vectorized in other
2688   // vectorize node. Here we can have only one single tree vector node to
2689   // correctly identify order of the gathered scalars.
2690   for (unsigned I = 0; I < NumScalars; ++I) {
2691     Value *V = TE.Scalars[I];
2692     if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
2693       continue;
2694     if (const auto *LocalSTE = getTreeEntry(V)) {
2695       if (!STE)
2696         STE = LocalSTE;
2697       else if (STE != LocalSTE)
2698         // Take the order only from the single vector node.
2699         return None;
2700       unsigned Lane =
2701           std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
2702       if (Lane >= NumScalars)
2703         return None;
2704       if (CurrentOrder[Lane] != NumScalars) {
2705         if (Lane != I)
2706           continue;
2707         UsedPositions.reset(CurrentOrder[Lane]);
2708       }
2709       // The partial identity (where only some elements of the gather node are
2710       // in the identity order) is good.
2711       CurrentOrder[Lane] = I;
2712       UsedPositions.set(I);
2713     }
2714   }
2715   // Need to keep the order if we have a vector entry and at least 2 scalars or
2716   // the vectorized entry has just 2 scalars.
2717   if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
2718     auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
2719       for (unsigned I = 0; I < NumScalars; ++I)
2720         if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
2721           return false;
2722       return true;
2723     };
2724     if (IsIdentityOrder(CurrentOrder)) {
2725       CurrentOrder.clear();
2726       return CurrentOrder;
2727     }
2728     auto *It = CurrentOrder.begin();
2729     for (unsigned I = 0; I < NumScalars;) {
2730       if (UsedPositions.test(I)) {
2731         ++I;
2732         continue;
2733       }
2734       if (*It == NumScalars) {
2735         *It = I;
2736         ++I;
2737       }
2738       ++It;
2739     }
2740     return CurrentOrder;
2741   }
2742   return None;
2743 }
2744 
2745 void BoUpSLP::reorderTopToBottom() {
2746   // Maps VF to the graph nodes.
2747   DenseMap<unsigned, SmallPtrSet<TreeEntry *, 4>> VFToOrderedEntries;
2748   // ExtractElement gather nodes which can be vectorized and need to handle
2749   // their ordering.
2750   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
2751   // Find all reorderable nodes with the given VF.
2752   // Currently the are vectorized loads,extracts + some gathering of extracts.
2753   for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
2754                                  const std::unique_ptr<TreeEntry> &TE) {
2755     // No need to reorder if need to shuffle reuses, still need to shuffle the
2756     // node.
2757     if (!TE->ReuseShuffleIndices.empty())
2758       return;
2759     if (TE->State == TreeEntry::Vectorize &&
2760         isa<LoadInst, ExtractElementInst, ExtractValueInst, StoreInst,
2761             InsertElementInst>(TE->getMainOp()) &&
2762         !TE->isAltShuffle()) {
2763       VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
2764       return;
2765     }
2766     if (TE->State == TreeEntry::NeedToGather) {
2767       if (TE->getOpcode() == Instruction::ExtractElement &&
2768           !TE->isAltShuffle() &&
2769           isa<FixedVectorType>(cast<ExtractElementInst>(TE->getMainOp())
2770                                    ->getVectorOperandType()) &&
2771           allSameType(TE->Scalars) && allSameBlock(TE->Scalars)) {
2772         // Check that gather of extractelements can be represented as
2773         // just a shuffle of a single vector.
2774         OrdersType CurrentOrder;
2775         bool Reuse =
2776             canReuseExtract(TE->Scalars, TE->getMainOp(), CurrentOrder);
2777         if (Reuse || !CurrentOrder.empty()) {
2778           VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
2779           GathersToOrders.try_emplace(TE.get(), CurrentOrder);
2780           return;
2781         }
2782       }
2783       if (Optional<OrdersType> CurrentOrder =
2784               findReusedOrderedScalars(*TE.get())) {
2785         VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
2786         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
2787       }
2788     }
2789   });
2790 
2791   // Reorder the graph nodes according to their vectorization factor.
2792   for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
2793        VF /= 2) {
2794     auto It = VFToOrderedEntries.find(VF);
2795     if (It == VFToOrderedEntries.end())
2796       continue;
2797     // Try to find the most profitable order. We just are looking for the most
2798     // used order and reorder scalar elements in the nodes according to this
2799     // mostly used order.
2800     const SmallPtrSetImpl<TreeEntry *> &OrderedEntries = It->getSecond();
2801     // All operands are reordered and used only in this node - propagate the
2802     // most used order to the user node.
2803     MapVector<OrdersType, unsigned,
2804               DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
2805         OrdersUses;
2806     SmallPtrSet<const TreeEntry *, 4> VisitedOps;
2807     for (const TreeEntry *OpTE : OrderedEntries) {
2808       // No need to reorder this nodes, still need to extend and to use shuffle,
2809       // just need to merge reordering shuffle and the reuse shuffle.
2810       if (!OpTE->ReuseShuffleIndices.empty())
2811         continue;
2812       // Count number of orders uses.
2813       const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
2814         if (OpTE->State == TreeEntry::NeedToGather)
2815           return GathersToOrders.find(OpTE)->second;
2816         return OpTE->ReorderIndices;
2817       }();
2818       // Stores actually store the mask, not the order, need to invert.
2819       if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
2820           OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
2821         SmallVector<int> Mask;
2822         inversePermutation(Order, Mask);
2823         unsigned E = Order.size();
2824         OrdersType CurrentOrder(E, E);
2825         transform(Mask, CurrentOrder.begin(), [E](int Idx) {
2826           return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
2827         });
2828         fixupOrderingIndices(CurrentOrder);
2829         ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
2830       } else {
2831         ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
2832       }
2833     }
2834     // Set order of the user node.
2835     if (OrdersUses.empty())
2836       continue;
2837     // Choose the most used order.
2838     ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
2839     unsigned Cnt = OrdersUses.front().second;
2840     for (const auto &Pair : drop_begin(OrdersUses)) {
2841       if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
2842         BestOrder = Pair.first;
2843         Cnt = Pair.second;
2844       }
2845     }
2846     // Set order of the user node.
2847     if (BestOrder.empty())
2848       continue;
2849     SmallVector<int> Mask;
2850     inversePermutation(BestOrder, Mask);
2851     SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
2852     unsigned E = BestOrder.size();
2853     transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
2854       return I < E ? static_cast<int>(I) : UndefMaskElem;
2855     });
2856     // Do an actual reordering, if profitable.
2857     for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
2858       // Just do the reordering for the nodes with the given VF.
2859       if (TE->Scalars.size() != VF) {
2860         if (TE->ReuseShuffleIndices.size() == VF) {
2861           // Need to reorder the reuses masks of the operands with smaller VF to
2862           // be able to find the match between the graph nodes and scalar
2863           // operands of the given node during vectorization/cost estimation.
2864           assert(all_of(TE->UserTreeIndices,
2865                         [VF, &TE](const EdgeInfo &EI) {
2866                           return EI.UserTE->Scalars.size() == VF ||
2867                                  EI.UserTE->Scalars.size() ==
2868                                      TE->Scalars.size();
2869                         }) &&
2870                  "All users must be of VF size.");
2871           // Update ordering of the operands with the smaller VF than the given
2872           // one.
2873           reorderReuses(TE->ReuseShuffleIndices, Mask);
2874         }
2875         continue;
2876       }
2877       if (TE->State == TreeEntry::Vectorize &&
2878           isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
2879               InsertElementInst>(TE->getMainOp()) &&
2880           !TE->isAltShuffle()) {
2881         // Build correct orders for extract{element,value}, loads and
2882         // stores.
2883         reorderOrder(TE->ReorderIndices, Mask);
2884         if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
2885           TE->reorderOperands(Mask);
2886       } else {
2887         // Reorder the node and its operands.
2888         TE->reorderOperands(Mask);
2889         assert(TE->ReorderIndices.empty() &&
2890                "Expected empty reorder sequence.");
2891         reorderScalars(TE->Scalars, Mask);
2892       }
2893       if (!TE->ReuseShuffleIndices.empty()) {
2894         // Apply reversed order to keep the original ordering of the reused
2895         // elements to avoid extra reorder indices shuffling.
2896         OrdersType CurrentOrder;
2897         reorderOrder(CurrentOrder, MaskOrder);
2898         SmallVector<int> NewReuses;
2899         inversePermutation(CurrentOrder, NewReuses);
2900         addMask(NewReuses, TE->ReuseShuffleIndices);
2901         TE->ReuseShuffleIndices.swap(NewReuses);
2902       }
2903     }
2904   }
2905 }
2906 
2907 void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
2908   SetVector<TreeEntry *> OrderedEntries;
2909   DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
2910   // Find all reorderable leaf nodes with the given VF.
2911   // Currently the are vectorized loads,extracts without alternate operands +
2912   // some gathering of extracts.
2913   SmallVector<TreeEntry *> NonVectorized;
2914   for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
2915                               &NonVectorized](
2916                                  const std::unique_ptr<TreeEntry> &TE) {
2917     if (TE->State != TreeEntry::Vectorize)
2918       NonVectorized.push_back(TE.get());
2919     // No need to reorder if need to shuffle reuses, still need to shuffle the
2920     // node.
2921     if (!TE->ReuseShuffleIndices.empty())
2922       return;
2923     if (TE->State == TreeEntry::Vectorize &&
2924         isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE->getMainOp()) &&
2925         !TE->isAltShuffle()) {
2926       OrderedEntries.insert(TE.get());
2927       return;
2928     }
2929     if (TE->State == TreeEntry::NeedToGather) {
2930       if (TE->getOpcode() == Instruction::ExtractElement &&
2931           !TE->isAltShuffle() &&
2932           isa<FixedVectorType>(cast<ExtractElementInst>(TE->getMainOp())
2933                                    ->getVectorOperandType()) &&
2934           allSameType(TE->Scalars) && allSameBlock(TE->Scalars)) {
2935         // Check that gather of extractelements can be represented as
2936         // just a shuffle of a single vector with a single user only.
2937         OrdersType CurrentOrder;
2938         bool Reuse =
2939             canReuseExtract(TE->Scalars, TE->getMainOp(), CurrentOrder);
2940         if ((Reuse || !CurrentOrder.empty()) &&
2941             !any_of(VectorizableTree,
2942                     [&TE](const std::unique_ptr<TreeEntry> &Entry) {
2943                       return Entry->State == TreeEntry::NeedToGather &&
2944                              Entry.get() != TE.get() &&
2945                              Entry->isSame(TE->Scalars);
2946                     })) {
2947           OrderedEntries.insert(TE.get());
2948           GathersToOrders.try_emplace(TE.get(), CurrentOrder);
2949           return;
2950         }
2951       }
2952       if (Optional<OrdersType> CurrentOrder =
2953               findReusedOrderedScalars(*TE.get())) {
2954         OrderedEntries.insert(TE.get());
2955         GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
2956       }
2957     }
2958   });
2959 
2960   // Checks if the operands of the users are reordarable and have only single
2961   // use.
2962   auto &&CheckOperands =
2963       [this, &NonVectorized](const auto &Data,
2964                              SmallVectorImpl<TreeEntry *> &GatherOps) {
2965         for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) {
2966           if (any_of(Data.second,
2967                      [I](const std::pair<unsigned, TreeEntry *> &OpData) {
2968                        return OpData.first == I &&
2969                               OpData.second->State == TreeEntry::Vectorize;
2970                      }))
2971             continue;
2972           ArrayRef<Value *> VL = Data.first->getOperand(I);
2973           const TreeEntry *TE = nullptr;
2974           const auto *It = find_if(VL, [this, &TE](Value *V) {
2975             TE = getTreeEntry(V);
2976             return TE;
2977           });
2978           if (It != VL.end() && TE->isSame(VL))
2979             return false;
2980           TreeEntry *Gather = nullptr;
2981           if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) {
2982                 assert(TE->State != TreeEntry::Vectorize &&
2983                        "Only non-vectorized nodes are expected.");
2984                 if (TE->isSame(VL)) {
2985                   Gather = TE;
2986                   return true;
2987                 }
2988                 return false;
2989               }) > 1)
2990             return false;
2991           if (Gather)
2992             GatherOps.push_back(Gather);
2993         }
2994         return true;
2995       };
2996   // 1. Propagate order to the graph nodes, which use only reordered nodes.
2997   // I.e., if the node has operands, that are reordered, try to make at least
2998   // one operand order in the natural order and reorder others + reorder the
2999   // user node itself.
3000   SmallPtrSet<const TreeEntry *, 4> Visited;
3001   while (!OrderedEntries.empty()) {
3002     // 1. Filter out only reordered nodes.
3003     // 2. If the entry has multiple uses - skip it and jump to the next node.
3004     MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
3005     SmallVector<TreeEntry *> Filtered;
3006     for (TreeEntry *TE : OrderedEntries) {
3007       if (!(TE->State == TreeEntry::Vectorize ||
3008             (TE->State == TreeEntry::NeedToGather &&
3009              GathersToOrders.count(TE))) ||
3010           TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
3011           !all_of(drop_begin(TE->UserTreeIndices),
3012                   [TE](const EdgeInfo &EI) {
3013                     return EI.UserTE == TE->UserTreeIndices.front().UserTE;
3014                   }) ||
3015           !Visited.insert(TE).second) {
3016         Filtered.push_back(TE);
3017         continue;
3018       }
3019       // Build a map between user nodes and their operands order to speedup
3020       // search. The graph currently does not provide this dependency directly.
3021       for (EdgeInfo &EI : TE->UserTreeIndices) {
3022         TreeEntry *UserTE = EI.UserTE;
3023         auto It = Users.find(UserTE);
3024         if (It == Users.end())
3025           It = Users.insert({UserTE, {}}).first;
3026         It->second.emplace_back(EI.EdgeIdx, TE);
3027       }
3028     }
3029     // Erase filtered entries.
3030     for_each(Filtered,
3031              [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
3032     for (const auto &Data : Users) {
3033       // Check that operands are used only in the User node.
3034       SmallVector<TreeEntry *> GatherOps;
3035       if (!CheckOperands(Data, GatherOps)) {
3036         for_each(Data.second,
3037                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3038                    OrderedEntries.remove(Op.second);
3039                  });
3040         continue;
3041       }
3042       // All operands are reordered and used only in this node - propagate the
3043       // most used order to the user node.
3044       MapVector<OrdersType, unsigned,
3045                 DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
3046           OrdersUses;
3047       SmallPtrSet<const TreeEntry *, 4> VisitedOps;
3048       for (const auto &Op : Data.second) {
3049         TreeEntry *OpTE = Op.second;
3050         if (!OpTE->ReuseShuffleIndices.empty() ||
3051             (IgnoreReorder && OpTE == VectorizableTree.front().get()))
3052           continue;
3053         const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
3054           if (OpTE->State == TreeEntry::NeedToGather)
3055             return GathersToOrders.find(OpTE)->second;
3056           return OpTE->ReorderIndices;
3057         }();
3058         // Stores actually store the mask, not the order, need to invert.
3059         if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
3060             OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
3061           SmallVector<int> Mask;
3062           inversePermutation(Order, Mask);
3063           unsigned E = Order.size();
3064           OrdersType CurrentOrder(E, E);
3065           transform(Mask, CurrentOrder.begin(), [E](int Idx) {
3066             return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
3067           });
3068           fixupOrderingIndices(CurrentOrder);
3069           ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
3070         } else {
3071           ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
3072         }
3073         if (VisitedOps.insert(OpTE).second)
3074           OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
3075               OpTE->UserTreeIndices.size();
3076         assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0.");
3077         --OrdersUses[{}];
3078       }
3079       // If no orders - skip current nodes and jump to the next one, if any.
3080       if (OrdersUses.empty()) {
3081         for_each(Data.second,
3082                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3083                    OrderedEntries.remove(Op.second);
3084                  });
3085         continue;
3086       }
3087       // Choose the best order.
3088       ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
3089       unsigned Cnt = OrdersUses.front().second;
3090       for (const auto &Pair : drop_begin(OrdersUses)) {
3091         if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
3092           BestOrder = Pair.first;
3093           Cnt = Pair.second;
3094         }
3095       }
3096       // Set order of the user node (reordering of operands and user nodes).
3097       if (BestOrder.empty()) {
3098         for_each(Data.second,
3099                  [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
3100                    OrderedEntries.remove(Op.second);
3101                  });
3102         continue;
3103       }
3104       // Erase operands from OrderedEntries list and adjust their orders.
3105       VisitedOps.clear();
3106       SmallVector<int> Mask;
3107       inversePermutation(BestOrder, Mask);
3108       SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
3109       unsigned E = BestOrder.size();
3110       transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
3111         return I < E ? static_cast<int>(I) : UndefMaskElem;
3112       });
3113       for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
3114         TreeEntry *TE = Op.second;
3115         OrderedEntries.remove(TE);
3116         if (!VisitedOps.insert(TE).second)
3117           continue;
3118         if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
3119           // Just reorder reuses indices.
3120           reorderReuses(TE->ReuseShuffleIndices, Mask);
3121           continue;
3122         }
3123         // Gathers are processed separately.
3124         if (TE->State != TreeEntry::Vectorize)
3125           continue;
3126         assert((BestOrder.size() == TE->ReorderIndices.size() ||
3127                 TE->ReorderIndices.empty()) &&
3128                "Non-matching sizes of user/operand entries.");
3129         reorderOrder(TE->ReorderIndices, Mask);
3130       }
3131       // For gathers just need to reorder its scalars.
3132       for (TreeEntry *Gather : GatherOps) {
3133         assert(Gather->ReorderIndices.empty() &&
3134                "Unexpected reordering of gathers.");
3135         if (!Gather->ReuseShuffleIndices.empty()) {
3136           // Just reorder reuses indices.
3137           reorderReuses(Gather->ReuseShuffleIndices, Mask);
3138           continue;
3139         }
3140         reorderScalars(Gather->Scalars, Mask);
3141         OrderedEntries.remove(Gather);
3142       }
3143       // Reorder operands of the user node and set the ordering for the user
3144       // node itself.
3145       if (Data.first->State != TreeEntry::Vectorize ||
3146           !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
3147               Data.first->getMainOp()) ||
3148           Data.first->isAltShuffle())
3149         Data.first->reorderOperands(Mask);
3150       if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
3151           Data.first->isAltShuffle()) {
3152         reorderScalars(Data.first->Scalars, Mask);
3153         reorderOrder(Data.first->ReorderIndices, MaskOrder);
3154         if (Data.first->ReuseShuffleIndices.empty() &&
3155             !Data.first->ReorderIndices.empty() &&
3156             !Data.first->isAltShuffle()) {
3157           // Insert user node to the list to try to sink reordering deeper in
3158           // the graph.
3159           OrderedEntries.insert(Data.first);
3160         }
3161       } else {
3162         reorderOrder(Data.first->ReorderIndices, Mask);
3163       }
3164     }
3165   }
3166   // If the reordering is unnecessary, just remove the reorder.
3167   if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
3168       VectorizableTree.front()->ReuseShuffleIndices.empty())
3169     VectorizableTree.front()->ReorderIndices.clear();
3170 }
3171 
3172 void BoUpSLP::buildExternalUses(
3173     const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3174   // Collect the values that we need to extract from the tree.
3175   for (auto &TEPtr : VectorizableTree) {
3176     TreeEntry *Entry = TEPtr.get();
3177 
3178     // No need to handle users of gathered values.
3179     if (Entry->State == TreeEntry::NeedToGather)
3180       continue;
3181 
3182     // For each lane:
3183     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3184       Value *Scalar = Entry->Scalars[Lane];
3185       int FoundLane = Entry->findLaneForValue(Scalar);
3186 
3187       // Check if the scalar is externally used as an extra arg.
3188       auto ExtI = ExternallyUsedValues.find(Scalar);
3189       if (ExtI != ExternallyUsedValues.end()) {
3190         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
3191                           << Lane << " from " << *Scalar << ".\n");
3192         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
3193       }
3194       for (User *U : Scalar->users()) {
3195         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
3196 
3197         Instruction *UserInst = dyn_cast<Instruction>(U);
3198         if (!UserInst)
3199           continue;
3200 
3201         if (isDeleted(UserInst))
3202           continue;
3203 
3204         // Skip in-tree scalars that become vectors
3205         if (TreeEntry *UseEntry = getTreeEntry(U)) {
3206           Value *UseScalar = UseEntry->Scalars[0];
3207           // Some in-tree scalars will remain as scalar in vectorized
3208           // instructions. If that is the case, the one in Lane 0 will
3209           // be used.
3210           if (UseScalar != U ||
3211               UseEntry->State == TreeEntry::ScatterVectorize ||
3212               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
3213             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
3214                               << ".\n");
3215             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
3216             continue;
3217           }
3218         }
3219 
3220         // Ignore users in the user ignore list.
3221         if (is_contained(UserIgnoreList, UserInst))
3222           continue;
3223 
3224         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
3225                           << Lane << " from " << *Scalar << ".\n");
3226         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
3227       }
3228     }
3229   }
3230 }
3231 
3232 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
3233                         ArrayRef<Value *> UserIgnoreLst) {
3234   deleteTree();
3235   UserIgnoreList = UserIgnoreLst;
3236   if (!allSameType(Roots))
3237     return;
3238   buildTree_rec(Roots, 0, EdgeInfo());
3239 }
3240 
3241 namespace {
3242 /// Tracks the state we can represent the loads in the given sequence.
3243 enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3244 } // anonymous namespace
3245 
3246 /// Checks if the given array of loads can be represented as a vectorized,
3247 /// scatter or just simple gather.
3248 static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3249                                     const TargetTransformInfo &TTI,
3250                                     const DataLayout &DL, ScalarEvolution &SE,
3251                                     SmallVectorImpl<unsigned> &Order,
3252                                     SmallVectorImpl<Value *> &PointerOps) {
3253   // Check that a vectorized load would load the same memory as a scalar
3254   // load. For example, we don't want to vectorize loads that are smaller
3255   // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3256   // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3257   // from such a struct, we read/write packed bits disagreeing with the
3258   // unvectorized version.
3259   Type *ScalarTy = VL0->getType();
3260 
3261   if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3262     return LoadsState::Gather;
3263 
3264   // Make sure all loads in the bundle are simple - we can't vectorize
3265   // atomic or volatile loads.
3266   PointerOps.clear();
3267   PointerOps.resize(VL.size());
3268   auto *POIter = PointerOps.begin();
3269   for (Value *V : VL) {
3270     auto *L = cast<LoadInst>(V);
3271     if (!L->isSimple())
3272       return LoadsState::Gather;
3273     *POIter = L->getPointerOperand();
3274     ++POIter;
3275   }
3276 
3277   Order.clear();
3278   // Check the order of pointer operands.
3279   if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
3280     Value *Ptr0;
3281     Value *PtrN;
3282     if (Order.empty()) {
3283       Ptr0 = PointerOps.front();
3284       PtrN = PointerOps.back();
3285     } else {
3286       Ptr0 = PointerOps[Order.front()];
3287       PtrN = PointerOps[Order.back()];
3288     }
3289     Optional<int> Diff =
3290         getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3291     // Check that the sorted loads are consecutive.
3292     if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3293       return LoadsState::Vectorize;
3294     Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3295     for (Value *V : VL)
3296       CommonAlignment =
3297           commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
3298     if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
3299                                 CommonAlignment))
3300       return LoadsState::ScatterVectorize;
3301   }
3302 
3303   return LoadsState::Gather;
3304 }
3305 
3306 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
3307                             const EdgeInfo &UserTreeIdx) {
3308   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
3309 
3310   SmallVector<int> ReuseShuffleIndicies;
3311   SmallVector<Value *> UniqueValues;
3312   auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
3313                                 &UserTreeIdx,
3314                                 this](const InstructionsState &S) {
3315     // Check that every instruction appears once in this bundle.
3316     DenseMap<Value *, unsigned> UniquePositions;
3317     for (Value *V : VL) {
3318       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
3319       ReuseShuffleIndicies.emplace_back(isa<UndefValue>(V) ? -1
3320                                                            : Res.first->second);
3321       if (Res.second)
3322         UniqueValues.emplace_back(V);
3323     }
3324     size_t NumUniqueScalarValues = UniqueValues.size();
3325     if (NumUniqueScalarValues == VL.size()) {
3326       ReuseShuffleIndicies.clear();
3327     } else {
3328       LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
3329       if (NumUniqueScalarValues <= 1 ||
3330           !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
3331         LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
3332         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3333         return false;
3334       }
3335       VL = UniqueValues;
3336     }
3337     return true;
3338   };
3339 
3340   InstructionsState S = getSameOpcode(VL);
3341   if (Depth == RecursionMaxDepth) {
3342     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
3343     if (TryToFindDuplicates(S))
3344       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3345                    ReuseShuffleIndicies);
3346     return;
3347   }
3348 
3349   // Don't handle scalable vectors
3350   if (S.getOpcode() == Instruction::ExtractElement &&
3351       isa<ScalableVectorType>(
3352           cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
3353     LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
3354     if (TryToFindDuplicates(S))
3355       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3356                    ReuseShuffleIndicies);
3357     return;
3358   }
3359 
3360   // Don't handle vectors.
3361   if (S.OpValue->getType()->isVectorTy() &&
3362       !isa<InsertElementInst>(S.OpValue)) {
3363     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
3364     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3365     return;
3366   }
3367 
3368   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
3369     if (SI->getValueOperand()->getType()->isVectorTy()) {
3370       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
3371       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3372       return;
3373     }
3374 
3375   // If all of the operands are identical or constant we have a simple solution.
3376   // If we deal with insert/extract instructions, they all must have constant
3377   // indices, otherwise we should gather them, not try to vectorize.
3378   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
3379       (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
3380        !all_of(VL, isVectorLikeInstWithConstOps))) {
3381     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
3382     if (TryToFindDuplicates(S))
3383       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3384                    ReuseShuffleIndicies);
3385     return;
3386   }
3387 
3388   // We now know that this is a vector of instructions of the same type from
3389   // the same block.
3390 
3391   // Don't vectorize ephemeral values.
3392   for (Value *V : VL) {
3393     if (EphValues.count(V)) {
3394       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3395                         << ") is ephemeral.\n");
3396       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3397       return;
3398     }
3399   }
3400 
3401   // Check if this is a duplicate of another entry.
3402   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
3403     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
3404     if (!E->isSame(VL)) {
3405       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
3406       if (TryToFindDuplicates(S))
3407         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3408                      ReuseShuffleIndicies);
3409       return;
3410     }
3411     // Record the reuse of the tree node.  FIXME, currently this is only used to
3412     // properly draw the graph rather than for the actual vectorization.
3413     E->UserTreeIndices.push_back(UserTreeIdx);
3414     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
3415                       << ".\n");
3416     return;
3417   }
3418 
3419   // Check that none of the instructions in the bundle are already in the tree.
3420   for (Value *V : VL) {
3421     auto *I = dyn_cast<Instruction>(V);
3422     if (!I)
3423       continue;
3424     if (getTreeEntry(I)) {
3425       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
3426                         << ") is already in tree.\n");
3427       if (TryToFindDuplicates(S))
3428         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3429                      ReuseShuffleIndicies);
3430       return;
3431     }
3432   }
3433 
3434   // If any of the scalars is marked as a value that needs to stay scalar, then
3435   // we need to gather the scalars.
3436   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
3437   for (Value *V : VL) {
3438     if (MustGather.count(V) || is_contained(UserIgnoreList, V)) {
3439       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
3440       if (TryToFindDuplicates(S))
3441         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3442                      ReuseShuffleIndicies);
3443       return;
3444     }
3445   }
3446 
3447   // Check that all of the users of the scalars that we want to vectorize are
3448   // schedulable.
3449   auto *VL0 = cast<Instruction>(S.OpValue);
3450   BasicBlock *BB = VL0->getParent();
3451 
3452   if (!DT->isReachableFromEntry(BB)) {
3453     // Don't go into unreachable blocks. They may contain instructions with
3454     // dependency cycles which confuse the final scheduling.
3455     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
3456     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3457     return;
3458   }
3459 
3460   // Check that every instruction appears once in this bundle.
3461   if (!TryToFindDuplicates(S))
3462     return;
3463 
3464   auto &BSRef = BlocksSchedules[BB];
3465   if (!BSRef)
3466     BSRef = std::make_unique<BlockScheduling>(BB);
3467 
3468   BlockScheduling &BS = *BSRef.get();
3469 
3470   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
3471   if (!Bundle) {
3472     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
3473     assert((!BS.getScheduleData(VL0) ||
3474             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
3475            "tryScheduleBundle should cancelScheduling on failure");
3476     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3477                  ReuseShuffleIndicies);
3478     return;
3479   }
3480   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
3481 
3482   unsigned ShuffleOrOp = S.isAltShuffle() ?
3483                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
3484   switch (ShuffleOrOp) {
3485     case Instruction::PHI: {
3486       auto *PH = cast<PHINode>(VL0);
3487 
3488       // Check for terminator values (e.g. invoke).
3489       for (Value *V : VL)
3490         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3491           Instruction *Term = dyn_cast<Instruction>(
3492               cast<PHINode>(V)->getIncomingValueForBlock(
3493                   PH->getIncomingBlock(I)));
3494           if (Term && Term->isTerminator()) {
3495             LLVM_DEBUG(dbgs()
3496                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
3497             BS.cancelScheduling(VL, VL0);
3498             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3499                          ReuseShuffleIndicies);
3500             return;
3501           }
3502         }
3503 
3504       TreeEntry *TE =
3505           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
3506       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
3507 
3508       // Keeps the reordered operands to avoid code duplication.
3509       SmallVector<ValueList, 2> OperandsVec;
3510       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
3511         if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
3512           ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
3513           TE->setOperand(I, Operands);
3514           OperandsVec.push_back(Operands);
3515           continue;
3516         }
3517         ValueList Operands;
3518         // Prepare the operand vector.
3519         for (Value *V : VL)
3520           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
3521               PH->getIncomingBlock(I)));
3522         TE->setOperand(I, Operands);
3523         OperandsVec.push_back(Operands);
3524       }
3525       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
3526         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
3527       return;
3528     }
3529     case Instruction::ExtractValue:
3530     case Instruction::ExtractElement: {
3531       OrdersType CurrentOrder;
3532       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
3533       if (Reuse) {
3534         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
3535         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3536                      ReuseShuffleIndicies);
3537         // This is a special case, as it does not gather, but at the same time
3538         // we are not extending buildTree_rec() towards the operands.
3539         ValueList Op0;
3540         Op0.assign(VL.size(), VL0->getOperand(0));
3541         VectorizableTree.back()->setOperand(0, Op0);
3542         return;
3543       }
3544       if (!CurrentOrder.empty()) {
3545         LLVM_DEBUG({
3546           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
3547                     "with order";
3548           for (unsigned Idx : CurrentOrder)
3549             dbgs() << " " << Idx;
3550           dbgs() << "\n";
3551         });
3552         fixupOrderingIndices(CurrentOrder);
3553         // Insert new order with initial value 0, if it does not exist,
3554         // otherwise return the iterator to the existing one.
3555         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3556                      ReuseShuffleIndicies, CurrentOrder);
3557         // This is a special case, as it does not gather, but at the same time
3558         // we are not extending buildTree_rec() towards the operands.
3559         ValueList Op0;
3560         Op0.assign(VL.size(), VL0->getOperand(0));
3561         VectorizableTree.back()->setOperand(0, Op0);
3562         return;
3563       }
3564       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
3565       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3566                    ReuseShuffleIndicies);
3567       BS.cancelScheduling(VL, VL0);
3568       return;
3569     }
3570     case Instruction::InsertElement: {
3571       assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
3572 
3573       // Check that we have a buildvector and not a shuffle of 2 or more
3574       // different vectors.
3575       ValueSet SourceVectors;
3576       int MinIdx = std::numeric_limits<int>::max();
3577       for (Value *V : VL) {
3578         SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
3579         Optional<int> Idx = *getInsertIndex(V, 0);
3580         if (!Idx || *Idx == UndefMaskElem)
3581           continue;
3582         MinIdx = std::min(MinIdx, *Idx);
3583       }
3584 
3585       if (count_if(VL, [&SourceVectors](Value *V) {
3586             return !SourceVectors.contains(V);
3587           }) >= 2) {
3588         // Found 2nd source vector - cancel.
3589         LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
3590                              "different source vectors.\n");
3591         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
3592         BS.cancelScheduling(VL, VL0);
3593         return;
3594       }
3595 
3596       auto OrdCompare = [](const std::pair<int, int> &P1,
3597                            const std::pair<int, int> &P2) {
3598         return P1.first > P2.first;
3599       };
3600       PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
3601                     decltype(OrdCompare)>
3602           Indices(OrdCompare);
3603       for (int I = 0, E = VL.size(); I < E; ++I) {
3604         Optional<int> Idx = *getInsertIndex(VL[I], 0);
3605         if (!Idx || *Idx == UndefMaskElem)
3606           continue;
3607         Indices.emplace(*Idx, I);
3608       }
3609       OrdersType CurrentOrder(VL.size(), VL.size());
3610       bool IsIdentity = true;
3611       for (int I = 0, E = VL.size(); I < E; ++I) {
3612         CurrentOrder[Indices.top().second] = I;
3613         IsIdentity &= Indices.top().second == I;
3614         Indices.pop();
3615       }
3616       if (IsIdentity)
3617         CurrentOrder.clear();
3618       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3619                                    None, CurrentOrder);
3620       LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
3621 
3622       constexpr int NumOps = 2;
3623       ValueList VectorOperands[NumOps];
3624       for (int I = 0; I < NumOps; ++I) {
3625         for (Value *V : VL)
3626           VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
3627 
3628         TE->setOperand(I, VectorOperands[I]);
3629       }
3630       buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
3631       return;
3632     }
3633     case Instruction::Load: {
3634       // Check that a vectorized load would load the same memory as a scalar
3635       // load. For example, we don't want to vectorize loads that are smaller
3636       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3637       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3638       // from such a struct, we read/write packed bits disagreeing with the
3639       // unvectorized version.
3640       SmallVector<Value *> PointerOps;
3641       OrdersType CurrentOrder;
3642       TreeEntry *TE = nullptr;
3643       switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
3644                                 PointerOps)) {
3645       case LoadsState::Vectorize:
3646         if (CurrentOrder.empty()) {
3647           // Original loads are consecutive and does not require reordering.
3648           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3649                             ReuseShuffleIndicies);
3650           LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
3651         } else {
3652           fixupOrderingIndices(CurrentOrder);
3653           // Need to reorder.
3654           TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3655                             ReuseShuffleIndicies, CurrentOrder);
3656           LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
3657         }
3658         TE->setOperandsInOrder();
3659         break;
3660       case LoadsState::ScatterVectorize:
3661         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
3662         TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
3663                           UserTreeIdx, ReuseShuffleIndicies);
3664         TE->setOperandsInOrder();
3665         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
3666         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
3667         break;
3668       case LoadsState::Gather:
3669         BS.cancelScheduling(VL, VL0);
3670         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3671                      ReuseShuffleIndicies);
3672 #ifndef NDEBUG
3673         Type *ScalarTy = VL0->getType();
3674         if (DL->getTypeSizeInBits(ScalarTy) !=
3675             DL->getTypeAllocSizeInBits(ScalarTy))
3676           LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
3677         else if (any_of(VL, [](Value *V) {
3678                    return !cast<LoadInst>(V)->isSimple();
3679                  }))
3680           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
3681         else
3682           LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
3683 #endif // NDEBUG
3684         break;
3685       }
3686       return;
3687     }
3688     case Instruction::ZExt:
3689     case Instruction::SExt:
3690     case Instruction::FPToUI:
3691     case Instruction::FPToSI:
3692     case Instruction::FPExt:
3693     case Instruction::PtrToInt:
3694     case Instruction::IntToPtr:
3695     case Instruction::SIToFP:
3696     case Instruction::UIToFP:
3697     case Instruction::Trunc:
3698     case Instruction::FPTrunc:
3699     case Instruction::BitCast: {
3700       Type *SrcTy = VL0->getOperand(0)->getType();
3701       for (Value *V : VL) {
3702         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
3703         if (Ty != SrcTy || !isValidElementType(Ty)) {
3704           BS.cancelScheduling(VL, VL0);
3705           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3706                        ReuseShuffleIndicies);
3707           LLVM_DEBUG(dbgs()
3708                      << "SLP: Gathering casts with different src types.\n");
3709           return;
3710         }
3711       }
3712       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3713                                    ReuseShuffleIndicies);
3714       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
3715 
3716       TE->setOperandsInOrder();
3717       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3718         ValueList Operands;
3719         // Prepare the operand vector.
3720         for (Value *V : VL)
3721           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3722 
3723         buildTree_rec(Operands, Depth + 1, {TE, i});
3724       }
3725       return;
3726     }
3727     case Instruction::ICmp:
3728     case Instruction::FCmp: {
3729       // Check that all of the compares have the same predicate.
3730       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
3731       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
3732       Type *ComparedTy = VL0->getOperand(0)->getType();
3733       for (Value *V : VL) {
3734         CmpInst *Cmp = cast<CmpInst>(V);
3735         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
3736             Cmp->getOperand(0)->getType() != ComparedTy) {
3737           BS.cancelScheduling(VL, VL0);
3738           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3739                        ReuseShuffleIndicies);
3740           LLVM_DEBUG(dbgs()
3741                      << "SLP: Gathering cmp with different predicate.\n");
3742           return;
3743         }
3744       }
3745 
3746       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3747                                    ReuseShuffleIndicies);
3748       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
3749 
3750       ValueList Left, Right;
3751       if (cast<CmpInst>(VL0)->isCommutative()) {
3752         // Commutative predicate - collect + sort operands of the instructions
3753         // so that each side is more likely to have the same opcode.
3754         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
3755         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3756       } else {
3757         // Collect operands - commute if it uses the swapped predicate.
3758         for (Value *V : VL) {
3759           auto *Cmp = cast<CmpInst>(V);
3760           Value *LHS = Cmp->getOperand(0);
3761           Value *RHS = Cmp->getOperand(1);
3762           if (Cmp->getPredicate() != P0)
3763             std::swap(LHS, RHS);
3764           Left.push_back(LHS);
3765           Right.push_back(RHS);
3766         }
3767       }
3768       TE->setOperand(0, Left);
3769       TE->setOperand(1, Right);
3770       buildTree_rec(Left, Depth + 1, {TE, 0});
3771       buildTree_rec(Right, Depth + 1, {TE, 1});
3772       return;
3773     }
3774     case Instruction::Select:
3775     case Instruction::FNeg:
3776     case Instruction::Add:
3777     case Instruction::FAdd:
3778     case Instruction::Sub:
3779     case Instruction::FSub:
3780     case Instruction::Mul:
3781     case Instruction::FMul:
3782     case Instruction::UDiv:
3783     case Instruction::SDiv:
3784     case Instruction::FDiv:
3785     case Instruction::URem:
3786     case Instruction::SRem:
3787     case Instruction::FRem:
3788     case Instruction::Shl:
3789     case Instruction::LShr:
3790     case Instruction::AShr:
3791     case Instruction::And:
3792     case Instruction::Or:
3793     case Instruction::Xor: {
3794       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3795                                    ReuseShuffleIndicies);
3796       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
3797 
3798       // Sort operands of the instructions so that each side is more likely to
3799       // have the same opcode.
3800       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
3801         ValueList Left, Right;
3802         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3803         TE->setOperand(0, Left);
3804         TE->setOperand(1, Right);
3805         buildTree_rec(Left, Depth + 1, {TE, 0});
3806         buildTree_rec(Right, Depth + 1, {TE, 1});
3807         return;
3808       }
3809 
3810       TE->setOperandsInOrder();
3811       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3812         ValueList Operands;
3813         // Prepare the operand vector.
3814         for (Value *V : VL)
3815           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3816 
3817         buildTree_rec(Operands, Depth + 1, {TE, i});
3818       }
3819       return;
3820     }
3821     case Instruction::GetElementPtr: {
3822       // We don't combine GEPs with complicated (nested) indexing.
3823       for (Value *V : VL) {
3824         if (cast<Instruction>(V)->getNumOperands() != 2) {
3825           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
3826           BS.cancelScheduling(VL, VL0);
3827           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3828                        ReuseShuffleIndicies);
3829           return;
3830         }
3831       }
3832 
3833       // We can't combine several GEPs into one vector if they operate on
3834       // different types.
3835       Type *Ty0 = VL0->getOperand(0)->getType();
3836       for (Value *V : VL) {
3837         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
3838         if (Ty0 != CurTy) {
3839           LLVM_DEBUG(dbgs()
3840                      << "SLP: not-vectorizable GEP (different types).\n");
3841           BS.cancelScheduling(VL, VL0);
3842           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3843                        ReuseShuffleIndicies);
3844           return;
3845         }
3846       }
3847 
3848       // We don't combine GEPs with non-constant indexes.
3849       Type *Ty1 = VL0->getOperand(1)->getType();
3850       for (Value *V : VL) {
3851         auto Op = cast<Instruction>(V)->getOperand(1);
3852         if (!isa<ConstantInt>(Op) ||
3853             (Op->getType() != Ty1 &&
3854              Op->getType()->getScalarSizeInBits() >
3855                  DL->getIndexSizeInBits(
3856                      V->getType()->getPointerAddressSpace()))) {
3857           LLVM_DEBUG(dbgs()
3858                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
3859           BS.cancelScheduling(VL, VL0);
3860           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3861                        ReuseShuffleIndicies);
3862           return;
3863         }
3864       }
3865 
3866       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3867                                    ReuseShuffleIndicies);
3868       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
3869       TE->setOperandsInOrder();
3870       for (unsigned i = 0, e = 2; i < e; ++i) {
3871         ValueList Operands;
3872         // Prepare the operand vector.
3873         for (Value *V : VL)
3874           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3875 
3876         buildTree_rec(Operands, Depth + 1, {TE, i});
3877       }
3878       return;
3879     }
3880     case Instruction::Store: {
3881       // Check if the stores are consecutive or if we need to swizzle them.
3882       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
3883       // Avoid types that are padded when being allocated as scalars, while
3884       // being packed together in a vector (such as i1).
3885       if (DL->getTypeSizeInBits(ScalarTy) !=
3886           DL->getTypeAllocSizeInBits(ScalarTy)) {
3887         BS.cancelScheduling(VL, VL0);
3888         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3889                      ReuseShuffleIndicies);
3890         LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
3891         return;
3892       }
3893       // Make sure all stores in the bundle are simple - we can't vectorize
3894       // atomic or volatile stores.
3895       SmallVector<Value *, 4> PointerOps(VL.size());
3896       ValueList Operands(VL.size());
3897       auto POIter = PointerOps.begin();
3898       auto OIter = Operands.begin();
3899       for (Value *V : VL) {
3900         auto *SI = cast<StoreInst>(V);
3901         if (!SI->isSimple()) {
3902           BS.cancelScheduling(VL, VL0);
3903           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3904                        ReuseShuffleIndicies);
3905           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
3906           return;
3907         }
3908         *POIter = SI->getPointerOperand();
3909         *OIter = SI->getValueOperand();
3910         ++POIter;
3911         ++OIter;
3912       }
3913 
3914       OrdersType CurrentOrder;
3915       // Check the order of pointer operands.
3916       if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
3917         Value *Ptr0;
3918         Value *PtrN;
3919         if (CurrentOrder.empty()) {
3920           Ptr0 = PointerOps.front();
3921           PtrN = PointerOps.back();
3922         } else {
3923           Ptr0 = PointerOps[CurrentOrder.front()];
3924           PtrN = PointerOps[CurrentOrder.back()];
3925         }
3926         Optional<int> Dist =
3927             getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
3928         // Check that the sorted pointer operands are consecutive.
3929         if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
3930           if (CurrentOrder.empty()) {
3931             // Original stores are consecutive and does not require reordering.
3932             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
3933                                          UserTreeIdx, ReuseShuffleIndicies);
3934             TE->setOperandsInOrder();
3935             buildTree_rec(Operands, Depth + 1, {TE, 0});
3936             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
3937           } else {
3938             fixupOrderingIndices(CurrentOrder);
3939             TreeEntry *TE =
3940                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3941                              ReuseShuffleIndicies, CurrentOrder);
3942             TE->setOperandsInOrder();
3943             buildTree_rec(Operands, Depth + 1, {TE, 0});
3944             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
3945           }
3946           return;
3947         }
3948       }
3949 
3950       BS.cancelScheduling(VL, VL0);
3951       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3952                    ReuseShuffleIndicies);
3953       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
3954       return;
3955     }
3956     case Instruction::Call: {
3957       // Check if the calls are all to the same vectorizable intrinsic or
3958       // library function.
3959       CallInst *CI = cast<CallInst>(VL0);
3960       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3961 
3962       VFShape Shape = VFShape::get(
3963           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
3964           false /*HasGlobalPred*/);
3965       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3966 
3967       if (!VecFunc && !isTriviallyVectorizable(ID)) {
3968         BS.cancelScheduling(VL, VL0);
3969         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3970                      ReuseShuffleIndicies);
3971         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
3972         return;
3973       }
3974       Function *F = CI->getCalledFunction();
3975       unsigned NumArgs = CI->arg_size();
3976       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
3977       for (unsigned j = 0; j != NumArgs; ++j)
3978         if (hasVectorInstrinsicScalarOpd(ID, j))
3979           ScalarArgs[j] = CI->getArgOperand(j);
3980       for (Value *V : VL) {
3981         CallInst *CI2 = dyn_cast<CallInst>(V);
3982         if (!CI2 || CI2->getCalledFunction() != F ||
3983             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
3984             (VecFunc &&
3985              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
3986             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
3987           BS.cancelScheduling(VL, VL0);
3988           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3989                        ReuseShuffleIndicies);
3990           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
3991                             << "\n");
3992           return;
3993         }
3994         // Some intrinsics have scalar arguments and should be same in order for
3995         // them to be vectorized.
3996         for (unsigned j = 0; j != NumArgs; ++j) {
3997           if (hasVectorInstrinsicScalarOpd(ID, j)) {
3998             Value *A1J = CI2->getArgOperand(j);
3999             if (ScalarArgs[j] != A1J) {
4000               BS.cancelScheduling(VL, VL0);
4001               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4002                            ReuseShuffleIndicies);
4003               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
4004                                 << " argument " << ScalarArgs[j] << "!=" << A1J
4005                                 << "\n");
4006               return;
4007             }
4008           }
4009         }
4010         // Verify that the bundle operands are identical between the two calls.
4011         if (CI->hasOperandBundles() &&
4012             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
4013                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
4014                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
4015           BS.cancelScheduling(VL, VL0);
4016           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4017                        ReuseShuffleIndicies);
4018           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
4019                             << *CI << "!=" << *V << '\n');
4020           return;
4021         }
4022       }
4023 
4024       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4025                                    ReuseShuffleIndicies);
4026       TE->setOperandsInOrder();
4027       for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
4028         ValueList Operands;
4029         // Prepare the operand vector.
4030         for (Value *V : VL) {
4031           auto *CI2 = cast<CallInst>(V);
4032           Operands.push_back(CI2->getArgOperand(i));
4033         }
4034         buildTree_rec(Operands, Depth + 1, {TE, i});
4035       }
4036       return;
4037     }
4038     case Instruction::ShuffleVector: {
4039       // If this is not an alternate sequence of opcode like add-sub
4040       // then do not vectorize this instruction.
4041       if (!S.isAltShuffle()) {
4042         BS.cancelScheduling(VL, VL0);
4043         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4044                      ReuseShuffleIndicies);
4045         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
4046         return;
4047       }
4048       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
4049                                    ReuseShuffleIndicies);
4050       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
4051 
4052       // Reorder operands if reordering would enable vectorization.
4053       if (isa<BinaryOperator>(VL0)) {
4054         ValueList Left, Right;
4055         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
4056         TE->setOperand(0, Left);
4057         TE->setOperand(1, Right);
4058         buildTree_rec(Left, Depth + 1, {TE, 0});
4059         buildTree_rec(Right, Depth + 1, {TE, 1});
4060         return;
4061       }
4062 
4063       TE->setOperandsInOrder();
4064       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
4065         ValueList Operands;
4066         // Prepare the operand vector.
4067         for (Value *V : VL)
4068           Operands.push_back(cast<Instruction>(V)->getOperand(i));
4069 
4070         buildTree_rec(Operands, Depth + 1, {TE, i});
4071       }
4072       return;
4073     }
4074     default:
4075       BS.cancelScheduling(VL, VL0);
4076       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
4077                    ReuseShuffleIndicies);
4078       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
4079       return;
4080   }
4081 }
4082 
4083 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
4084   unsigned N = 1;
4085   Type *EltTy = T;
4086 
4087   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
4088          isa<VectorType>(EltTy)) {
4089     if (auto *ST = dyn_cast<StructType>(EltTy)) {
4090       // Check that struct is homogeneous.
4091       for (const auto *Ty : ST->elements())
4092         if (Ty != *ST->element_begin())
4093           return 0;
4094       N *= ST->getNumElements();
4095       EltTy = *ST->element_begin();
4096     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
4097       N *= AT->getNumElements();
4098       EltTy = AT->getElementType();
4099     } else {
4100       auto *VT = cast<FixedVectorType>(EltTy);
4101       N *= VT->getNumElements();
4102       EltTy = VT->getElementType();
4103     }
4104   }
4105 
4106   if (!isValidElementType(EltTy))
4107     return 0;
4108   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
4109   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
4110     return 0;
4111   return N;
4112 }
4113 
4114 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
4115                               SmallVectorImpl<unsigned> &CurrentOrder) const {
4116   Instruction *E0 = cast<Instruction>(OpValue);
4117   assert(E0->getOpcode() == Instruction::ExtractElement ||
4118          E0->getOpcode() == Instruction::ExtractValue);
4119   assert(E0->getOpcode() == getSameOpcode(VL).getOpcode() && "Invalid opcode");
4120   // Check if all of the extracts come from the same vector and from the
4121   // correct offset.
4122   Value *Vec = E0->getOperand(0);
4123 
4124   CurrentOrder.clear();
4125 
4126   // We have to extract from a vector/aggregate with the same number of elements.
4127   unsigned NElts;
4128   if (E0->getOpcode() == Instruction::ExtractValue) {
4129     const DataLayout &DL = E0->getModule()->getDataLayout();
4130     NElts = canMapToVector(Vec->getType(), DL);
4131     if (!NElts)
4132       return false;
4133     // Check if load can be rewritten as load of vector.
4134     LoadInst *LI = dyn_cast<LoadInst>(Vec);
4135     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
4136       return false;
4137   } else {
4138     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
4139   }
4140 
4141   if (NElts != VL.size())
4142     return false;
4143 
4144   // Check that all of the indices extract from the correct offset.
4145   bool ShouldKeepOrder = true;
4146   unsigned E = VL.size();
4147   // Assign to all items the initial value E + 1 so we can check if the extract
4148   // instruction index was used already.
4149   // Also, later we can check that all the indices are used and we have a
4150   // consecutive access in the extract instructions, by checking that no
4151   // element of CurrentOrder still has value E + 1.
4152   CurrentOrder.assign(E, E + 1);
4153   unsigned I = 0;
4154   for (; I < E; ++I) {
4155     auto *Inst = cast<Instruction>(VL[I]);
4156     if (Inst->getOperand(0) != Vec)
4157       break;
4158     Optional<unsigned> Idx = getExtractIndex(Inst);
4159     if (!Idx)
4160       break;
4161     const unsigned ExtIdx = *Idx;
4162     if (ExtIdx != I) {
4163       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1)
4164         break;
4165       ShouldKeepOrder = false;
4166       CurrentOrder[ExtIdx] = I;
4167     } else {
4168       if (CurrentOrder[I] != E + 1)
4169         break;
4170       CurrentOrder[I] = I;
4171     }
4172   }
4173   if (I < E) {
4174     CurrentOrder.clear();
4175     return false;
4176   }
4177 
4178   return ShouldKeepOrder;
4179 }
4180 
4181 bool BoUpSLP::areAllUsersVectorized(Instruction *I,
4182                                     ArrayRef<Value *> VectorizedVals) const {
4183   return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
4184          llvm::all_of(I->users(), [this](User *U) {
4185            return ScalarToTreeEntry.count(U) > 0;
4186          });
4187 }
4188 
4189 static std::pair<InstructionCost, InstructionCost>
4190 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
4191                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
4192   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4193 
4194   // Calculate the cost of the scalar and vector calls.
4195   SmallVector<Type *, 4> VecTys;
4196   for (Use &Arg : CI->args())
4197     VecTys.push_back(
4198         FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
4199   FastMathFlags FMF;
4200   if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
4201     FMF = FPCI->getFastMathFlags();
4202   SmallVector<const Value *> Arguments(CI->args());
4203   IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
4204                                     dyn_cast<IntrinsicInst>(CI));
4205   auto IntrinsicCost =
4206     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
4207 
4208   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4209                                      VecTy->getNumElements())),
4210                             false /*HasGlobalPred*/);
4211   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
4212   auto LibCost = IntrinsicCost;
4213   if (!CI->isNoBuiltin() && VecFunc) {
4214     // Calculate the cost of the vector library call.
4215     // If the corresponding vector call is cheaper, return its cost.
4216     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
4217                                     TTI::TCK_RecipThroughput);
4218   }
4219   return {IntrinsicCost, LibCost};
4220 }
4221 
4222 /// Compute the cost of creating a vector of type \p VecTy containing the
4223 /// extracted values from \p VL.
4224 static InstructionCost
4225 computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
4226                    TargetTransformInfo::ShuffleKind ShuffleKind,
4227                    ArrayRef<int> Mask, TargetTransformInfo &TTI) {
4228   unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
4229 
4230   if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
4231       VecTy->getNumElements() < NumOfParts)
4232     return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
4233 
4234   bool AllConsecutive = true;
4235   unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
4236   unsigned Idx = -1;
4237   InstructionCost Cost = 0;
4238 
4239   // Process extracts in blocks of EltsPerVector to check if the source vector
4240   // operand can be re-used directly. If not, add the cost of creating a shuffle
4241   // to extract the values into a vector register.
4242   for (auto *V : VL) {
4243     ++Idx;
4244 
4245     // Reached the start of a new vector registers.
4246     if (Idx % EltsPerVector == 0) {
4247       AllConsecutive = true;
4248       continue;
4249     }
4250 
4251     // Check all extracts for a vector register on the target directly
4252     // extract values in order.
4253     unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
4254     unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
4255     AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
4256                       CurrentIdx % EltsPerVector == Idx % EltsPerVector;
4257 
4258     if (AllConsecutive)
4259       continue;
4260 
4261     // Skip all indices, except for the last index per vector block.
4262     if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
4263       continue;
4264 
4265     // If we have a series of extracts which are not consecutive and hence
4266     // cannot re-use the source vector register directly, compute the shuffle
4267     // cost to extract the a vector with EltsPerVector elements.
4268     Cost += TTI.getShuffleCost(
4269         TargetTransformInfo::SK_PermuteSingleSrc,
4270         FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
4271   }
4272   return Cost;
4273 }
4274 
4275 /// Build shuffle mask for shuffle graph entries and lists of main and alternate
4276 /// operations operands.
4277 static void
4278 buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
4279                      ArrayRef<int> ReusesIndices,
4280                      const function_ref<bool(Instruction *)> IsAltOp,
4281                      SmallVectorImpl<int> &Mask,
4282                      SmallVectorImpl<Value *> *OpScalars = nullptr,
4283                      SmallVectorImpl<Value *> *AltScalars = nullptr) {
4284   unsigned Sz = VL.size();
4285   Mask.assign(Sz, UndefMaskElem);
4286   SmallVector<int> OrderMask;
4287   if (!ReorderIndices.empty())
4288     inversePermutation(ReorderIndices, OrderMask);
4289   for (unsigned I = 0; I < Sz; ++I) {
4290     unsigned Idx = I;
4291     if (!ReorderIndices.empty())
4292       Idx = OrderMask[I];
4293     auto *OpInst = cast<Instruction>(VL[Idx]);
4294     if (IsAltOp(OpInst)) {
4295       Mask[I] = Sz + Idx;
4296       if (AltScalars)
4297         AltScalars->push_back(OpInst);
4298     } else {
4299       Mask[I] = Idx;
4300       if (OpScalars)
4301         OpScalars->push_back(OpInst);
4302     }
4303   }
4304   if (!ReusesIndices.empty()) {
4305     SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
4306     transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
4307       return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
4308     });
4309     Mask.swap(NewMask);
4310   }
4311 }
4312 
4313 InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
4314                                       ArrayRef<Value *> VectorizedVals) {
4315   ArrayRef<Value*> VL = E->Scalars;
4316 
4317   Type *ScalarTy = VL[0]->getType();
4318   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4319     ScalarTy = SI->getValueOperand()->getType();
4320   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
4321     ScalarTy = CI->getOperand(0)->getType();
4322   else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
4323     ScalarTy = IE->getOperand(1)->getType();
4324   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4325   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
4326 
4327   // If we have computed a smaller type for the expression, update VecTy so
4328   // that the costs will be accurate.
4329   if (MinBWs.count(VL[0]))
4330     VecTy = FixedVectorType::get(
4331         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
4332   auto *FinalVecTy = VecTy;
4333 
4334   unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size();
4335   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4336   if (NeedToShuffleReuses)
4337     FinalVecTy =
4338         FixedVectorType::get(VecTy->getElementType(), ReuseShuffleNumbers);
4339   // FIXME: it tries to fix a problem with MSVC buildbots.
4340   TargetTransformInfo &TTIRef = *TTI;
4341   auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
4342                                VectorizedVals](InstructionCost &Cost,
4343                                                bool IsGather) {
4344     DenseMap<Value *, int> ExtractVectorsTys;
4345     for (auto *V : VL) {
4346       // If all users of instruction are going to be vectorized and this
4347       // instruction itself is not going to be vectorized, consider this
4348       // instruction as dead and remove its cost from the final cost of the
4349       // vectorized tree.
4350       if (!areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
4351           (IsGather && ScalarToTreeEntry.count(V)))
4352         continue;
4353       auto *EE = cast<ExtractElementInst>(V);
4354       unsigned Idx = *getExtractIndex(EE);
4355       if (TTIRef.getNumberOfParts(VecTy) !=
4356           TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
4357         auto It =
4358             ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
4359         It->getSecond() = std::min<int>(It->second, Idx);
4360       }
4361       // Take credit for instruction that will become dead.
4362       if (EE->hasOneUse()) {
4363         Instruction *Ext = EE->user_back();
4364         if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4365             all_of(Ext->users(),
4366                    [](User *U) { return isa<GetElementPtrInst>(U); })) {
4367           // Use getExtractWithExtendCost() to calculate the cost of
4368           // extractelement/ext pair.
4369           Cost -=
4370               TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
4371                                               EE->getVectorOperandType(), Idx);
4372           // Add back the cost of s|zext which is subtracted separately.
4373           Cost += TTIRef.getCastInstrCost(
4374               Ext->getOpcode(), Ext->getType(), EE->getType(),
4375               TTI::getCastContextHint(Ext), CostKind, Ext);
4376           continue;
4377         }
4378       }
4379       Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
4380                                         EE->getVectorOperandType(), Idx);
4381     }
4382     // Add a cost for subvector extracts/inserts if required.
4383     for (const auto &Data : ExtractVectorsTys) {
4384       auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
4385       unsigned NumElts = VecTy->getNumElements();
4386       if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
4387         unsigned Idx = (Data.second / NumElts) * NumElts;
4388         unsigned EENumElts = EEVTy->getNumElements();
4389         if (Idx + NumElts <= EENumElts) {
4390           Cost +=
4391               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4392                                     EEVTy, None, Idx, VecTy);
4393         } else {
4394           // Need to round up the subvector type vectorization factor to avoid a
4395           // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
4396           // <= EENumElts.
4397           auto *SubVT =
4398               FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
4399           Cost +=
4400               TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
4401                                     EEVTy, None, Idx, SubVT);
4402         }
4403       } else {
4404         Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
4405                                       VecTy, None, 0, EEVTy);
4406       }
4407     }
4408   };
4409   if (E->State == TreeEntry::NeedToGather) {
4410     if (allConstant(VL))
4411       return 0;
4412     if (isa<InsertElementInst>(VL[0]))
4413       return InstructionCost::getInvalid();
4414     SmallVector<int> Mask;
4415     SmallVector<const TreeEntry *> Entries;
4416     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
4417         isGatherShuffledEntry(E, Mask, Entries);
4418     if (Shuffle.hasValue()) {
4419       InstructionCost GatherCost = 0;
4420       if (ShuffleVectorInst::isIdentityMask(Mask)) {
4421         // Perfect match in the graph, will reuse the previously vectorized
4422         // node. Cost is 0.
4423         LLVM_DEBUG(
4424             dbgs()
4425             << "SLP: perfect diamond match for gather bundle that starts with "
4426             << *VL.front() << ".\n");
4427         if (NeedToShuffleReuses)
4428           GatherCost =
4429               TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4430                                   FinalVecTy, E->ReuseShuffleIndices);
4431       } else {
4432         LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
4433                           << " entries for bundle that starts with "
4434                           << *VL.front() << ".\n");
4435         // Detected that instead of gather we can emit a shuffle of single/two
4436         // previously vectorized nodes. Add the cost of the permutation rather
4437         // than gather.
4438         ::addMask(Mask, E->ReuseShuffleIndices);
4439         GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
4440       }
4441       return GatherCost;
4442     }
4443     if (isSplat(VL)) {
4444       // Found the broadcasting of the single scalar, calculate the cost as the
4445       // broadcast.
4446       return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
4447     }
4448     if (E->getOpcode() == Instruction::ExtractElement && allSameType(VL) &&
4449         allSameBlock(VL) &&
4450         !isa<ScalableVectorType>(
4451             cast<ExtractElementInst>(E->getMainOp())->getVectorOperandType())) {
4452       // Check that gather of extractelements can be represented as just a
4453       // shuffle of a single/two vectors the scalars are extracted from.
4454       SmallVector<int> Mask;
4455       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
4456           isFixedVectorShuffle(VL, Mask);
4457       if (ShuffleKind.hasValue()) {
4458         // Found the bunch of extractelement instructions that must be gathered
4459         // into a vector and can be represented as a permutation elements in a
4460         // single input vector or of 2 input vectors.
4461         InstructionCost Cost =
4462             computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
4463         AdjustExtractsCost(Cost, /*IsGather=*/true);
4464         if (NeedToShuffleReuses)
4465           Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
4466                                       FinalVecTy, E->ReuseShuffleIndices);
4467         return Cost;
4468       }
4469     }
4470     InstructionCost ReuseShuffleCost = 0;
4471     if (NeedToShuffleReuses)
4472       ReuseShuffleCost = TTI->getShuffleCost(
4473           TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
4474     // Improve gather cost for gather of loads, if we can group some of the
4475     // loads into vector loads.
4476     if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
4477         !E->isAltShuffle()) {
4478       BoUpSLP::ValueSet VectorizedLoads;
4479       unsigned StartIdx = 0;
4480       unsigned VF = VL.size() / 2;
4481       unsigned VectorizedCnt = 0;
4482       unsigned ScatterVectorizeCnt = 0;
4483       const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
4484       for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
4485         for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
4486              Cnt += VF) {
4487           ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
4488           if (!VectorizedLoads.count(Slice.front()) &&
4489               !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
4490             SmallVector<Value *> PointerOps;
4491             OrdersType CurrentOrder;
4492             LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
4493                                               *SE, CurrentOrder, PointerOps);
4494             switch (LS) {
4495             case LoadsState::Vectorize:
4496             case LoadsState::ScatterVectorize:
4497               // Mark the vectorized loads so that we don't vectorize them
4498               // again.
4499               if (LS == LoadsState::Vectorize)
4500                 ++VectorizedCnt;
4501               else
4502                 ++ScatterVectorizeCnt;
4503               VectorizedLoads.insert(Slice.begin(), Slice.end());
4504               // If we vectorized initial block, no need to try to vectorize it
4505               // again.
4506               if (Cnt == StartIdx)
4507                 StartIdx += VF;
4508               break;
4509             case LoadsState::Gather:
4510               break;
4511             }
4512           }
4513         }
4514         // Check if the whole array was vectorized already - exit.
4515         if (StartIdx >= VL.size())
4516           break;
4517         // Found vectorizable parts - exit.
4518         if (!VectorizedLoads.empty())
4519           break;
4520       }
4521       if (!VectorizedLoads.empty()) {
4522         InstructionCost GatherCost = 0;
4523         // Get the cost for gathered loads.
4524         for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
4525           if (VectorizedLoads.contains(VL[I]))
4526             continue;
4527           GatherCost += getGatherCost(VL.slice(I, VF));
4528         }
4529         // The cost for vectorized loads.
4530         InstructionCost ScalarsCost = 0;
4531         for (Value *V : VectorizedLoads) {
4532           auto *LI = cast<LoadInst>(V);
4533           ScalarsCost += TTI->getMemoryOpCost(
4534               Instruction::Load, LI->getType(), LI->getAlign(),
4535               LI->getPointerAddressSpace(), CostKind, LI);
4536         }
4537         auto *LI = cast<LoadInst>(E->getMainOp());
4538         auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
4539         Align Alignment = LI->getAlign();
4540         GatherCost +=
4541             VectorizedCnt *
4542             TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
4543                                  LI->getPointerAddressSpace(), CostKind, LI);
4544         GatherCost += ScatterVectorizeCnt *
4545                       TTI->getGatherScatterOpCost(
4546                           Instruction::Load, LoadTy, LI->getPointerOperand(),
4547                           /*VariableMask=*/false, Alignment, CostKind, LI);
4548         // Add the cost for the subvectors shuffling.
4549         GatherCost += ((VL.size() - VF) / VF) *
4550                       TTI->getShuffleCost(TTI::SK_Select, VecTy);
4551         return ReuseShuffleCost + GatherCost - ScalarsCost;
4552       }
4553     }
4554     return ReuseShuffleCost + getGatherCost(VL);
4555   }
4556   InstructionCost CommonCost = 0;
4557   SmallVector<int> Mask;
4558   if (!E->ReorderIndices.empty()) {
4559     SmallVector<int> NewMask;
4560     if (E->getOpcode() == Instruction::Store) {
4561       // For stores the order is actually a mask.
4562       NewMask.resize(E->ReorderIndices.size());
4563       copy(E->ReorderIndices, NewMask.begin());
4564     } else {
4565       inversePermutation(E->ReorderIndices, NewMask);
4566     }
4567     ::addMask(Mask, NewMask);
4568   }
4569   if (NeedToShuffleReuses)
4570     ::addMask(Mask, E->ReuseShuffleIndices);
4571   if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
4572     CommonCost =
4573         TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
4574   assert((E->State == TreeEntry::Vectorize ||
4575           E->State == TreeEntry::ScatterVectorize) &&
4576          "Unhandled state");
4577   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
4578   Instruction *VL0 = E->getMainOp();
4579   unsigned ShuffleOrOp =
4580       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
4581   switch (ShuffleOrOp) {
4582     case Instruction::PHI:
4583       return 0;
4584 
4585     case Instruction::ExtractValue:
4586     case Instruction::ExtractElement: {
4587       // The common cost of removal ExtractElement/ExtractValue instructions +
4588       // the cost of shuffles, if required to resuffle the original vector.
4589       if (NeedToShuffleReuses) {
4590         unsigned Idx = 0;
4591         for (unsigned I : E->ReuseShuffleIndices) {
4592           if (ShuffleOrOp == Instruction::ExtractElement) {
4593             auto *EE = cast<ExtractElementInst>(VL[I]);
4594             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4595                                                   EE->getVectorOperandType(),
4596                                                   *getExtractIndex(EE));
4597           } else {
4598             CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
4599                                                   VecTy, Idx);
4600             ++Idx;
4601           }
4602         }
4603         Idx = ReuseShuffleNumbers;
4604         for (Value *V : VL) {
4605           if (ShuffleOrOp == Instruction::ExtractElement) {
4606             auto *EE = cast<ExtractElementInst>(V);
4607             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4608                                                   EE->getVectorOperandType(),
4609                                                   *getExtractIndex(EE));
4610           } else {
4611             --Idx;
4612             CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
4613                                                   VecTy, Idx);
4614           }
4615         }
4616       }
4617       if (ShuffleOrOp == Instruction::ExtractValue) {
4618         for (unsigned I = 0, E = VL.size(); I < E; ++I) {
4619           auto *EI = cast<Instruction>(VL[I]);
4620           // Take credit for instruction that will become dead.
4621           if (EI->hasOneUse()) {
4622             Instruction *Ext = EI->user_back();
4623             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
4624                 all_of(Ext->users(),
4625                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
4626               // Use getExtractWithExtendCost() to calculate the cost of
4627               // extractelement/ext pair.
4628               CommonCost -= TTI->getExtractWithExtendCost(
4629                   Ext->getOpcode(), Ext->getType(), VecTy, I);
4630               // Add back the cost of s|zext which is subtracted separately.
4631               CommonCost += TTI->getCastInstrCost(
4632                   Ext->getOpcode(), Ext->getType(), EI->getType(),
4633                   TTI::getCastContextHint(Ext), CostKind, Ext);
4634               continue;
4635             }
4636           }
4637           CommonCost -=
4638               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
4639         }
4640       } else {
4641         AdjustExtractsCost(CommonCost, /*IsGather=*/false);
4642       }
4643       return CommonCost;
4644     }
4645     case Instruction::InsertElement: {
4646       assert(E->ReuseShuffleIndices.empty() &&
4647              "Unique insertelements only are expected.");
4648       auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
4649 
4650       unsigned const NumElts = SrcVecTy->getNumElements();
4651       unsigned const NumScalars = VL.size();
4652       APInt DemandedElts = APInt::getZero(NumElts);
4653       // TODO: Add support for Instruction::InsertValue.
4654       SmallVector<int> Mask;
4655       if (!E->ReorderIndices.empty()) {
4656         inversePermutation(E->ReorderIndices, Mask);
4657         Mask.append(NumElts - NumScalars, UndefMaskElem);
4658       } else {
4659         Mask.assign(NumElts, UndefMaskElem);
4660         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
4661       }
4662       unsigned Offset = *getInsertIndex(VL0, 0);
4663       bool IsIdentity = true;
4664       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
4665       Mask.swap(PrevMask);
4666       for (unsigned I = 0; I < NumScalars; ++I) {
4667         Optional<int> InsertIdx = getInsertIndex(VL[PrevMask[I]], 0);
4668         if (!InsertIdx || *InsertIdx == UndefMaskElem)
4669           continue;
4670         DemandedElts.setBit(*InsertIdx);
4671         IsIdentity &= *InsertIdx - Offset == I;
4672         Mask[*InsertIdx - Offset] = I;
4673       }
4674       assert(Offset < NumElts && "Failed to find vector index offset");
4675 
4676       InstructionCost Cost = 0;
4677       Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
4678                                             /*Insert*/ true, /*Extract*/ false);
4679 
4680       if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
4681         // FIXME: Replace with SK_InsertSubvector once it is properly supported.
4682         unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
4683         Cost += TTI->getShuffleCost(
4684             TargetTransformInfo::SK_PermuteSingleSrc,
4685             FixedVectorType::get(SrcVecTy->getElementType(), Sz));
4686       } else if (!IsIdentity) {
4687         auto *FirstInsert =
4688             cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
4689               return !is_contained(E->Scalars,
4690                                    cast<Instruction>(V)->getOperand(0));
4691             }));
4692         if (isa<UndefValue>(FirstInsert->getOperand(0))) {
4693           Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
4694         } else {
4695           SmallVector<int> InsertMask(NumElts);
4696           std::iota(InsertMask.begin(), InsertMask.end(), 0);
4697           for (unsigned I = 0; I < NumElts; I++) {
4698             if (Mask[I] != UndefMaskElem)
4699               InsertMask[Offset + I] = NumElts + I;
4700           }
4701           Cost +=
4702               TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
4703         }
4704       }
4705 
4706       return Cost;
4707     }
4708     case Instruction::ZExt:
4709     case Instruction::SExt:
4710     case Instruction::FPToUI:
4711     case Instruction::FPToSI:
4712     case Instruction::FPExt:
4713     case Instruction::PtrToInt:
4714     case Instruction::IntToPtr:
4715     case Instruction::SIToFP:
4716     case Instruction::UIToFP:
4717     case Instruction::Trunc:
4718     case Instruction::FPTrunc:
4719     case Instruction::BitCast: {
4720       Type *SrcTy = VL0->getOperand(0)->getType();
4721       InstructionCost ScalarEltCost =
4722           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
4723                                 TTI::getCastContextHint(VL0), CostKind, VL0);
4724       if (NeedToShuffleReuses) {
4725         CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4726       }
4727 
4728       // Calculate the cost of this instruction.
4729       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
4730 
4731       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
4732       InstructionCost VecCost = 0;
4733       // Check if the values are candidates to demote.
4734       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
4735         VecCost = CommonCost + TTI->getCastInstrCost(
4736                                    E->getOpcode(), VecTy, SrcVecTy,
4737                                    TTI::getCastContextHint(VL0), CostKind, VL0);
4738       }
4739       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4740       return VecCost - ScalarCost;
4741     }
4742     case Instruction::FCmp:
4743     case Instruction::ICmp:
4744     case Instruction::Select: {
4745       // Calculate the cost of this instruction.
4746       InstructionCost ScalarEltCost =
4747           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
4748                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
4749       if (NeedToShuffleReuses) {
4750         CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4751       }
4752       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
4753       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4754 
4755       // Check if all entries in VL are either compares or selects with compares
4756       // as condition that have the same predicates.
4757       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
4758       bool First = true;
4759       for (auto *V : VL) {
4760         CmpInst::Predicate CurrentPred;
4761         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
4762         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
4763              !match(V, MatchCmp)) ||
4764             (!First && VecPred != CurrentPred)) {
4765           VecPred = CmpInst::BAD_ICMP_PREDICATE;
4766           break;
4767         }
4768         First = false;
4769         VecPred = CurrentPred;
4770       }
4771 
4772       InstructionCost VecCost = TTI->getCmpSelInstrCost(
4773           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
4774       // Check if it is possible and profitable to use min/max for selects in
4775       // VL.
4776       //
4777       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
4778       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
4779         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
4780                                           {VecTy, VecTy});
4781         InstructionCost IntrinsicCost =
4782             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
4783         // If the selects are the only uses of the compares, they will be dead
4784         // and we can adjust the cost by removing their cost.
4785         if (IntrinsicAndUse.second)
4786           IntrinsicCost -=
4787               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
4788                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
4789         VecCost = std::min(VecCost, IntrinsicCost);
4790       }
4791       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4792       return CommonCost + VecCost - ScalarCost;
4793     }
4794     case Instruction::FNeg:
4795     case Instruction::Add:
4796     case Instruction::FAdd:
4797     case Instruction::Sub:
4798     case Instruction::FSub:
4799     case Instruction::Mul:
4800     case Instruction::FMul:
4801     case Instruction::UDiv:
4802     case Instruction::SDiv:
4803     case Instruction::FDiv:
4804     case Instruction::URem:
4805     case Instruction::SRem:
4806     case Instruction::FRem:
4807     case Instruction::Shl:
4808     case Instruction::LShr:
4809     case Instruction::AShr:
4810     case Instruction::And:
4811     case Instruction::Or:
4812     case Instruction::Xor: {
4813       // Certain instructions can be cheaper to vectorize if they have a
4814       // constant second vector operand.
4815       TargetTransformInfo::OperandValueKind Op1VK =
4816           TargetTransformInfo::OK_AnyValue;
4817       TargetTransformInfo::OperandValueKind Op2VK =
4818           TargetTransformInfo::OK_UniformConstantValue;
4819       TargetTransformInfo::OperandValueProperties Op1VP =
4820           TargetTransformInfo::OP_None;
4821       TargetTransformInfo::OperandValueProperties Op2VP =
4822           TargetTransformInfo::OP_PowerOf2;
4823 
4824       // If all operands are exactly the same ConstantInt then set the
4825       // operand kind to OK_UniformConstantValue.
4826       // If instead not all operands are constants, then set the operand kind
4827       // to OK_AnyValue. If all operands are constants but not the same,
4828       // then set the operand kind to OK_NonUniformConstantValue.
4829       ConstantInt *CInt0 = nullptr;
4830       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
4831         const Instruction *I = cast<Instruction>(VL[i]);
4832         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
4833         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
4834         if (!CInt) {
4835           Op2VK = TargetTransformInfo::OK_AnyValue;
4836           Op2VP = TargetTransformInfo::OP_None;
4837           break;
4838         }
4839         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
4840             !CInt->getValue().isPowerOf2())
4841           Op2VP = TargetTransformInfo::OP_None;
4842         if (i == 0) {
4843           CInt0 = CInt;
4844           continue;
4845         }
4846         if (CInt0 != CInt)
4847           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
4848       }
4849 
4850       SmallVector<const Value *, 4> Operands(VL0->operand_values());
4851       InstructionCost ScalarEltCost =
4852           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
4853                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
4854       if (NeedToShuffleReuses) {
4855         CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4856       }
4857       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4858       InstructionCost VecCost =
4859           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
4860                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
4861       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4862       return CommonCost + VecCost - ScalarCost;
4863     }
4864     case Instruction::GetElementPtr: {
4865       TargetTransformInfo::OperandValueKind Op1VK =
4866           TargetTransformInfo::OK_AnyValue;
4867       TargetTransformInfo::OperandValueKind Op2VK =
4868           TargetTransformInfo::OK_UniformConstantValue;
4869 
4870       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
4871           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
4872       if (NeedToShuffleReuses) {
4873         CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4874       }
4875       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
4876       InstructionCost VecCost = TTI->getArithmeticInstrCost(
4877           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
4878       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4879       return CommonCost + VecCost - ScalarCost;
4880     }
4881     case Instruction::Load: {
4882       // Cost of wide load - cost of scalar loads.
4883       Align Alignment = cast<LoadInst>(VL0)->getAlign();
4884       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
4885           Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
4886       if (NeedToShuffleReuses) {
4887         CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4888       }
4889       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
4890       InstructionCost VecLdCost;
4891       if (E->State == TreeEntry::Vectorize) {
4892         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
4893                                          CostKind, VL0);
4894       } else {
4895         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
4896         Align CommonAlignment = Alignment;
4897         for (Value *V : VL)
4898           CommonAlignment =
4899               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4900         VecLdCost = TTI->getGatherScatterOpCost(
4901             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
4902             /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
4903       }
4904       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
4905       return CommonCost + VecLdCost - ScalarLdCost;
4906     }
4907     case Instruction::Store: {
4908       // We know that we can merge the stores. Calculate the cost.
4909       bool IsReorder = !E->ReorderIndices.empty();
4910       auto *SI =
4911           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
4912       Align Alignment = SI->getAlign();
4913       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
4914           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
4915       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
4916       InstructionCost VecStCost = TTI->getMemoryOpCost(
4917           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
4918       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
4919       return CommonCost + VecStCost - ScalarStCost;
4920     }
4921     case Instruction::Call: {
4922       CallInst *CI = cast<CallInst>(VL0);
4923       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4924 
4925       // Calculate the cost of the scalar and vector calls.
4926       IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
4927       InstructionCost ScalarEltCost =
4928           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
4929       if (NeedToShuffleReuses) {
4930         CommonCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
4931       }
4932       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
4933 
4934       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
4935       InstructionCost VecCallCost =
4936           std::min(VecCallCosts.first, VecCallCosts.second);
4937 
4938       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
4939                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
4940                         << " for " << *CI << "\n");
4941 
4942       return CommonCost + VecCallCost - ScalarCallCost;
4943     }
4944     case Instruction::ShuffleVector: {
4945       assert(E->isAltShuffle() &&
4946              ((Instruction::isBinaryOp(E->getOpcode()) &&
4947                Instruction::isBinaryOp(E->getAltOpcode())) ||
4948               (Instruction::isCast(E->getOpcode()) &&
4949                Instruction::isCast(E->getAltOpcode()))) &&
4950              "Invalid Shuffle Vector Operand");
4951       InstructionCost ScalarCost = 0;
4952       if (NeedToShuffleReuses) {
4953         for (unsigned Idx : E->ReuseShuffleIndices) {
4954           Instruction *I = cast<Instruction>(VL[Idx]);
4955           CommonCost -= TTI->getInstructionCost(I, CostKind);
4956         }
4957         for (Value *V : VL) {
4958           Instruction *I = cast<Instruction>(V);
4959           CommonCost += TTI->getInstructionCost(I, CostKind);
4960         }
4961       }
4962       for (Value *V : VL) {
4963         Instruction *I = cast<Instruction>(V);
4964         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
4965         ScalarCost += TTI->getInstructionCost(I, CostKind);
4966       }
4967       // VecCost is equal to sum of the cost of creating 2 vectors
4968       // and the cost of creating shuffle.
4969       InstructionCost VecCost = 0;
4970       if (Instruction::isBinaryOp(E->getOpcode())) {
4971         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
4972         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
4973                                                CostKind);
4974       } else {
4975         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
4976         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
4977         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
4978         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
4979         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
4980                                         TTI::CastContextHint::None, CostKind);
4981         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
4982                                          TTI::CastContextHint::None, CostKind);
4983       }
4984 
4985       SmallVector<int> Mask;
4986       buildSuffleEntryMask(
4987           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
4988           [E](Instruction *I) {
4989             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
4990             return I->getOpcode() == E->getAltOpcode();
4991           },
4992           Mask);
4993       CommonCost =
4994           TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
4995       LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
4996       return CommonCost + VecCost - ScalarCost;
4997     }
4998     default:
4999       llvm_unreachable("Unknown instruction");
5000   }
5001 }
5002 
5003 bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
5004   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
5005                     << VectorizableTree.size() << " is fully vectorizable .\n");
5006 
5007   auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
5008     SmallVector<int> Mask;
5009     return TE->State == TreeEntry::NeedToGather &&
5010            !any_of(TE->Scalars,
5011                    [this](Value *V) { return EphValues.contains(V); }) &&
5012            (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
5013             TE->Scalars.size() < Limit ||
5014             (TE->getOpcode() == Instruction::ExtractElement &&
5015              isFixedVectorShuffle(TE->Scalars, Mask)));
5016   };
5017 
5018   // We only handle trees of heights 1 and 2.
5019   if (VectorizableTree.size() == 1 &&
5020       (VectorizableTree[0]->State == TreeEntry::Vectorize ||
5021        (ForReduction &&
5022         AreVectorizableGathers(VectorizableTree[0].get(),
5023                                VectorizableTree[0]->Scalars.size()) &&
5024         (VectorizableTree[0]->Scalars.size() > 2 ||
5025          VectorizableTree[0]->ReuseShuffleIndices.size() > 2))))
5026     return true;
5027 
5028   if (VectorizableTree.size() != 2)
5029     return false;
5030 
5031   // Handle splat and all-constants stores. Also try to vectorize tiny trees
5032   // with the second gather nodes if they have less scalar operands rather than
5033   // the initial tree element (may be profitable to shuffle the second gather)
5034   // or they are extractelements, which form shuffle.
5035   SmallVector<int> Mask;
5036   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
5037       AreVectorizableGathers(VectorizableTree[1].get(),
5038                              VectorizableTree[0]->Scalars.size()))
5039     return true;
5040 
5041   // Gathering cost would be too much for tiny trees.
5042   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
5043       (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
5044        VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
5045     return false;
5046 
5047   return true;
5048 }
5049 
5050 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
5051                                        TargetTransformInfo *TTI,
5052                                        bool MustMatchOrInst) {
5053   // Look past the root to find a source value. Arbitrarily follow the
5054   // path through operand 0 of any 'or'. Also, peek through optional
5055   // shift-left-by-multiple-of-8-bits.
5056   Value *ZextLoad = Root;
5057   const APInt *ShAmtC;
5058   bool FoundOr = false;
5059   while (!isa<ConstantExpr>(ZextLoad) &&
5060          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
5061           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
5062            ShAmtC->urem(8) == 0))) {
5063     auto *BinOp = cast<BinaryOperator>(ZextLoad);
5064     ZextLoad = BinOp->getOperand(0);
5065     if (BinOp->getOpcode() == Instruction::Or)
5066       FoundOr = true;
5067   }
5068   // Check if the input is an extended load of the required or/shift expression.
5069   Value *LoadPtr;
5070   if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
5071       !match(ZextLoad, m_ZExt(m_Load(m_Value(LoadPtr)))))
5072     return false;
5073 
5074   // Require that the total load bit width is a legal integer type.
5075   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
5076   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
5077   Type *SrcTy = LoadPtr->getType()->getPointerElementType();
5078   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
5079   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
5080     return false;
5081 
5082   // Everything matched - assume that we can fold the whole sequence using
5083   // load combining.
5084   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
5085              << *(cast<Instruction>(Root)) << "\n");
5086 
5087   return true;
5088 }
5089 
5090 bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
5091   if (RdxKind != RecurKind::Or)
5092     return false;
5093 
5094   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5095   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
5096   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
5097                                     /* MatchOr */ false);
5098 }
5099 
5100 bool BoUpSLP::isLoadCombineCandidate() const {
5101   // Peek through a final sequence of stores and check if all operations are
5102   // likely to be load-combined.
5103   unsigned NumElts = VectorizableTree[0]->Scalars.size();
5104   for (Value *Scalar : VectorizableTree[0]->Scalars) {
5105     Value *X;
5106     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
5107         !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
5108       return false;
5109   }
5110   return true;
5111 }
5112 
5113 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
5114   // No need to vectorize inserts of gathered values.
5115   if (VectorizableTree.size() == 2 &&
5116       isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
5117       VectorizableTree[1]->State == TreeEntry::NeedToGather)
5118     return true;
5119 
5120   // We can vectorize the tree if its size is greater than or equal to the
5121   // minimum size specified by the MinTreeSize command line option.
5122   if (VectorizableTree.size() >= MinTreeSize)
5123     return false;
5124 
5125   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
5126   // can vectorize it if we can prove it fully vectorizable.
5127   if (isFullyVectorizableTinyTree(ForReduction))
5128     return false;
5129 
5130   assert(VectorizableTree.empty()
5131              ? ExternalUses.empty()
5132              : true && "We shouldn't have any external users");
5133 
5134   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
5135   // vectorizable.
5136   return true;
5137 }
5138 
5139 InstructionCost BoUpSLP::getSpillCost() const {
5140   // Walk from the bottom of the tree to the top, tracking which values are
5141   // live. When we see a call instruction that is not part of our tree,
5142   // query TTI to see if there is a cost to keeping values live over it
5143   // (for example, if spills and fills are required).
5144   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
5145   InstructionCost Cost = 0;
5146 
5147   SmallPtrSet<Instruction*, 4> LiveValues;
5148   Instruction *PrevInst = nullptr;
5149 
5150   // The entries in VectorizableTree are not necessarily ordered by their
5151   // position in basic blocks. Collect them and order them by dominance so later
5152   // instructions are guaranteed to be visited first. For instructions in
5153   // different basic blocks, we only scan to the beginning of the block, so
5154   // their order does not matter, as long as all instructions in a basic block
5155   // are grouped together. Using dominance ensures a deterministic order.
5156   SmallVector<Instruction *, 16> OrderedScalars;
5157   for (const auto &TEPtr : VectorizableTree) {
5158     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
5159     if (!Inst)
5160       continue;
5161     OrderedScalars.push_back(Inst);
5162   }
5163   llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
5164     auto *NodeA = DT->getNode(A->getParent());
5165     auto *NodeB = DT->getNode(B->getParent());
5166     assert(NodeA && "Should only process reachable instructions");
5167     assert(NodeB && "Should only process reachable instructions");
5168     assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
5169            "Different nodes should have different DFS numbers");
5170     if (NodeA != NodeB)
5171       return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
5172     return B->comesBefore(A);
5173   });
5174 
5175   for (Instruction *Inst : OrderedScalars) {
5176     if (!PrevInst) {
5177       PrevInst = Inst;
5178       continue;
5179     }
5180 
5181     // Update LiveValues.
5182     LiveValues.erase(PrevInst);
5183     for (auto &J : PrevInst->operands()) {
5184       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
5185         LiveValues.insert(cast<Instruction>(&*J));
5186     }
5187 
5188     LLVM_DEBUG({
5189       dbgs() << "SLP: #LV: " << LiveValues.size();
5190       for (auto *X : LiveValues)
5191         dbgs() << " " << X->getName();
5192       dbgs() << ", Looking at ";
5193       Inst->dump();
5194     });
5195 
5196     // Now find the sequence of instructions between PrevInst and Inst.
5197     unsigned NumCalls = 0;
5198     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
5199                                  PrevInstIt =
5200                                      PrevInst->getIterator().getReverse();
5201     while (InstIt != PrevInstIt) {
5202       if (PrevInstIt == PrevInst->getParent()->rend()) {
5203         PrevInstIt = Inst->getParent()->rbegin();
5204         continue;
5205       }
5206 
5207       // Debug information does not impact spill cost.
5208       if ((isa<CallInst>(&*PrevInstIt) &&
5209            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
5210           &*PrevInstIt != PrevInst)
5211         NumCalls++;
5212 
5213       ++PrevInstIt;
5214     }
5215 
5216     if (NumCalls) {
5217       SmallVector<Type*, 4> V;
5218       for (auto *II : LiveValues) {
5219         auto *ScalarTy = II->getType();
5220         if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
5221           ScalarTy = VectorTy->getElementType();
5222         V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
5223       }
5224       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
5225     }
5226 
5227     PrevInst = Inst;
5228   }
5229 
5230   return Cost;
5231 }
5232 
5233 InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
5234   InstructionCost Cost = 0;
5235   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
5236                     << VectorizableTree.size() << ".\n");
5237 
5238   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
5239 
5240   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
5241     TreeEntry &TE = *VectorizableTree[I].get();
5242 
5243     InstructionCost C = getEntryCost(&TE, VectorizedVals);
5244     Cost += C;
5245     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5246                       << " for bundle that starts with " << *TE.Scalars[0]
5247                       << ".\n"
5248                       << "SLP: Current total cost = " << Cost << "\n");
5249   }
5250 
5251   SmallPtrSet<Value *, 16> ExtractCostCalculated;
5252   InstructionCost ExtractCost = 0;
5253   SmallVector<unsigned> VF;
5254   SmallVector<SmallVector<int>> ShuffleMask;
5255   SmallVector<Value *> FirstUsers;
5256   SmallVector<APInt> DemandedElts;
5257   for (ExternalUser &EU : ExternalUses) {
5258     // We only add extract cost once for the same scalar.
5259     if (!ExtractCostCalculated.insert(EU.Scalar).second)
5260       continue;
5261 
5262     // Uses by ephemeral values are free (because the ephemeral value will be
5263     // removed prior to code generation, and so the extraction will be
5264     // removed as well).
5265     if (EphValues.count(EU.User))
5266       continue;
5267 
5268     // No extract cost for vector "scalar"
5269     if (isa<FixedVectorType>(EU.Scalar->getType()))
5270       continue;
5271 
5272     // Already counted the cost for external uses when tried to adjust the cost
5273     // for extractelements, no need to add it again.
5274     if (isa<ExtractElementInst>(EU.Scalar))
5275       continue;
5276 
5277     // If found user is an insertelement, do not calculate extract cost but try
5278     // to detect it as a final shuffled/identity match.
5279     if (EU.User && isa<InsertElementInst>(EU.User)) {
5280       if (auto *FTy = dyn_cast<FixedVectorType>(EU.User->getType())) {
5281         Optional<int> InsertIdx = getInsertIndex(EU.User, 0);
5282         if (!InsertIdx || *InsertIdx == UndefMaskElem)
5283           continue;
5284         Value *VU = EU.User;
5285         auto *It = find_if(FirstUsers, [VU](Value *V) {
5286           // Checks if 2 insertelements are from the same buildvector.
5287           if (VU->getType() != V->getType())
5288             return false;
5289           auto *IE1 = cast<InsertElementInst>(VU);
5290           auto *IE2 = cast<InsertElementInst>(V);
5291           // Go though of insertelement instructions trying to find either VU as
5292           // the original vector for IE2 or V as the original vector for IE1.
5293           do {
5294             if (IE1 == VU || IE2 == V)
5295               return true;
5296             if (IE1)
5297               IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
5298             if (IE2)
5299               IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
5300           } while (IE1 || IE2);
5301           return false;
5302         });
5303         int VecId = -1;
5304         if (It == FirstUsers.end()) {
5305           VF.push_back(FTy->getNumElements());
5306           ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
5307           FirstUsers.push_back(EU.User);
5308           DemandedElts.push_back(APInt::getZero(VF.back()));
5309           VecId = FirstUsers.size() - 1;
5310         } else {
5311           VecId = std::distance(FirstUsers.begin(), It);
5312         }
5313         int Idx = *InsertIdx;
5314         ShuffleMask[VecId][Idx] = EU.Lane;
5315         DemandedElts[VecId].setBit(Idx);
5316       }
5317     }
5318 
5319     // If we plan to rewrite the tree in a smaller type, we will need to sign
5320     // extend the extracted value back to the original type. Here, we account
5321     // for the extract and the added cost of the sign extend if needed.
5322     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
5323     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
5324     if (MinBWs.count(ScalarRoot)) {
5325       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
5326       auto Extend =
5327           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
5328       VecTy = FixedVectorType::get(MinTy, BundleWidth);
5329       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
5330                                                    VecTy, EU.Lane);
5331     } else {
5332       ExtractCost +=
5333           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
5334     }
5335   }
5336 
5337   InstructionCost SpillCost = getSpillCost();
5338   Cost += SpillCost + ExtractCost;
5339   for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
5340     // For the very first element - simple shuffle of the source vector.
5341     int Limit = ShuffleMask[I].size() * 2;
5342     if (I == 0 &&
5343         all_of(ShuffleMask[I], [Limit](int Idx) { return Idx < Limit; }) &&
5344         !ShuffleVectorInst::isIdentityMask(ShuffleMask[I])) {
5345       InstructionCost C = TTI->getShuffleCost(
5346           TTI::SK_PermuteSingleSrc,
5347           cast<FixedVectorType>(FirstUsers[I]->getType()), ShuffleMask[I]);
5348       LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
5349                         << " for final shuffle of insertelement external users "
5350                         << *VectorizableTree.front()->Scalars.front() << ".\n"
5351                         << "SLP: Current total cost = " << Cost << "\n");
5352       Cost += C;
5353       continue;
5354     }
5355     // Other elements - permutation of 2 vectors (the initial one and the next
5356     // Ith incoming vector).
5357     unsigned VF = ShuffleMask[I].size();
5358     for (unsigned Idx = 0; Idx < VF; ++Idx) {
5359       int &Mask = ShuffleMask[I][Idx];
5360       Mask = Mask == UndefMaskElem ? Idx : VF + Mask;
5361     }
5362     InstructionCost C = TTI->getShuffleCost(
5363         TTI::SK_PermuteTwoSrc, cast<FixedVectorType>(FirstUsers[I]->getType()),
5364         ShuffleMask[I]);
5365     LLVM_DEBUG(
5366         dbgs()
5367         << "SLP: Adding cost " << C
5368         << " for final shuffle of vector node and external insertelement users "
5369         << *VectorizableTree.front()->Scalars.front() << ".\n"
5370         << "SLP: Current total cost = " << Cost << "\n");
5371     Cost += C;
5372     InstructionCost InsertCost = TTI->getScalarizationOverhead(
5373         cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
5374         /*Insert*/ true,
5375         /*Extract*/ false);
5376     Cost -= InsertCost;
5377     LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
5378                       << " for insertelements gather.\n"
5379                       << "SLP: Current total cost = " << Cost << "\n");
5380   }
5381 
5382 #ifndef NDEBUG
5383   SmallString<256> Str;
5384   {
5385     raw_svector_ostream OS(Str);
5386     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
5387        << "SLP: Extract Cost = " << ExtractCost << ".\n"
5388        << "SLP: Total Cost = " << Cost << ".\n";
5389   }
5390   LLVM_DEBUG(dbgs() << Str);
5391   if (ViewSLPTree)
5392     ViewGraph(this, "SLP" + F->getName(), false, Str);
5393 #endif
5394 
5395   return Cost;
5396 }
5397 
5398 Optional<TargetTransformInfo::ShuffleKind>
5399 BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
5400                                SmallVectorImpl<const TreeEntry *> &Entries) {
5401   // TODO: currently checking only for Scalars in the tree entry, need to count
5402   // reused elements too for better cost estimation.
5403   Mask.assign(TE->Scalars.size(), UndefMaskElem);
5404   Entries.clear();
5405   // Build a lists of values to tree entries.
5406   DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
5407   for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
5408     if (EntryPtr.get() == TE)
5409       break;
5410     if (EntryPtr->State != TreeEntry::NeedToGather)
5411       continue;
5412     for (Value *V : EntryPtr->Scalars)
5413       ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
5414   }
5415   // Find all tree entries used by the gathered values. If no common entries
5416   // found - not a shuffle.
5417   // Here we build a set of tree nodes for each gathered value and trying to
5418   // find the intersection between these sets. If we have at least one common
5419   // tree node for each gathered value - we have just a permutation of the
5420   // single vector. If we have 2 different sets, we're in situation where we
5421   // have a permutation of 2 input vectors.
5422   SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
5423   DenseMap<Value *, int> UsedValuesEntry;
5424   for (Value *V : TE->Scalars) {
5425     if (isa<UndefValue>(V))
5426       continue;
5427     // Build a list of tree entries where V is used.
5428     SmallPtrSet<const TreeEntry *, 4> VToTEs;
5429     auto It = ValueToTEs.find(V);
5430     if (It != ValueToTEs.end())
5431       VToTEs = It->second;
5432     if (const TreeEntry *VTE = getTreeEntry(V))
5433       VToTEs.insert(VTE);
5434     if (VToTEs.empty())
5435       return None;
5436     if (UsedTEs.empty()) {
5437       // The first iteration, just insert the list of nodes to vector.
5438       UsedTEs.push_back(VToTEs);
5439     } else {
5440       // Need to check if there are any previously used tree nodes which use V.
5441       // If there are no such nodes, consider that we have another one input
5442       // vector.
5443       SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
5444       unsigned Idx = 0;
5445       for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
5446         // Do we have a non-empty intersection of previously listed tree entries
5447         // and tree entries using current V?
5448         set_intersect(VToTEs, Set);
5449         if (!VToTEs.empty()) {
5450           // Yes, write the new subset and continue analysis for the next
5451           // scalar.
5452           Set.swap(VToTEs);
5453           break;
5454         }
5455         VToTEs = SavedVToTEs;
5456         ++Idx;
5457       }
5458       // No non-empty intersection found - need to add a second set of possible
5459       // source vectors.
5460       if (Idx == UsedTEs.size()) {
5461         // If the number of input vectors is greater than 2 - not a permutation,
5462         // fallback to the regular gather.
5463         if (UsedTEs.size() == 2)
5464           return None;
5465         UsedTEs.push_back(SavedVToTEs);
5466         Idx = UsedTEs.size() - 1;
5467       }
5468       UsedValuesEntry.try_emplace(V, Idx);
5469     }
5470   }
5471 
5472   unsigned VF = 0;
5473   if (UsedTEs.size() == 1) {
5474     // Try to find the perfect match in another gather node at first.
5475     auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
5476       return EntryPtr->isSame(TE->Scalars);
5477     });
5478     if (It != UsedTEs.front().end()) {
5479       Entries.push_back(*It);
5480       std::iota(Mask.begin(), Mask.end(), 0);
5481       return TargetTransformInfo::SK_PermuteSingleSrc;
5482     }
5483     // No perfect match, just shuffle, so choose the first tree node.
5484     Entries.push_back(*UsedTEs.front().begin());
5485   } else {
5486     // Try to find nodes with the same vector factor.
5487     assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
5488     // FIXME: Shall be replaced by GetVF function once non-power-2 patch is
5489     // landed.
5490     auto &&GetVF = [](const TreeEntry *TE) {
5491       if (!TE->ReuseShuffleIndices.empty())
5492         return TE->ReuseShuffleIndices.size();
5493       return TE->Scalars.size();
5494     };
5495     DenseMap<int, const TreeEntry *> VFToTE;
5496     for (const TreeEntry *TE : UsedTEs.front())
5497       VFToTE.try_emplace(GetVF(TE), TE);
5498     for (const TreeEntry *TE : UsedTEs.back()) {
5499       auto It = VFToTE.find(GetVF(TE));
5500       if (It != VFToTE.end()) {
5501         VF = It->first;
5502         Entries.push_back(It->second);
5503         Entries.push_back(TE);
5504         break;
5505       }
5506     }
5507     // No 2 source vectors with the same vector factor - give up and do regular
5508     // gather.
5509     if (Entries.empty())
5510       return None;
5511   }
5512 
5513   // Build a shuffle mask for better cost estimation and vector emission.
5514   for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
5515     Value *V = TE->Scalars[I];
5516     if (isa<UndefValue>(V))
5517       continue;
5518     unsigned Idx = UsedValuesEntry.lookup(V);
5519     const TreeEntry *VTE = Entries[Idx];
5520     int FoundLane = VTE->findLaneForValue(V);
5521     Mask[I] = Idx * VF + FoundLane;
5522     // Extra check required by isSingleSourceMaskImpl function (called by
5523     // ShuffleVectorInst::isSingleSourceMask).
5524     if (Mask[I] >= 2 * E)
5525       return None;
5526   }
5527   switch (Entries.size()) {
5528   case 1:
5529     return TargetTransformInfo::SK_PermuteSingleSrc;
5530   case 2:
5531     return TargetTransformInfo::SK_PermuteTwoSrc;
5532   default:
5533     break;
5534   }
5535   return None;
5536 }
5537 
5538 InstructionCost
5539 BoUpSLP::getGatherCost(FixedVectorType *Ty,
5540                        const DenseSet<unsigned> &ShuffledIndices) const {
5541   unsigned NumElts = Ty->getNumElements();
5542   APInt DemandedElts = APInt::getZero(NumElts);
5543   for (unsigned I = 0; I < NumElts; ++I)
5544     if (!ShuffledIndices.count(I))
5545       DemandedElts.setBit(I);
5546   InstructionCost Cost =
5547       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
5548                                     /*Extract*/ false);
5549   if (!ShuffledIndices.empty())
5550     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
5551   return Cost;
5552 }
5553 
5554 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
5555   // Find the type of the operands in VL.
5556   Type *ScalarTy = VL[0]->getType();
5557   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
5558     ScalarTy = SI->getValueOperand()->getType();
5559   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
5560   // Find the cost of inserting/extracting values from the vector.
5561   // Check if the same elements are inserted several times and count them as
5562   // shuffle candidates.
5563   DenseSet<unsigned> ShuffledElements;
5564   DenseSet<Value *> UniqueElements;
5565   // Iterate in reverse order to consider insert elements with the high cost.
5566   for (unsigned I = VL.size(); I > 0; --I) {
5567     unsigned Idx = I - 1;
5568     if (isConstant(VL[Idx]))
5569       continue;
5570     if (!UniqueElements.insert(VL[Idx]).second)
5571       ShuffledElements.insert(Idx);
5572   }
5573   return getGatherCost(VecTy, ShuffledElements);
5574 }
5575 
5576 // Perform operand reordering on the instructions in VL and return the reordered
5577 // operands in Left and Right.
5578 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
5579                                              SmallVectorImpl<Value *> &Left,
5580                                              SmallVectorImpl<Value *> &Right,
5581                                              const DataLayout &DL,
5582                                              ScalarEvolution &SE,
5583                                              const BoUpSLP &R) {
5584   if (VL.empty())
5585     return;
5586   VLOperands Ops(VL, DL, SE, R);
5587   // Reorder the operands in place.
5588   Ops.reorder();
5589   Left = Ops.getVL(0);
5590   Right = Ops.getVL(1);
5591 }
5592 
5593 void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
5594   // Get the basic block this bundle is in. All instructions in the bundle
5595   // should be in this block.
5596   auto *Front = E->getMainOp();
5597   auto *BB = Front->getParent();
5598   assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
5599     auto *I = cast<Instruction>(V);
5600     return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
5601   }));
5602 
5603   // The last instruction in the bundle in program order.
5604   Instruction *LastInst = nullptr;
5605 
5606   // Find the last instruction. The common case should be that BB has been
5607   // scheduled, and the last instruction is VL.back(). So we start with
5608   // VL.back() and iterate over schedule data until we reach the end of the
5609   // bundle. The end of the bundle is marked by null ScheduleData.
5610   if (BlocksSchedules.count(BB)) {
5611     auto *Bundle =
5612         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
5613     if (Bundle && Bundle->isPartOfBundle())
5614       for (; Bundle; Bundle = Bundle->NextInBundle)
5615         if (Bundle->OpValue == Bundle->Inst)
5616           LastInst = Bundle->Inst;
5617   }
5618 
5619   // LastInst can still be null at this point if there's either not an entry
5620   // for BB in BlocksSchedules or there's no ScheduleData available for
5621   // VL.back(). This can be the case if buildTree_rec aborts for various
5622   // reasons (e.g., the maximum recursion depth is reached, the maximum region
5623   // size is reached, etc.). ScheduleData is initialized in the scheduling
5624   // "dry-run".
5625   //
5626   // If this happens, we can still find the last instruction by brute force. We
5627   // iterate forwards from Front (inclusive) until we either see all
5628   // instructions in the bundle or reach the end of the block. If Front is the
5629   // last instruction in program order, LastInst will be set to Front, and we
5630   // will visit all the remaining instructions in the block.
5631   //
5632   // One of the reasons we exit early from buildTree_rec is to place an upper
5633   // bound on compile-time. Thus, taking an additional compile-time hit here is
5634   // not ideal. However, this should be exceedingly rare since it requires that
5635   // we both exit early from buildTree_rec and that the bundle be out-of-order
5636   // (causing us to iterate all the way to the end of the block).
5637   if (!LastInst) {
5638     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
5639     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
5640       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
5641         LastInst = &I;
5642       if (Bundle.empty())
5643         break;
5644     }
5645   }
5646   assert(LastInst && "Failed to find last instruction in bundle");
5647 
5648   // Set the insertion point after the last instruction in the bundle. Set the
5649   // debug location to Front.
5650   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
5651   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
5652 }
5653 
5654 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
5655   // List of instructions/lanes from current block and/or the blocks which are
5656   // part of the current loop. These instructions will be inserted at the end to
5657   // make it possible to optimize loops and hoist invariant instructions out of
5658   // the loops body with better chances for success.
5659   SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
5660   SmallSet<int, 4> PostponedIndices;
5661   Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
5662   auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
5663     SmallPtrSet<BasicBlock *, 4> Visited;
5664     while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
5665       InsertBB = InsertBB->getSinglePredecessor();
5666     return InsertBB && InsertBB == InstBB;
5667   };
5668   for (int I = 0, E = VL.size(); I < E; ++I) {
5669     if (auto *Inst = dyn_cast<Instruction>(VL[I]))
5670       if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
5671            getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
5672           PostponedIndices.insert(I).second)
5673         PostponedInsts.emplace_back(Inst, I);
5674   }
5675 
5676   auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
5677     Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
5678     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
5679     if (!InsElt)
5680       return Vec;
5681     GatherSeq.insert(InsElt);
5682     CSEBlocks.insert(InsElt->getParent());
5683     // Add to our 'need-to-extract' list.
5684     if (TreeEntry *Entry = getTreeEntry(V)) {
5685       // Find which lane we need to extract.
5686       unsigned FoundLane = Entry->findLaneForValue(V);
5687       ExternalUses.emplace_back(V, InsElt, FoundLane);
5688     }
5689     return Vec;
5690   };
5691   Value *Val0 =
5692       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
5693   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
5694   Value *Vec = PoisonValue::get(VecTy);
5695   SmallVector<int> NonConsts;
5696   // Insert constant values at first.
5697   for (int I = 0, E = VL.size(); I < E; ++I) {
5698     if (PostponedIndices.contains(I))
5699       continue;
5700     if (!isConstant(VL[I])) {
5701       NonConsts.push_back(I);
5702       continue;
5703     }
5704     Vec = CreateInsertElement(Vec, VL[I], I);
5705   }
5706   // Insert non-constant values.
5707   for (int I : NonConsts)
5708     Vec = CreateInsertElement(Vec, VL[I], I);
5709   // Append instructions, which are/may be part of the loop, in the end to make
5710   // it possible to hoist non-loop-based instructions.
5711   for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
5712     Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
5713 
5714   return Vec;
5715 }
5716 
5717 namespace {
5718 /// Merges shuffle masks and emits final shuffle instruction, if required.
5719 class ShuffleInstructionBuilder {
5720   IRBuilderBase &Builder;
5721   const unsigned VF = 0;
5722   bool IsFinalized = false;
5723   SmallVector<int, 4> Mask;
5724 
5725 public:
5726   ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF)
5727       : Builder(Builder), VF(VF) {}
5728 
5729   /// Adds a mask, inverting it before applying.
5730   void addInversedMask(ArrayRef<unsigned> SubMask) {
5731     if (SubMask.empty())
5732       return;
5733     SmallVector<int, 4> NewMask;
5734     inversePermutation(SubMask, NewMask);
5735     addMask(NewMask);
5736   }
5737 
5738   /// Functions adds masks, merging them into  single one.
5739   void addMask(ArrayRef<unsigned> SubMask) {
5740     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
5741     addMask(NewMask);
5742   }
5743 
5744   void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
5745 
5746   Value *finalize(Value *V) {
5747     IsFinalized = true;
5748     unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
5749     if (VF == ValueVF && Mask.empty())
5750       return V;
5751     SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
5752     std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
5753     addMask(NormalizedMask);
5754 
5755     if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
5756       return V;
5757     return Builder.CreateShuffleVector(V, Mask, "shuffle");
5758   }
5759 
5760   ~ShuffleInstructionBuilder() {
5761     assert((IsFinalized || Mask.empty()) &&
5762            "Shuffle construction must be finalized.");
5763   }
5764 };
5765 } // namespace
5766 
5767 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
5768   unsigned VF = VL.size();
5769   InstructionsState S = getSameOpcode(VL);
5770   if (S.getOpcode()) {
5771     if (TreeEntry *E = getTreeEntry(S.OpValue))
5772       if (E->isSame(VL)) {
5773         Value *V = vectorizeTree(E);
5774         if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
5775           if (!E->ReuseShuffleIndices.empty()) {
5776             // Reshuffle to get only unique values.
5777             // If some of the scalars are duplicated in the vectorization tree
5778             // entry, we do not vectorize them but instead generate a mask for
5779             // the reuses. But if there are several users of the same entry,
5780             // they may have different vectorization factors. This is especially
5781             // important for PHI nodes. In this case, we need to adapt the
5782             // resulting instruction for the user vectorization factor and have
5783             // to reshuffle it again to take only unique elements of the vector.
5784             // Without this code the function incorrectly returns reduced vector
5785             // instruction with the same elements, not with the unique ones.
5786 
5787             // block:
5788             // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
5789             // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
5790             // ... (use %2)
5791             // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
5792             // br %block
5793             SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
5794             SmallSet<int, 4> UsedIdxs;
5795             int Pos = 0;
5796             int Sz = VL.size();
5797             for (int Idx : E->ReuseShuffleIndices) {
5798               if (Idx != Sz && Idx != UndefMaskElem &&
5799                   UsedIdxs.insert(Idx).second)
5800                 UniqueIdxs[Idx] = Pos;
5801               ++Pos;
5802             }
5803             assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
5804                                             "less than original vector size.");
5805             UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
5806             V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
5807           } else {
5808             assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
5809                    "Expected vectorization factor less "
5810                    "than original vector size.");
5811             SmallVector<int> UniformMask(VF, 0);
5812             std::iota(UniformMask.begin(), UniformMask.end(), 0);
5813             V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
5814           }
5815         }
5816         return V;
5817       }
5818   }
5819 
5820   // Check that every instruction appears once in this bundle.
5821   SmallVector<int> ReuseShuffleIndicies;
5822   SmallVector<Value *> UniqueValues;
5823   if (VL.size() > 2) {
5824     DenseMap<Value *, unsigned> UniquePositions;
5825     unsigned NumValues =
5826         std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
5827                                     return !isa<UndefValue>(V);
5828                                   }).base());
5829     VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
5830     int UniqueVals = 0;
5831     for (Value *V : VL.drop_back(VL.size() - VF)) {
5832       if (isa<UndefValue>(V)) {
5833         ReuseShuffleIndicies.emplace_back(UndefMaskElem);
5834         continue;
5835       }
5836       if (isConstant(V)) {
5837         ReuseShuffleIndicies.emplace_back(UniqueValues.size());
5838         UniqueValues.emplace_back(V);
5839         continue;
5840       }
5841       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
5842       ReuseShuffleIndicies.emplace_back(Res.first->second);
5843       if (Res.second) {
5844         UniqueValues.emplace_back(V);
5845         ++UniqueVals;
5846       }
5847     }
5848     if (UniqueVals == 1 && UniqueValues.size() == 1) {
5849       // Emit pure splat vector.
5850       ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
5851                                   UndefMaskElem);
5852     } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
5853       ReuseShuffleIndicies.clear();
5854       UniqueValues.clear();
5855       UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
5856     }
5857     UniqueValues.append(VF - UniqueValues.size(),
5858                         PoisonValue::get(VL[0]->getType()));
5859     VL = UniqueValues;
5860   }
5861 
5862   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF);
5863   Value *Vec = gather(VL);
5864   if (!ReuseShuffleIndicies.empty()) {
5865     ShuffleBuilder.addMask(ReuseShuffleIndicies);
5866     Vec = ShuffleBuilder.finalize(Vec);
5867     if (auto *I = dyn_cast<Instruction>(Vec)) {
5868       GatherSeq.insert(I);
5869       CSEBlocks.insert(I->getParent());
5870     }
5871   }
5872   return Vec;
5873 }
5874 
5875 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
5876   IRBuilder<>::InsertPointGuard Guard(Builder);
5877 
5878   if (E->VectorizedValue) {
5879     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
5880     return E->VectorizedValue;
5881   }
5882 
5883   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
5884   unsigned VF = E->Scalars.size();
5885   if (NeedToShuffleReuses)
5886     VF = E->ReuseShuffleIndices.size();
5887   ShuffleInstructionBuilder ShuffleBuilder(Builder, VF);
5888   if (E->State == TreeEntry::NeedToGather) {
5889     if (E->getMainOp())
5890       setInsertPointAfterBundle(E);
5891     Value *Vec;
5892     SmallVector<int> Mask;
5893     SmallVector<const TreeEntry *> Entries;
5894     Optional<TargetTransformInfo::ShuffleKind> Shuffle =
5895         isGatherShuffledEntry(E, Mask, Entries);
5896     if (Shuffle.hasValue()) {
5897       assert((Entries.size() == 1 || Entries.size() == 2) &&
5898              "Expected shuffle of 1 or 2 entries.");
5899       Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
5900                                         Entries.back()->VectorizedValue, Mask);
5901     } else {
5902       Vec = gather(E->Scalars);
5903     }
5904     if (NeedToShuffleReuses) {
5905       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5906       Vec = ShuffleBuilder.finalize(Vec);
5907       if (auto *I = dyn_cast<Instruction>(Vec)) {
5908         GatherSeq.insert(I);
5909         CSEBlocks.insert(I->getParent());
5910       }
5911     }
5912     E->VectorizedValue = Vec;
5913     return Vec;
5914   }
5915 
5916   assert((E->State == TreeEntry::Vectorize ||
5917           E->State == TreeEntry::ScatterVectorize) &&
5918          "Unhandled state");
5919   unsigned ShuffleOrOp =
5920       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
5921   Instruction *VL0 = E->getMainOp();
5922   Type *ScalarTy = VL0->getType();
5923   if (auto *Store = dyn_cast<StoreInst>(VL0))
5924     ScalarTy = Store->getValueOperand()->getType();
5925   else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
5926     ScalarTy = IE->getOperand(1)->getType();
5927   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
5928   switch (ShuffleOrOp) {
5929     case Instruction::PHI: {
5930       assert(
5931           (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
5932           "PHI reordering is free.");
5933       auto *PH = cast<PHINode>(VL0);
5934       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
5935       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
5936       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
5937       Value *V = NewPhi;
5938       ShuffleBuilder.addInversedMask(E->ReorderIndices);
5939       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5940       V = ShuffleBuilder.finalize(V);
5941 
5942       E->VectorizedValue = V;
5943 
5944       // PHINodes may have multiple entries from the same block. We want to
5945       // visit every block once.
5946       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
5947 
5948       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
5949         ValueList Operands;
5950         BasicBlock *IBB = PH->getIncomingBlock(i);
5951 
5952         if (!VisitedBBs.insert(IBB).second) {
5953           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
5954           continue;
5955         }
5956 
5957         Builder.SetInsertPoint(IBB->getTerminator());
5958         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
5959         Value *Vec = vectorizeTree(E->getOperand(i));
5960         NewPhi->addIncoming(Vec, IBB);
5961       }
5962 
5963       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
5964              "Invalid number of incoming values");
5965       return V;
5966     }
5967 
5968     case Instruction::ExtractElement: {
5969       Value *V = E->getSingleOperand(0);
5970       Builder.SetInsertPoint(VL0);
5971       ShuffleBuilder.addInversedMask(E->ReorderIndices);
5972       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5973       V = ShuffleBuilder.finalize(V);
5974       E->VectorizedValue = V;
5975       return V;
5976     }
5977     case Instruction::ExtractValue: {
5978       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
5979       Builder.SetInsertPoint(LI);
5980       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
5981       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
5982       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
5983       Value *NewV = propagateMetadata(V, E->Scalars);
5984       ShuffleBuilder.addInversedMask(E->ReorderIndices);
5985       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
5986       NewV = ShuffleBuilder.finalize(NewV);
5987       E->VectorizedValue = NewV;
5988       return NewV;
5989     }
5990     case Instruction::InsertElement: {
5991       assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
5992       Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
5993       Value *V = vectorizeTree(E->getOperand(1));
5994 
5995       // Create InsertVector shuffle if necessary
5996       auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
5997         return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
5998       }));
5999       const unsigned NumElts =
6000           cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
6001       const unsigned NumScalars = E->Scalars.size();
6002 
6003       unsigned Offset = *getInsertIndex(VL0, 0);
6004       assert(Offset < NumElts && "Failed to find vector index offset");
6005 
6006       // Create shuffle to resize vector
6007       SmallVector<int> Mask;
6008       if (!E->ReorderIndices.empty()) {
6009         inversePermutation(E->ReorderIndices, Mask);
6010         Mask.append(NumElts - NumScalars, UndefMaskElem);
6011       } else {
6012         Mask.assign(NumElts, UndefMaskElem);
6013         std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
6014       }
6015       // Create InsertVector shuffle if necessary
6016       bool IsIdentity = true;
6017       SmallVector<int> PrevMask(NumElts, UndefMaskElem);
6018       Mask.swap(PrevMask);
6019       for (unsigned I = 0; I < NumScalars; ++I) {
6020         Value *Scalar = E->Scalars[PrevMask[I]];
6021         Optional<int> InsertIdx = getInsertIndex(Scalar, 0);
6022         if (!InsertIdx || *InsertIdx == UndefMaskElem)
6023           continue;
6024         IsIdentity &= *InsertIdx - Offset == I;
6025         Mask[*InsertIdx - Offset] = I;
6026       }
6027       if (!IsIdentity || NumElts != NumScalars)
6028         V = Builder.CreateShuffleVector(V, Mask);
6029 
6030       if ((!IsIdentity || Offset != 0 ||
6031            !isa<UndefValue>(FirstInsert->getOperand(0))) &&
6032           NumElts != NumScalars) {
6033         SmallVector<int> InsertMask(NumElts);
6034         std::iota(InsertMask.begin(), InsertMask.end(), 0);
6035         for (unsigned I = 0; I < NumElts; I++) {
6036           if (Mask[I] != UndefMaskElem)
6037             InsertMask[Offset + I] = NumElts + I;
6038         }
6039 
6040         V = Builder.CreateShuffleVector(
6041             FirstInsert->getOperand(0), V, InsertMask,
6042             cast<Instruction>(E->Scalars.back())->getName());
6043       }
6044 
6045       ++NumVectorInstructions;
6046       E->VectorizedValue = V;
6047       return V;
6048     }
6049     case Instruction::ZExt:
6050     case Instruction::SExt:
6051     case Instruction::FPToUI:
6052     case Instruction::FPToSI:
6053     case Instruction::FPExt:
6054     case Instruction::PtrToInt:
6055     case Instruction::IntToPtr:
6056     case Instruction::SIToFP:
6057     case Instruction::UIToFP:
6058     case Instruction::Trunc:
6059     case Instruction::FPTrunc:
6060     case Instruction::BitCast: {
6061       setInsertPointAfterBundle(E);
6062 
6063       Value *InVec = vectorizeTree(E->getOperand(0));
6064 
6065       if (E->VectorizedValue) {
6066         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6067         return E->VectorizedValue;
6068       }
6069 
6070       auto *CI = cast<CastInst>(VL0);
6071       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
6072       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6073       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6074       V = ShuffleBuilder.finalize(V);
6075 
6076       E->VectorizedValue = V;
6077       ++NumVectorInstructions;
6078       return V;
6079     }
6080     case Instruction::FCmp:
6081     case Instruction::ICmp: {
6082       setInsertPointAfterBundle(E);
6083 
6084       Value *L = vectorizeTree(E->getOperand(0));
6085       Value *R = vectorizeTree(E->getOperand(1));
6086 
6087       if (E->VectorizedValue) {
6088         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6089         return E->VectorizedValue;
6090       }
6091 
6092       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
6093       Value *V = Builder.CreateCmp(P0, L, R);
6094       propagateIRFlags(V, E->Scalars, VL0);
6095       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6096       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6097       V = ShuffleBuilder.finalize(V);
6098 
6099       E->VectorizedValue = V;
6100       ++NumVectorInstructions;
6101       return V;
6102     }
6103     case Instruction::Select: {
6104       setInsertPointAfterBundle(E);
6105 
6106       Value *Cond = vectorizeTree(E->getOperand(0));
6107       Value *True = vectorizeTree(E->getOperand(1));
6108       Value *False = vectorizeTree(E->getOperand(2));
6109 
6110       if (E->VectorizedValue) {
6111         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6112         return E->VectorizedValue;
6113       }
6114 
6115       Value *V = Builder.CreateSelect(Cond, True, False);
6116       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6117       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6118       V = ShuffleBuilder.finalize(V);
6119 
6120       E->VectorizedValue = V;
6121       ++NumVectorInstructions;
6122       return V;
6123     }
6124     case Instruction::FNeg: {
6125       setInsertPointAfterBundle(E);
6126 
6127       Value *Op = vectorizeTree(E->getOperand(0));
6128 
6129       if (E->VectorizedValue) {
6130         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6131         return E->VectorizedValue;
6132       }
6133 
6134       Value *V = Builder.CreateUnOp(
6135           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
6136       propagateIRFlags(V, E->Scalars, VL0);
6137       if (auto *I = dyn_cast<Instruction>(V))
6138         V = propagateMetadata(I, E->Scalars);
6139 
6140       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6141       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6142       V = ShuffleBuilder.finalize(V);
6143 
6144       E->VectorizedValue = V;
6145       ++NumVectorInstructions;
6146 
6147       return V;
6148     }
6149     case Instruction::Add:
6150     case Instruction::FAdd:
6151     case Instruction::Sub:
6152     case Instruction::FSub:
6153     case Instruction::Mul:
6154     case Instruction::FMul:
6155     case Instruction::UDiv:
6156     case Instruction::SDiv:
6157     case Instruction::FDiv:
6158     case Instruction::URem:
6159     case Instruction::SRem:
6160     case Instruction::FRem:
6161     case Instruction::Shl:
6162     case Instruction::LShr:
6163     case Instruction::AShr:
6164     case Instruction::And:
6165     case Instruction::Or:
6166     case Instruction::Xor: {
6167       setInsertPointAfterBundle(E);
6168 
6169       Value *LHS = vectorizeTree(E->getOperand(0));
6170       Value *RHS = vectorizeTree(E->getOperand(1));
6171 
6172       if (E->VectorizedValue) {
6173         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6174         return E->VectorizedValue;
6175       }
6176 
6177       Value *V = Builder.CreateBinOp(
6178           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
6179           RHS);
6180       propagateIRFlags(V, E->Scalars, VL0);
6181       if (auto *I = dyn_cast<Instruction>(V))
6182         V = propagateMetadata(I, E->Scalars);
6183 
6184       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6185       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6186       V = ShuffleBuilder.finalize(V);
6187 
6188       E->VectorizedValue = V;
6189       ++NumVectorInstructions;
6190 
6191       return V;
6192     }
6193     case Instruction::Load: {
6194       // Loads are inserted at the head of the tree because we don't want to
6195       // sink them all the way down past store instructions.
6196       setInsertPointAfterBundle(E);
6197 
6198       LoadInst *LI = cast<LoadInst>(VL0);
6199       Instruction *NewLI;
6200       unsigned AS = LI->getPointerAddressSpace();
6201       Value *PO = LI->getPointerOperand();
6202       if (E->State == TreeEntry::Vectorize) {
6203 
6204         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
6205 
6206         // The pointer operand uses an in-tree scalar so we add the new BitCast
6207         // to ExternalUses list to make sure that an extract will be generated
6208         // in the future.
6209         if (TreeEntry *Entry = getTreeEntry(PO)) {
6210           // Find which lane we need to extract.
6211           unsigned FoundLane = Entry->findLaneForValue(PO);
6212           ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
6213         }
6214 
6215         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
6216       } else {
6217         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
6218         Value *VecPtr = vectorizeTree(E->getOperand(0));
6219         // Use the minimum alignment of the gathered loads.
6220         Align CommonAlignment = LI->getAlign();
6221         for (Value *V : E->Scalars)
6222           CommonAlignment =
6223               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
6224         NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
6225       }
6226       Value *V = propagateMetadata(NewLI, E->Scalars);
6227 
6228       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6229       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6230       V = ShuffleBuilder.finalize(V);
6231       E->VectorizedValue = V;
6232       ++NumVectorInstructions;
6233       return V;
6234     }
6235     case Instruction::Store: {
6236       auto *SI = cast<StoreInst>(VL0);
6237       unsigned AS = SI->getPointerAddressSpace();
6238 
6239       setInsertPointAfterBundle(E);
6240 
6241       Value *VecValue = vectorizeTree(E->getOperand(0));
6242       ShuffleBuilder.addMask(E->ReorderIndices);
6243       VecValue = ShuffleBuilder.finalize(VecValue);
6244 
6245       Value *ScalarPtr = SI->getPointerOperand();
6246       Value *VecPtr = Builder.CreateBitCast(
6247           ScalarPtr, VecValue->getType()->getPointerTo(AS));
6248       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
6249                                                  SI->getAlign());
6250 
6251       // The pointer operand uses an in-tree scalar, so add the new BitCast to
6252       // ExternalUses to make sure that an extract will be generated in the
6253       // future.
6254       if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
6255         // Find which lane we need to extract.
6256         unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
6257         ExternalUses.push_back(
6258             ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
6259       }
6260 
6261       Value *V = propagateMetadata(ST, E->Scalars);
6262 
6263       E->VectorizedValue = V;
6264       ++NumVectorInstructions;
6265       return V;
6266     }
6267     case Instruction::GetElementPtr: {
6268       setInsertPointAfterBundle(E);
6269 
6270       Value *Op0 = vectorizeTree(E->getOperand(0));
6271 
6272       std::vector<Value *> OpVecs;
6273       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
6274            ++j) {
6275         ValueList &VL = E->getOperand(j);
6276         // Need to cast all elements to the same type before vectorization to
6277         // avoid crash.
6278         Type *VL0Ty = VL0->getOperand(j)->getType();
6279         Type *Ty = llvm::all_of(
6280                        VL, [VL0Ty](Value *V) { return VL0Ty == V->getType(); })
6281                        ? VL0Ty
6282                        : DL->getIndexType(cast<GetElementPtrInst>(VL0)
6283                                               ->getPointerOperandType()
6284                                               ->getScalarType());
6285         for (Value *&V : VL) {
6286           auto *CI = cast<ConstantInt>(V);
6287           V = ConstantExpr::getIntegerCast(CI, Ty,
6288                                            CI->getValue().isSignBitSet());
6289         }
6290         Value *OpVec = vectorizeTree(VL);
6291         OpVecs.push_back(OpVec);
6292       }
6293 
6294       Value *V = Builder.CreateGEP(
6295           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
6296       if (Instruction *I = dyn_cast<Instruction>(V))
6297         V = propagateMetadata(I, E->Scalars);
6298 
6299       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6300       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6301       V = ShuffleBuilder.finalize(V);
6302 
6303       E->VectorizedValue = V;
6304       ++NumVectorInstructions;
6305 
6306       return V;
6307     }
6308     case Instruction::Call: {
6309       CallInst *CI = cast<CallInst>(VL0);
6310       setInsertPointAfterBundle(E);
6311 
6312       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
6313       if (Function *FI = CI->getCalledFunction())
6314         IID = FI->getIntrinsicID();
6315 
6316       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
6317 
6318       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
6319       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
6320                           VecCallCosts.first <= VecCallCosts.second;
6321 
6322       Value *ScalarArg = nullptr;
6323       std::vector<Value *> OpVecs;
6324       SmallVector<Type *, 2> TysForDecl =
6325           {FixedVectorType::get(CI->getType(), E->Scalars.size())};
6326       for (int j = 0, e = CI->arg_size(); j < e; ++j) {
6327         ValueList OpVL;
6328         // Some intrinsics have scalar arguments. This argument should not be
6329         // vectorized.
6330         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
6331           CallInst *CEI = cast<CallInst>(VL0);
6332           ScalarArg = CEI->getArgOperand(j);
6333           OpVecs.push_back(CEI->getArgOperand(j));
6334           if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
6335             TysForDecl.push_back(ScalarArg->getType());
6336           continue;
6337         }
6338 
6339         Value *OpVec = vectorizeTree(E->getOperand(j));
6340         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
6341         OpVecs.push_back(OpVec);
6342       }
6343 
6344       Function *CF;
6345       if (!UseIntrinsic) {
6346         VFShape Shape =
6347             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
6348                                   VecTy->getNumElements())),
6349                          false /*HasGlobalPred*/);
6350         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
6351       } else {
6352         CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
6353       }
6354 
6355       SmallVector<OperandBundleDef, 1> OpBundles;
6356       CI->getOperandBundlesAsDefs(OpBundles);
6357       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
6358 
6359       // The scalar argument uses an in-tree scalar so we add the new vectorized
6360       // call to ExternalUses list to make sure that an extract will be
6361       // generated in the future.
6362       if (ScalarArg) {
6363         if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
6364           // Find which lane we need to extract.
6365           unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
6366           ExternalUses.push_back(
6367               ExternalUser(ScalarArg, cast<User>(V), FoundLane));
6368         }
6369       }
6370 
6371       propagateIRFlags(V, E->Scalars, VL0);
6372       ShuffleBuilder.addInversedMask(E->ReorderIndices);
6373       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
6374       V = ShuffleBuilder.finalize(V);
6375 
6376       E->VectorizedValue = V;
6377       ++NumVectorInstructions;
6378       return V;
6379     }
6380     case Instruction::ShuffleVector: {
6381       assert(E->isAltShuffle() &&
6382              ((Instruction::isBinaryOp(E->getOpcode()) &&
6383                Instruction::isBinaryOp(E->getAltOpcode())) ||
6384               (Instruction::isCast(E->getOpcode()) &&
6385                Instruction::isCast(E->getAltOpcode()))) &&
6386              "Invalid Shuffle Vector Operand");
6387 
6388       Value *LHS = nullptr, *RHS = nullptr;
6389       if (Instruction::isBinaryOp(E->getOpcode())) {
6390         setInsertPointAfterBundle(E);
6391         LHS = vectorizeTree(E->getOperand(0));
6392         RHS = vectorizeTree(E->getOperand(1));
6393       } else {
6394         setInsertPointAfterBundle(E);
6395         LHS = vectorizeTree(E->getOperand(0));
6396       }
6397 
6398       if (E->VectorizedValue) {
6399         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
6400         return E->VectorizedValue;
6401       }
6402 
6403       Value *V0, *V1;
6404       if (Instruction::isBinaryOp(E->getOpcode())) {
6405         V0 = Builder.CreateBinOp(
6406             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
6407         V1 = Builder.CreateBinOp(
6408             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
6409       } else {
6410         V0 = Builder.CreateCast(
6411             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
6412         V1 = Builder.CreateCast(
6413             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
6414       }
6415 
6416       // Create shuffle to take alternate operations from the vector.
6417       // Also, gather up main and alt scalar ops to propagate IR flags to
6418       // each vector operation.
6419       ValueList OpScalars, AltScalars;
6420       SmallVector<int> Mask;
6421       buildSuffleEntryMask(
6422           E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
6423           [E](Instruction *I) {
6424             assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
6425             return I->getOpcode() == E->getAltOpcode();
6426           },
6427           Mask, &OpScalars, &AltScalars);
6428 
6429       propagateIRFlags(V0, OpScalars);
6430       propagateIRFlags(V1, AltScalars);
6431 
6432       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
6433       if (Instruction *I = dyn_cast<Instruction>(V))
6434         V = propagateMetadata(I, E->Scalars);
6435       V = ShuffleBuilder.finalize(V);
6436 
6437       E->VectorizedValue = V;
6438       ++NumVectorInstructions;
6439 
6440       return V;
6441     }
6442     default:
6443     llvm_unreachable("unknown inst");
6444   }
6445   return nullptr;
6446 }
6447 
6448 Value *BoUpSLP::vectorizeTree() {
6449   ExtraValueToDebugLocsMap ExternallyUsedValues;
6450   return vectorizeTree(ExternallyUsedValues);
6451 }
6452 
6453 Value *
6454 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
6455   // All blocks must be scheduled before any instructions are inserted.
6456   for (auto &BSIter : BlocksSchedules) {
6457     scheduleBlock(BSIter.second.get());
6458   }
6459 
6460   Builder.SetInsertPoint(&F->getEntryBlock().front());
6461   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
6462 
6463   // If the vectorized tree can be rewritten in a smaller type, we truncate the
6464   // vectorized root. InstCombine will then rewrite the entire expression. We
6465   // sign extend the extracted values below.
6466   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
6467   if (MinBWs.count(ScalarRoot)) {
6468     if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
6469       // If current instr is a phi and not the last phi, insert it after the
6470       // last phi node.
6471       if (isa<PHINode>(I))
6472         Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
6473       else
6474         Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
6475     }
6476     auto BundleWidth = VectorizableTree[0]->Scalars.size();
6477     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
6478     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
6479     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
6480     VectorizableTree[0]->VectorizedValue = Trunc;
6481   }
6482 
6483   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
6484                     << " values .\n");
6485 
6486   // Extract all of the elements with the external uses.
6487   for (const auto &ExternalUse : ExternalUses) {
6488     Value *Scalar = ExternalUse.Scalar;
6489     llvm::User *User = ExternalUse.User;
6490 
6491     // Skip users that we already RAUW. This happens when one instruction
6492     // has multiple uses of the same value.
6493     if (User && !is_contained(Scalar->users(), User))
6494       continue;
6495     TreeEntry *E = getTreeEntry(Scalar);
6496     assert(E && "Invalid scalar");
6497     assert(E->State != TreeEntry::NeedToGather &&
6498            "Extracting from a gather list");
6499 
6500     Value *Vec = E->VectorizedValue;
6501     assert(Vec && "Can't find vectorizable value");
6502 
6503     Value *Lane = Builder.getInt32(ExternalUse.Lane);
6504     auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
6505       if (Scalar->getType() != Vec->getType()) {
6506         Value *Ex;
6507         // "Reuse" the existing extract to improve final codegen.
6508         if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
6509           Ex = Builder.CreateExtractElement(ES->getOperand(0),
6510                                             ES->getOperand(1));
6511         } else {
6512           Ex = Builder.CreateExtractElement(Vec, Lane);
6513         }
6514         // If necessary, sign-extend or zero-extend ScalarRoot
6515         // to the larger type.
6516         if (!MinBWs.count(ScalarRoot))
6517           return Ex;
6518         if (MinBWs[ScalarRoot].second)
6519           return Builder.CreateSExt(Ex, Scalar->getType());
6520         return Builder.CreateZExt(Ex, Scalar->getType());
6521       }
6522       assert(isa<FixedVectorType>(Scalar->getType()) &&
6523              isa<InsertElementInst>(Scalar) &&
6524              "In-tree scalar of vector type is not insertelement?");
6525       return Vec;
6526     };
6527     // If User == nullptr, the Scalar is used as extra arg. Generate
6528     // ExtractElement instruction and update the record for this scalar in
6529     // ExternallyUsedValues.
6530     if (!User) {
6531       assert(ExternallyUsedValues.count(Scalar) &&
6532              "Scalar with nullptr as an external user must be registered in "
6533              "ExternallyUsedValues map");
6534       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6535         Builder.SetInsertPoint(VecI->getParent(),
6536                                std::next(VecI->getIterator()));
6537       } else {
6538         Builder.SetInsertPoint(&F->getEntryBlock().front());
6539       }
6540       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6541       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
6542       auto &NewInstLocs = ExternallyUsedValues[NewInst];
6543       auto It = ExternallyUsedValues.find(Scalar);
6544       assert(It != ExternallyUsedValues.end() &&
6545              "Externally used scalar is not found in ExternallyUsedValues");
6546       NewInstLocs.append(It->second);
6547       ExternallyUsedValues.erase(Scalar);
6548       // Required to update internally referenced instructions.
6549       Scalar->replaceAllUsesWith(NewInst);
6550       continue;
6551     }
6552 
6553     // Generate extracts for out-of-tree users.
6554     // Find the insertion point for the extractelement lane.
6555     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
6556       if (PHINode *PH = dyn_cast<PHINode>(User)) {
6557         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
6558           if (PH->getIncomingValue(i) == Scalar) {
6559             Instruction *IncomingTerminator =
6560                 PH->getIncomingBlock(i)->getTerminator();
6561             if (isa<CatchSwitchInst>(IncomingTerminator)) {
6562               Builder.SetInsertPoint(VecI->getParent(),
6563                                      std::next(VecI->getIterator()));
6564             } else {
6565               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
6566             }
6567             Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6568             CSEBlocks.insert(PH->getIncomingBlock(i));
6569             PH->setOperand(i, NewInst);
6570           }
6571         }
6572       } else {
6573         Builder.SetInsertPoint(cast<Instruction>(User));
6574         Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6575         CSEBlocks.insert(cast<Instruction>(User)->getParent());
6576         User->replaceUsesOfWith(Scalar, NewInst);
6577       }
6578     } else {
6579       Builder.SetInsertPoint(&F->getEntryBlock().front());
6580       Value *NewInst = ExtractAndExtendIfNeeded(Vec);
6581       CSEBlocks.insert(&F->getEntryBlock());
6582       User->replaceUsesOfWith(Scalar, NewInst);
6583     }
6584 
6585     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
6586   }
6587 
6588   // For each vectorized value:
6589   for (auto &TEPtr : VectorizableTree) {
6590     TreeEntry *Entry = TEPtr.get();
6591 
6592     // No need to handle users of gathered values.
6593     if (Entry->State == TreeEntry::NeedToGather)
6594       continue;
6595 
6596     assert(Entry->VectorizedValue && "Can't find vectorizable value");
6597 
6598     // For each lane:
6599     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
6600       Value *Scalar = Entry->Scalars[Lane];
6601 
6602 #ifndef NDEBUG
6603       Type *Ty = Scalar->getType();
6604       if (!Ty->isVoidTy()) {
6605         for (User *U : Scalar->users()) {
6606           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
6607 
6608           // It is legal to delete users in the ignorelist.
6609           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
6610                   (isa_and_nonnull<Instruction>(U) &&
6611                    isDeleted(cast<Instruction>(U)))) &&
6612                  "Deleting out-of-tree value");
6613         }
6614       }
6615 #endif
6616       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
6617       eraseInstruction(cast<Instruction>(Scalar));
6618     }
6619   }
6620 
6621   Builder.ClearInsertionPoint();
6622   InstrElementSize.clear();
6623 
6624   return VectorizableTree[0]->VectorizedValue;
6625 }
6626 
6627 void BoUpSLP::optimizeGatherSequence() {
6628   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
6629                     << " gather sequences instructions.\n");
6630   // LICM InsertElementInst sequences.
6631   for (Instruction *I : GatherSeq) {
6632     if (isDeleted(I))
6633       continue;
6634 
6635     // Check if this block is inside a loop.
6636     Loop *L = LI->getLoopFor(I->getParent());
6637     if (!L)
6638       continue;
6639 
6640     // Check if it has a preheader.
6641     BasicBlock *PreHeader = L->getLoopPreheader();
6642     if (!PreHeader)
6643       continue;
6644 
6645     // If the vector or the element that we insert into it are
6646     // instructions that are defined in this basic block then we can't
6647     // hoist this instruction.
6648     auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
6649     auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
6650     if (Op0 && L->contains(Op0))
6651       continue;
6652     if (Op1 && L->contains(Op1))
6653       continue;
6654 
6655     // We can hoist this instruction. Move it to the pre-header.
6656     I->moveBefore(PreHeader->getTerminator());
6657   }
6658 
6659   // Make a list of all reachable blocks in our CSE queue.
6660   SmallVector<const DomTreeNode *, 8> CSEWorkList;
6661   CSEWorkList.reserve(CSEBlocks.size());
6662   for (BasicBlock *BB : CSEBlocks)
6663     if (DomTreeNode *N = DT->getNode(BB)) {
6664       assert(DT->isReachableFromEntry(N));
6665       CSEWorkList.push_back(N);
6666     }
6667 
6668   // Sort blocks by domination. This ensures we visit a block after all blocks
6669   // dominating it are visited.
6670   llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
6671     assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
6672            "Different nodes should have different DFS numbers");
6673     return A->getDFSNumIn() < B->getDFSNumIn();
6674   });
6675 
6676   // Perform O(N^2) search over the gather sequences and merge identical
6677   // instructions. TODO: We can further optimize this scan if we split the
6678   // instructions into different buckets based on the insert lane.
6679   SmallVector<Instruction *, 16> Visited;
6680   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
6681     assert(*I &&
6682            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
6683            "Worklist not sorted properly!");
6684     BasicBlock *BB = (*I)->getBlock();
6685     // For all instructions in blocks containing gather sequences:
6686     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
6687       Instruction *In = &*it++;
6688       if (isDeleted(In))
6689         continue;
6690       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In) &&
6691           !isa<ShuffleVectorInst>(In))
6692         continue;
6693 
6694       // Check if we can replace this instruction with any of the
6695       // visited instructions.
6696       for (Instruction *v : Visited) {
6697         if (In->isIdenticalTo(v) &&
6698             DT->dominates(v->getParent(), In->getParent())) {
6699           In->replaceAllUsesWith(v);
6700           eraseInstruction(In);
6701           In = nullptr;
6702           break;
6703         }
6704       }
6705       if (In) {
6706         assert(!is_contained(Visited, In));
6707         Visited.push_back(In);
6708       }
6709     }
6710   }
6711   CSEBlocks.clear();
6712   GatherSeq.clear();
6713 }
6714 
6715 // Groups the instructions to a bundle (which is then a single scheduling entity)
6716 // and schedules instructions until the bundle gets ready.
6717 Optional<BoUpSLP::ScheduleData *>
6718 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
6719                                             const InstructionsState &S) {
6720   // No need to schedule PHIs, insertelement, extractelement and extractvalue
6721   // instructions.
6722   if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
6723     return nullptr;
6724 
6725   // Initialize the instruction bundle.
6726   Instruction *OldScheduleEnd = ScheduleEnd;
6727   ScheduleData *PrevInBundle = nullptr;
6728   ScheduleData *Bundle = nullptr;
6729   bool ReSchedule = false;
6730   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
6731 
6732   auto &&TryScheduleBundle = [this, OldScheduleEnd, SLP](bool ReSchedule,
6733                                                          ScheduleData *Bundle) {
6734     // The scheduling region got new instructions at the lower end (or it is a
6735     // new region for the first bundle). This makes it necessary to
6736     // recalculate all dependencies.
6737     // It is seldom that this needs to be done a second time after adding the
6738     // initial bundle to the region.
6739     if (ScheduleEnd != OldScheduleEnd) {
6740       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
6741         doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
6742       ReSchedule = true;
6743     }
6744     if (ReSchedule) {
6745       resetSchedule();
6746       initialFillReadyList(ReadyInsts);
6747     }
6748     if (Bundle) {
6749       LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
6750                         << " in block " << BB->getName() << "\n");
6751       calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
6752     }
6753 
6754     // Now try to schedule the new bundle or (if no bundle) just calculate
6755     // dependencies. As soon as the bundle is "ready" it means that there are no
6756     // cyclic dependencies and we can schedule it. Note that's important that we
6757     // don't "schedule" the bundle yet (see cancelScheduling).
6758     while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
6759            !ReadyInsts.empty()) {
6760       ScheduleData *Picked = ReadyInsts.pop_back_val();
6761       if (Picked->isSchedulingEntity() && Picked->isReady())
6762         schedule(Picked, ReadyInsts);
6763     }
6764   };
6765 
6766   // Make sure that the scheduling region contains all
6767   // instructions of the bundle.
6768   for (Value *V : VL) {
6769     if (!extendSchedulingRegion(V, S)) {
6770       // If the scheduling region got new instructions at the lower end (or it
6771       // is a new region for the first bundle). This makes it necessary to
6772       // recalculate all dependencies.
6773       // Otherwise the compiler may crash trying to incorrectly calculate
6774       // dependencies and emit instruction in the wrong order at the actual
6775       // scheduling.
6776       TryScheduleBundle(/*ReSchedule=*/false, nullptr);
6777       return None;
6778     }
6779   }
6780 
6781   for (Value *V : VL) {
6782     ScheduleData *BundleMember = getScheduleData(V);
6783     assert(BundleMember &&
6784            "no ScheduleData for bundle member (maybe not in same basic block)");
6785     if (BundleMember->IsScheduled) {
6786       // A bundle member was scheduled as single instruction before and now
6787       // needs to be scheduled as part of the bundle. We just get rid of the
6788       // existing schedule.
6789       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
6790                         << " was already scheduled\n");
6791       ReSchedule = true;
6792     }
6793     assert(BundleMember->isSchedulingEntity() &&
6794            "bundle member already part of other bundle");
6795     if (PrevInBundle) {
6796       PrevInBundle->NextInBundle = BundleMember;
6797     } else {
6798       Bundle = BundleMember;
6799     }
6800     BundleMember->UnscheduledDepsInBundle = 0;
6801     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
6802 
6803     // Group the instructions to a bundle.
6804     BundleMember->FirstInBundle = Bundle;
6805     PrevInBundle = BundleMember;
6806   }
6807   assert(Bundle && "Failed to find schedule bundle");
6808   TryScheduleBundle(ReSchedule, Bundle);
6809   if (!Bundle->isReady()) {
6810     cancelScheduling(VL, S.OpValue);
6811     return None;
6812   }
6813   return Bundle;
6814 }
6815 
6816 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
6817                                                 Value *OpValue) {
6818   if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
6819     return;
6820 
6821   ScheduleData *Bundle = getScheduleData(OpValue);
6822   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
6823   assert(!Bundle->IsScheduled &&
6824          "Can't cancel bundle which is already scheduled");
6825   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
6826          "tried to unbundle something which is not a bundle");
6827 
6828   // Un-bundle: make single instructions out of the bundle.
6829   ScheduleData *BundleMember = Bundle;
6830   while (BundleMember) {
6831     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
6832     BundleMember->FirstInBundle = BundleMember;
6833     ScheduleData *Next = BundleMember->NextInBundle;
6834     BundleMember->NextInBundle = nullptr;
6835     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
6836     if (BundleMember->UnscheduledDepsInBundle == 0) {
6837       ReadyInsts.insert(BundleMember);
6838     }
6839     BundleMember = Next;
6840   }
6841 }
6842 
6843 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
6844   // Allocate a new ScheduleData for the instruction.
6845   if (ChunkPos >= ChunkSize) {
6846     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
6847     ChunkPos = 0;
6848   }
6849   return &(ScheduleDataChunks.back()[ChunkPos++]);
6850 }
6851 
6852 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
6853                                                       const InstructionsState &S) {
6854   if (getScheduleData(V, isOneOf(S, V)))
6855     return true;
6856   Instruction *I = dyn_cast<Instruction>(V);
6857   assert(I && "bundle member must be an instruction");
6858   assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
6859          "phi nodes/insertelements/extractelements/extractvalues don't need to "
6860          "be scheduled");
6861   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
6862     ScheduleData *ISD = getScheduleData(I);
6863     if (!ISD)
6864       return false;
6865     assert(isInSchedulingRegion(ISD) &&
6866            "ScheduleData not in scheduling region");
6867     ScheduleData *SD = allocateScheduleDataChunks();
6868     SD->Inst = I;
6869     SD->init(SchedulingRegionID, S.OpValue);
6870     ExtraScheduleDataMap[I][S.OpValue] = SD;
6871     return true;
6872   };
6873   if (CheckSheduleForI(I))
6874     return true;
6875   if (!ScheduleStart) {
6876     // It's the first instruction in the new region.
6877     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
6878     ScheduleStart = I;
6879     ScheduleEnd = I->getNextNode();
6880     if (isOneOf(S, I) != I)
6881       CheckSheduleForI(I);
6882     assert(ScheduleEnd && "tried to vectorize a terminator?");
6883     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
6884     return true;
6885   }
6886   // Search up and down at the same time, because we don't know if the new
6887   // instruction is above or below the existing scheduling region.
6888   BasicBlock::reverse_iterator UpIter =
6889       ++ScheduleStart->getIterator().getReverse();
6890   BasicBlock::reverse_iterator UpperEnd = BB->rend();
6891   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
6892   BasicBlock::iterator LowerEnd = BB->end();
6893   while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
6894          &*DownIter != I) {
6895     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
6896       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
6897       return false;
6898     }
6899 
6900     ++UpIter;
6901     ++DownIter;
6902   }
6903   if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
6904     assert(I->getParent() == ScheduleStart->getParent() &&
6905            "Instruction is in wrong basic block.");
6906     initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
6907     ScheduleStart = I;
6908     if (isOneOf(S, I) != I)
6909       CheckSheduleForI(I);
6910     LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
6911                       << "\n");
6912     return true;
6913   }
6914   assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
6915          "Expected to reach top of the basic block or instruction down the "
6916          "lower end.");
6917   assert(I->getParent() == ScheduleEnd->getParent() &&
6918          "Instruction is in wrong basic block.");
6919   initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
6920                    nullptr);
6921   ScheduleEnd = I->getNextNode();
6922   if (isOneOf(S, I) != I)
6923     CheckSheduleForI(I);
6924   assert(ScheduleEnd && "tried to vectorize a terminator?");
6925   LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
6926   return true;
6927 }
6928 
6929 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
6930                                                 Instruction *ToI,
6931                                                 ScheduleData *PrevLoadStore,
6932                                                 ScheduleData *NextLoadStore) {
6933   ScheduleData *CurrentLoadStore = PrevLoadStore;
6934   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
6935     ScheduleData *SD = ScheduleDataMap[I];
6936     if (!SD) {
6937       SD = allocateScheduleDataChunks();
6938       ScheduleDataMap[I] = SD;
6939       SD->Inst = I;
6940     }
6941     assert(!isInSchedulingRegion(SD) &&
6942            "new ScheduleData already in scheduling region");
6943     SD->init(SchedulingRegionID, I);
6944 
6945     if (I->mayReadOrWriteMemory() &&
6946         (!isa<IntrinsicInst>(I) ||
6947          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
6948           cast<IntrinsicInst>(I)->getIntrinsicID() !=
6949               Intrinsic::pseudoprobe))) {
6950       // Update the linked list of memory accessing instructions.
6951       if (CurrentLoadStore) {
6952         CurrentLoadStore->NextLoadStore = SD;
6953       } else {
6954         FirstLoadStoreInRegion = SD;
6955       }
6956       CurrentLoadStore = SD;
6957     }
6958   }
6959   if (NextLoadStore) {
6960     if (CurrentLoadStore)
6961       CurrentLoadStore->NextLoadStore = NextLoadStore;
6962   } else {
6963     LastLoadStoreInRegion = CurrentLoadStore;
6964   }
6965 }
6966 
6967 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
6968                                                      bool InsertInReadyList,
6969                                                      BoUpSLP *SLP) {
6970   assert(SD->isSchedulingEntity());
6971 
6972   SmallVector<ScheduleData *, 10> WorkList;
6973   WorkList.push_back(SD);
6974 
6975   while (!WorkList.empty()) {
6976     ScheduleData *SD = WorkList.pop_back_val();
6977 
6978     ScheduleData *BundleMember = SD;
6979     while (BundleMember) {
6980       assert(isInSchedulingRegion(BundleMember));
6981       if (!BundleMember->hasValidDependencies()) {
6982 
6983         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
6984                           << "\n");
6985         BundleMember->Dependencies = 0;
6986         BundleMember->resetUnscheduledDeps();
6987 
6988         // Handle def-use chain dependencies.
6989         if (BundleMember->OpValue != BundleMember->Inst) {
6990           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
6991           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
6992             BundleMember->Dependencies++;
6993             ScheduleData *DestBundle = UseSD->FirstInBundle;
6994             if (!DestBundle->IsScheduled)
6995               BundleMember->incrementUnscheduledDeps(1);
6996             if (!DestBundle->hasValidDependencies())
6997               WorkList.push_back(DestBundle);
6998           }
6999         } else {
7000           for (User *U : BundleMember->Inst->users()) {
7001             if (isa<Instruction>(U)) {
7002               ScheduleData *UseSD = getScheduleData(U);
7003               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
7004                 BundleMember->Dependencies++;
7005                 ScheduleData *DestBundle = UseSD->FirstInBundle;
7006                 if (!DestBundle->IsScheduled)
7007                   BundleMember->incrementUnscheduledDeps(1);
7008                 if (!DestBundle->hasValidDependencies())
7009                   WorkList.push_back(DestBundle);
7010               }
7011             } else {
7012               // I'm not sure if this can ever happen. But we need to be safe.
7013               // This lets the instruction/bundle never be scheduled and
7014               // eventually disable vectorization.
7015               BundleMember->Dependencies++;
7016               BundleMember->incrementUnscheduledDeps(1);
7017             }
7018           }
7019         }
7020 
7021         // Handle the memory dependencies.
7022         ScheduleData *DepDest = BundleMember->NextLoadStore;
7023         if (DepDest) {
7024           Instruction *SrcInst = BundleMember->Inst;
7025           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
7026           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
7027           unsigned numAliased = 0;
7028           unsigned DistToSrc = 1;
7029 
7030           while (DepDest) {
7031             assert(isInSchedulingRegion(DepDest));
7032 
7033             // We have two limits to reduce the complexity:
7034             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
7035             //    SLP->isAliased (which is the expensive part in this loop).
7036             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
7037             //    the whole loop (even if the loop is fast, it's quadratic).
7038             //    It's important for the loop break condition (see below) to
7039             //    check this limit even between two read-only instructions.
7040             if (DistToSrc >= MaxMemDepDistance ||
7041                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
7042                      (numAliased >= AliasedCheckLimit ||
7043                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
7044 
7045               // We increment the counter only if the locations are aliased
7046               // (instead of counting all alias checks). This gives a better
7047               // balance between reduced runtime and accurate dependencies.
7048               numAliased++;
7049 
7050               DepDest->MemoryDependencies.push_back(BundleMember);
7051               BundleMember->Dependencies++;
7052               ScheduleData *DestBundle = DepDest->FirstInBundle;
7053               if (!DestBundle->IsScheduled) {
7054                 BundleMember->incrementUnscheduledDeps(1);
7055               }
7056               if (!DestBundle->hasValidDependencies()) {
7057                 WorkList.push_back(DestBundle);
7058               }
7059             }
7060             DepDest = DepDest->NextLoadStore;
7061 
7062             // Example, explaining the loop break condition: Let's assume our
7063             // starting instruction is i0 and MaxMemDepDistance = 3.
7064             //
7065             //                      +--------v--v--v
7066             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
7067             //             +--------^--^--^
7068             //
7069             // MaxMemDepDistance let us stop alias-checking at i3 and we add
7070             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
7071             // Previously we already added dependencies from i3 to i6,i7,i8
7072             // (because of MaxMemDepDistance). As we added a dependency from
7073             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
7074             // and we can abort this loop at i6.
7075             if (DistToSrc >= 2 * MaxMemDepDistance)
7076               break;
7077             DistToSrc++;
7078           }
7079         }
7080       }
7081       BundleMember = BundleMember->NextInBundle;
7082     }
7083     if (InsertInReadyList && SD->isReady()) {
7084       ReadyInsts.push_back(SD);
7085       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
7086                         << "\n");
7087     }
7088   }
7089 }
7090 
7091 void BoUpSLP::BlockScheduling::resetSchedule() {
7092   assert(ScheduleStart &&
7093          "tried to reset schedule on block which has not been scheduled");
7094   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
7095     doForAllOpcodes(I, [&](ScheduleData *SD) {
7096       assert(isInSchedulingRegion(SD) &&
7097              "ScheduleData not in scheduling region");
7098       SD->IsScheduled = false;
7099       SD->resetUnscheduledDeps();
7100     });
7101   }
7102   ReadyInsts.clear();
7103 }
7104 
7105 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
7106   if (!BS->ScheduleStart)
7107     return;
7108 
7109   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
7110 
7111   BS->resetSchedule();
7112 
7113   // For the real scheduling we use a more sophisticated ready-list: it is
7114   // sorted by the original instruction location. This lets the final schedule
7115   // be as  close as possible to the original instruction order.
7116   struct ScheduleDataCompare {
7117     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
7118       return SD2->SchedulingPriority < SD1->SchedulingPriority;
7119     }
7120   };
7121   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
7122 
7123   // Ensure that all dependency data is updated and fill the ready-list with
7124   // initial instructions.
7125   int Idx = 0;
7126   int NumToSchedule = 0;
7127   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
7128        I = I->getNextNode()) {
7129     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
7130       assert((isVectorLikeInstWithConstOps(SD->Inst) ||
7131               SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
7132              "scheduler and vectorizer bundle mismatch");
7133       SD->FirstInBundle->SchedulingPriority = Idx++;
7134       if (SD->isSchedulingEntity()) {
7135         BS->calculateDependencies(SD, false, this);
7136         NumToSchedule++;
7137       }
7138     });
7139   }
7140   BS->initialFillReadyList(ReadyInsts);
7141 
7142   Instruction *LastScheduledInst = BS->ScheduleEnd;
7143 
7144   // Do the "real" scheduling.
7145   while (!ReadyInsts.empty()) {
7146     ScheduleData *picked = *ReadyInsts.begin();
7147     ReadyInsts.erase(ReadyInsts.begin());
7148 
7149     // Move the scheduled instruction(s) to their dedicated places, if not
7150     // there yet.
7151     ScheduleData *BundleMember = picked;
7152     while (BundleMember) {
7153       Instruction *pickedInst = BundleMember->Inst;
7154       if (pickedInst->getNextNode() != LastScheduledInst) {
7155         BS->BB->getInstList().remove(pickedInst);
7156         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
7157                                      pickedInst);
7158       }
7159       LastScheduledInst = pickedInst;
7160       BundleMember = BundleMember->NextInBundle;
7161     }
7162 
7163     BS->schedule(picked, ReadyInsts);
7164     NumToSchedule--;
7165   }
7166   assert(NumToSchedule == 0 && "could not schedule all instructions");
7167 
7168   // Avoid duplicate scheduling of the block.
7169   BS->ScheduleStart = nullptr;
7170 }
7171 
7172 unsigned BoUpSLP::getVectorElementSize(Value *V) {
7173   // If V is a store, just return the width of the stored value (or value
7174   // truncated just before storing) without traversing the expression tree.
7175   // This is the common case.
7176   if (auto *Store = dyn_cast<StoreInst>(V)) {
7177     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
7178       return DL->getTypeSizeInBits(Trunc->getSrcTy());
7179     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
7180   }
7181 
7182   if (auto *IEI = dyn_cast<InsertElementInst>(V))
7183     return getVectorElementSize(IEI->getOperand(1));
7184 
7185   auto E = InstrElementSize.find(V);
7186   if (E != InstrElementSize.end())
7187     return E->second;
7188 
7189   // If V is not a store, we can traverse the expression tree to find loads
7190   // that feed it. The type of the loaded value may indicate a more suitable
7191   // width than V's type. We want to base the vector element size on the width
7192   // of memory operations where possible.
7193   SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
7194   SmallPtrSet<Instruction *, 16> Visited;
7195   if (auto *I = dyn_cast<Instruction>(V)) {
7196     Worklist.emplace_back(I, I->getParent());
7197     Visited.insert(I);
7198   }
7199 
7200   // Traverse the expression tree in bottom-up order looking for loads. If we
7201   // encounter an instruction we don't yet handle, we give up.
7202   auto Width = 0u;
7203   while (!Worklist.empty()) {
7204     Instruction *I;
7205     BasicBlock *Parent;
7206     std::tie(I, Parent) = Worklist.pop_back_val();
7207 
7208     // We should only be looking at scalar instructions here. If the current
7209     // instruction has a vector type, skip.
7210     auto *Ty = I->getType();
7211     if (isa<VectorType>(Ty))
7212       continue;
7213 
7214     // If the current instruction is a load, update MaxWidth to reflect the
7215     // width of the loaded value.
7216     if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
7217         isa<ExtractValueInst>(I))
7218       Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
7219 
7220     // Otherwise, we need to visit the operands of the instruction. We only
7221     // handle the interesting cases from buildTree here. If an operand is an
7222     // instruction we haven't yet visited and from the same basic block as the
7223     // user or the use is a PHI node, we add it to the worklist.
7224     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
7225              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
7226              isa<UnaryOperator>(I)) {
7227       for (Use &U : I->operands())
7228         if (auto *J = dyn_cast<Instruction>(U.get()))
7229           if (Visited.insert(J).second &&
7230               (isa<PHINode>(I) || J->getParent() == Parent))
7231             Worklist.emplace_back(J, J->getParent());
7232     } else {
7233       break;
7234     }
7235   }
7236 
7237   // If we didn't encounter a memory access in the expression tree, or if we
7238   // gave up for some reason, just return the width of V. Otherwise, return the
7239   // maximum width we found.
7240   if (!Width) {
7241     if (auto *CI = dyn_cast<CmpInst>(V))
7242       V = CI->getOperand(0);
7243     Width = DL->getTypeSizeInBits(V->getType());
7244   }
7245 
7246   for (Instruction *I : Visited)
7247     InstrElementSize[I] = Width;
7248 
7249   return Width;
7250 }
7251 
7252 // Determine if a value V in a vectorizable expression Expr can be demoted to a
7253 // smaller type with a truncation. We collect the values that will be demoted
7254 // in ToDemote and additional roots that require investigating in Roots.
7255 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
7256                                   SmallVectorImpl<Value *> &ToDemote,
7257                                   SmallVectorImpl<Value *> &Roots) {
7258   // We can always demote constants.
7259   if (isa<Constant>(V)) {
7260     ToDemote.push_back(V);
7261     return true;
7262   }
7263 
7264   // If the value is not an instruction in the expression with only one use, it
7265   // cannot be demoted.
7266   auto *I = dyn_cast<Instruction>(V);
7267   if (!I || !I->hasOneUse() || !Expr.count(I))
7268     return false;
7269 
7270   switch (I->getOpcode()) {
7271 
7272   // We can always demote truncations and extensions. Since truncations can
7273   // seed additional demotion, we save the truncated value.
7274   case Instruction::Trunc:
7275     Roots.push_back(I->getOperand(0));
7276     break;
7277   case Instruction::ZExt:
7278   case Instruction::SExt:
7279     if (isa<ExtractElementInst>(I->getOperand(0)) ||
7280         isa<InsertElementInst>(I->getOperand(0)))
7281       return false;
7282     break;
7283 
7284   // We can demote certain binary operations if we can demote both of their
7285   // operands.
7286   case Instruction::Add:
7287   case Instruction::Sub:
7288   case Instruction::Mul:
7289   case Instruction::And:
7290   case Instruction::Or:
7291   case Instruction::Xor:
7292     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
7293         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
7294       return false;
7295     break;
7296 
7297   // We can demote selects if we can demote their true and false values.
7298   case Instruction::Select: {
7299     SelectInst *SI = cast<SelectInst>(I);
7300     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
7301         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
7302       return false;
7303     break;
7304   }
7305 
7306   // We can demote phis if we can demote all their incoming operands. Note that
7307   // we don't need to worry about cycles since we ensure single use above.
7308   case Instruction::PHI: {
7309     PHINode *PN = cast<PHINode>(I);
7310     for (Value *IncValue : PN->incoming_values())
7311       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
7312         return false;
7313     break;
7314   }
7315 
7316   // Otherwise, conservatively give up.
7317   default:
7318     return false;
7319   }
7320 
7321   // Record the value that we can demote.
7322   ToDemote.push_back(V);
7323   return true;
7324 }
7325 
7326 void BoUpSLP::computeMinimumValueSizes() {
7327   // If there are no external uses, the expression tree must be rooted by a
7328   // store. We can't demote in-memory values, so there is nothing to do here.
7329   if (ExternalUses.empty())
7330     return;
7331 
7332   // We only attempt to truncate integer expressions.
7333   auto &TreeRoot = VectorizableTree[0]->Scalars;
7334   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
7335   if (!TreeRootIT)
7336     return;
7337 
7338   // If the expression is not rooted by a store, these roots should have
7339   // external uses. We will rely on InstCombine to rewrite the expression in
7340   // the narrower type. However, InstCombine only rewrites single-use values.
7341   // This means that if a tree entry other than a root is used externally, it
7342   // must have multiple uses and InstCombine will not rewrite it. The code
7343   // below ensures that only the roots are used externally.
7344   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
7345   for (auto &EU : ExternalUses)
7346     if (!Expr.erase(EU.Scalar))
7347       return;
7348   if (!Expr.empty())
7349     return;
7350 
7351   // Collect the scalar values of the vectorizable expression. We will use this
7352   // context to determine which values can be demoted. If we see a truncation,
7353   // we mark it as seeding another demotion.
7354   for (auto &EntryPtr : VectorizableTree)
7355     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
7356 
7357   // Ensure the roots of the vectorizable tree don't form a cycle. They must
7358   // have a single external user that is not in the vectorizable tree.
7359   for (auto *Root : TreeRoot)
7360     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
7361       return;
7362 
7363   // Conservatively determine if we can actually truncate the roots of the
7364   // expression. Collect the values that can be demoted in ToDemote and
7365   // additional roots that require investigating in Roots.
7366   SmallVector<Value *, 32> ToDemote;
7367   SmallVector<Value *, 4> Roots;
7368   for (auto *Root : TreeRoot)
7369     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
7370       return;
7371 
7372   // The maximum bit width required to represent all the values that can be
7373   // demoted without loss of precision. It would be safe to truncate the roots
7374   // of the expression to this width.
7375   auto MaxBitWidth = 8u;
7376 
7377   // We first check if all the bits of the roots are demanded. If they're not,
7378   // we can truncate the roots to this narrower type.
7379   for (auto *Root : TreeRoot) {
7380     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
7381     MaxBitWidth = std::max<unsigned>(
7382         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
7383   }
7384 
7385   // True if the roots can be zero-extended back to their original type, rather
7386   // than sign-extended. We know that if the leading bits are not demanded, we
7387   // can safely zero-extend. So we initialize IsKnownPositive to True.
7388   bool IsKnownPositive = true;
7389 
7390   // If all the bits of the roots are demanded, we can try a little harder to
7391   // compute a narrower type. This can happen, for example, if the roots are
7392   // getelementptr indices. InstCombine promotes these indices to the pointer
7393   // width. Thus, all their bits are technically demanded even though the
7394   // address computation might be vectorized in a smaller type.
7395   //
7396   // We start by looking at each entry that can be demoted. We compute the
7397   // maximum bit width required to store the scalar by using ValueTracking to
7398   // compute the number of high-order bits we can truncate.
7399   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
7400       llvm::all_of(TreeRoot, [](Value *R) {
7401         assert(R->hasOneUse() && "Root should have only one use!");
7402         return isa<GetElementPtrInst>(R->user_back());
7403       })) {
7404     MaxBitWidth = 8u;
7405 
7406     // Determine if the sign bit of all the roots is known to be zero. If not,
7407     // IsKnownPositive is set to False.
7408     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
7409       KnownBits Known = computeKnownBits(R, *DL);
7410       return Known.isNonNegative();
7411     });
7412 
7413     // Determine the maximum number of bits required to store the scalar
7414     // values.
7415     for (auto *Scalar : ToDemote) {
7416       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
7417       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
7418       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
7419     }
7420 
7421     // If we can't prove that the sign bit is zero, we must add one to the
7422     // maximum bit width to account for the unknown sign bit. This preserves
7423     // the existing sign bit so we can safely sign-extend the root back to the
7424     // original type. Otherwise, if we know the sign bit is zero, we will
7425     // zero-extend the root instead.
7426     //
7427     // FIXME: This is somewhat suboptimal, as there will be cases where adding
7428     //        one to the maximum bit width will yield a larger-than-necessary
7429     //        type. In general, we need to add an extra bit only if we can't
7430     //        prove that the upper bit of the original type is equal to the
7431     //        upper bit of the proposed smaller type. If these two bits are the
7432     //        same (either zero or one) we know that sign-extending from the
7433     //        smaller type will result in the same value. Here, since we can't
7434     //        yet prove this, we are just making the proposed smaller type
7435     //        larger to ensure correctness.
7436     if (!IsKnownPositive)
7437       ++MaxBitWidth;
7438   }
7439 
7440   // Round MaxBitWidth up to the next power-of-two.
7441   if (!isPowerOf2_64(MaxBitWidth))
7442     MaxBitWidth = NextPowerOf2(MaxBitWidth);
7443 
7444   // If the maximum bit width we compute is less than the with of the roots'
7445   // type, we can proceed with the narrowing. Otherwise, do nothing.
7446   if (MaxBitWidth >= TreeRootIT->getBitWidth())
7447     return;
7448 
7449   // If we can truncate the root, we must collect additional values that might
7450   // be demoted as a result. That is, those seeded by truncations we will
7451   // modify.
7452   while (!Roots.empty())
7453     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
7454 
7455   // Finally, map the values we can demote to the maximum bit with we computed.
7456   for (auto *Scalar : ToDemote)
7457     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
7458 }
7459 
7460 namespace {
7461 
7462 /// The SLPVectorizer Pass.
7463 struct SLPVectorizer : public FunctionPass {
7464   SLPVectorizerPass Impl;
7465 
7466   /// Pass identification, replacement for typeid
7467   static char ID;
7468 
7469   explicit SLPVectorizer() : FunctionPass(ID) {
7470     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
7471   }
7472 
7473   bool doInitialization(Module &M) override { return false; }
7474 
7475   bool runOnFunction(Function &F) override {
7476     if (skipFunction(F))
7477       return false;
7478 
7479     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
7480     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
7481     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
7482     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
7483     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
7484     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
7485     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
7486     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
7487     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
7488     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
7489 
7490     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
7491   }
7492 
7493   void getAnalysisUsage(AnalysisUsage &AU) const override {
7494     FunctionPass::getAnalysisUsage(AU);
7495     AU.addRequired<AssumptionCacheTracker>();
7496     AU.addRequired<ScalarEvolutionWrapperPass>();
7497     AU.addRequired<AAResultsWrapperPass>();
7498     AU.addRequired<TargetTransformInfoWrapperPass>();
7499     AU.addRequired<LoopInfoWrapperPass>();
7500     AU.addRequired<DominatorTreeWrapperPass>();
7501     AU.addRequired<DemandedBitsWrapperPass>();
7502     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
7503     AU.addRequired<InjectTLIMappingsLegacy>();
7504     AU.addPreserved<LoopInfoWrapperPass>();
7505     AU.addPreserved<DominatorTreeWrapperPass>();
7506     AU.addPreserved<AAResultsWrapperPass>();
7507     AU.addPreserved<GlobalsAAWrapperPass>();
7508     AU.setPreservesCFG();
7509   }
7510 };
7511 
7512 } // end anonymous namespace
7513 
7514 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
7515   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
7516   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
7517   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
7518   auto *AA = &AM.getResult<AAManager>(F);
7519   auto *LI = &AM.getResult<LoopAnalysis>(F);
7520   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
7521   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
7522   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
7523   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
7524 
7525   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
7526   if (!Changed)
7527     return PreservedAnalyses::all();
7528 
7529   PreservedAnalyses PA;
7530   PA.preserveSet<CFGAnalyses>();
7531   return PA;
7532 }
7533 
7534 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
7535                                 TargetTransformInfo *TTI_,
7536                                 TargetLibraryInfo *TLI_, AAResults *AA_,
7537                                 LoopInfo *LI_, DominatorTree *DT_,
7538                                 AssumptionCache *AC_, DemandedBits *DB_,
7539                                 OptimizationRemarkEmitter *ORE_) {
7540   if (!RunSLPVectorization)
7541     return false;
7542   SE = SE_;
7543   TTI = TTI_;
7544   TLI = TLI_;
7545   AA = AA_;
7546   LI = LI_;
7547   DT = DT_;
7548   AC = AC_;
7549   DB = DB_;
7550   DL = &F.getParent()->getDataLayout();
7551 
7552   Stores.clear();
7553   GEPs.clear();
7554   bool Changed = false;
7555 
7556   // If the target claims to have no vector registers don't attempt
7557   // vectorization.
7558   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)))
7559     return false;
7560 
7561   // Don't vectorize when the attribute NoImplicitFloat is used.
7562   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
7563     return false;
7564 
7565   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
7566 
7567   // Use the bottom up slp vectorizer to construct chains that start with
7568   // store instructions.
7569   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
7570 
7571   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
7572   // delete instructions.
7573 
7574   // Update DFS numbers now so that we can use them for ordering.
7575   DT->updateDFSNumbers();
7576 
7577   // Scan the blocks in the function in post order.
7578   for (auto BB : post_order(&F.getEntryBlock())) {
7579     collectSeedInstructions(BB);
7580 
7581     // Vectorize trees that end at stores.
7582     if (!Stores.empty()) {
7583       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
7584                         << " underlying objects.\n");
7585       Changed |= vectorizeStoreChains(R);
7586     }
7587 
7588     // Vectorize trees that end at reductions.
7589     Changed |= vectorizeChainsInBlock(BB, R);
7590 
7591     // Vectorize the index computations of getelementptr instructions. This
7592     // is primarily intended to catch gather-like idioms ending at
7593     // non-consecutive loads.
7594     if (!GEPs.empty()) {
7595       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
7596                         << " underlying objects.\n");
7597       Changed |= vectorizeGEPIndices(BB, R);
7598     }
7599   }
7600 
7601   if (Changed) {
7602     R.optimizeGatherSequence();
7603     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
7604   }
7605   return Changed;
7606 }
7607 
7608 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
7609                                             unsigned Idx) {
7610   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
7611                     << "\n");
7612   const unsigned Sz = R.getVectorElementSize(Chain[0]);
7613   const unsigned MinVF = R.getMinVecRegSize() / Sz;
7614   unsigned VF = Chain.size();
7615 
7616   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
7617     return false;
7618 
7619   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
7620                     << "\n");
7621 
7622   R.buildTree(Chain);
7623   if (R.isTreeTinyAndNotFullyVectorizable())
7624     return false;
7625   if (R.isLoadCombineCandidate())
7626     return false;
7627   R.reorderTopToBottom();
7628   R.reorderBottomToTop();
7629   R.buildExternalUses();
7630 
7631   R.computeMinimumValueSizes();
7632 
7633   InstructionCost Cost = R.getTreeCost();
7634 
7635   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
7636   if (Cost < -SLPCostThreshold) {
7637     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
7638 
7639     using namespace ore;
7640 
7641     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
7642                                         cast<StoreInst>(Chain[0]))
7643                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
7644                      << " and with tree size "
7645                      << NV("TreeSize", R.getTreeSize()));
7646 
7647     R.vectorizeTree();
7648     return true;
7649   }
7650 
7651   return false;
7652 }
7653 
7654 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
7655                                         BoUpSLP &R) {
7656   // We may run into multiple chains that merge into a single chain. We mark the
7657   // stores that we vectorized so that we don't visit the same store twice.
7658   BoUpSLP::ValueSet VectorizedStores;
7659   bool Changed = false;
7660 
7661   int E = Stores.size();
7662   SmallBitVector Tails(E, false);
7663   int MaxIter = MaxStoreLookup.getValue();
7664   SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
7665       E, std::make_pair(E, INT_MAX));
7666   SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
7667   int IterCnt;
7668   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
7669                                   &CheckedPairs,
7670                                   &ConsecutiveChain](int K, int Idx) {
7671     if (IterCnt >= MaxIter)
7672       return true;
7673     if (CheckedPairs[Idx].test(K))
7674       return ConsecutiveChain[K].second == 1 &&
7675              ConsecutiveChain[K].first == Idx;
7676     ++IterCnt;
7677     CheckedPairs[Idx].set(K);
7678     CheckedPairs[K].set(Idx);
7679     Optional<int> Diff = getPointersDiff(
7680         Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
7681         Stores[Idx]->getValueOperand()->getType(),
7682         Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
7683     if (!Diff || *Diff == 0)
7684       return false;
7685     int Val = *Diff;
7686     if (Val < 0) {
7687       if (ConsecutiveChain[Idx].second > -Val) {
7688         Tails.set(K);
7689         ConsecutiveChain[Idx] = std::make_pair(K, -Val);
7690       }
7691       return false;
7692     }
7693     if (ConsecutiveChain[K].second <= Val)
7694       return false;
7695 
7696     Tails.set(Idx);
7697     ConsecutiveChain[K] = std::make_pair(Idx, Val);
7698     return Val == 1;
7699   };
7700   // Do a quadratic search on all of the given stores in reverse order and find
7701   // all of the pairs of stores that follow each other.
7702   for (int Idx = E - 1; Idx >= 0; --Idx) {
7703     // If a store has multiple consecutive store candidates, search according
7704     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
7705     // This is because usually pairing with immediate succeeding or preceding
7706     // candidate create the best chance to find slp vectorization opportunity.
7707     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
7708     IterCnt = 0;
7709     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
7710       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
7711           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
7712         break;
7713   }
7714 
7715   // Tracks if we tried to vectorize stores starting from the given tail
7716   // already.
7717   SmallBitVector TriedTails(E, false);
7718   // For stores that start but don't end a link in the chain:
7719   for (int Cnt = E; Cnt > 0; --Cnt) {
7720     int I = Cnt - 1;
7721     if (ConsecutiveChain[I].first == E || Tails.test(I))
7722       continue;
7723     // We found a store instr that starts a chain. Now follow the chain and try
7724     // to vectorize it.
7725     BoUpSLP::ValueList Operands;
7726     // Collect the chain into a list.
7727     while (I != E && !VectorizedStores.count(Stores[I])) {
7728       Operands.push_back(Stores[I]);
7729       Tails.set(I);
7730       if (ConsecutiveChain[I].second != 1) {
7731         // Mark the new end in the chain and go back, if required. It might be
7732         // required if the original stores come in reversed order, for example.
7733         if (ConsecutiveChain[I].first != E &&
7734             Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
7735             !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
7736           TriedTails.set(I);
7737           Tails.reset(ConsecutiveChain[I].first);
7738           if (Cnt < ConsecutiveChain[I].first + 2)
7739             Cnt = ConsecutiveChain[I].first + 2;
7740         }
7741         break;
7742       }
7743       // Move to the next value in the chain.
7744       I = ConsecutiveChain[I].first;
7745     }
7746     assert(!Operands.empty() && "Expected non-empty list of stores.");
7747 
7748     unsigned MaxVecRegSize = R.getMaxVecRegSize();
7749     unsigned EltSize = R.getVectorElementSize(Operands[0]);
7750     unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
7751 
7752     unsigned MinVF = R.getMinVF(EltSize);
7753     unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
7754                               MaxElts);
7755 
7756     // FIXME: Is division-by-2 the correct step? Should we assert that the
7757     // register size is a power-of-2?
7758     unsigned StartIdx = 0;
7759     for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
7760       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
7761         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
7762         if (!VectorizedStores.count(Slice.front()) &&
7763             !VectorizedStores.count(Slice.back()) &&
7764             vectorizeStoreChain(Slice, R, Cnt)) {
7765           // Mark the vectorized stores so that we don't vectorize them again.
7766           VectorizedStores.insert(Slice.begin(), Slice.end());
7767           Changed = true;
7768           // If we vectorized initial block, no need to try to vectorize it
7769           // again.
7770           if (Cnt == StartIdx)
7771             StartIdx += Size;
7772           Cnt += Size;
7773           continue;
7774         }
7775         ++Cnt;
7776       }
7777       // Check if the whole array was vectorized already - exit.
7778       if (StartIdx >= Operands.size())
7779         break;
7780     }
7781   }
7782 
7783   return Changed;
7784 }
7785 
7786 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
7787   // Initialize the collections. We will make a single pass over the block.
7788   Stores.clear();
7789   GEPs.clear();
7790 
7791   // Visit the store and getelementptr instructions in BB and organize them in
7792   // Stores and GEPs according to the underlying objects of their pointer
7793   // operands.
7794   for (Instruction &I : *BB) {
7795     // Ignore store instructions that are volatile or have a pointer operand
7796     // that doesn't point to a scalar type.
7797     if (auto *SI = dyn_cast<StoreInst>(&I)) {
7798       if (!SI->isSimple())
7799         continue;
7800       if (!isValidElementType(SI->getValueOperand()->getType()))
7801         continue;
7802       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
7803     }
7804 
7805     // Ignore getelementptr instructions that have more than one index, a
7806     // constant index, or a pointer operand that doesn't point to a scalar
7807     // type.
7808     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
7809       auto Idx = GEP->idx_begin()->get();
7810       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
7811         continue;
7812       if (!isValidElementType(Idx->getType()))
7813         continue;
7814       if (GEP->getType()->isVectorTy())
7815         continue;
7816       GEPs[GEP->getPointerOperand()].push_back(GEP);
7817     }
7818   }
7819 }
7820 
7821 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
7822   if (!A || !B)
7823     return false;
7824   Value *VL[] = {A, B};
7825   return tryToVectorizeList(VL, R);
7826 }
7827 
7828 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
7829                                            bool LimitForRegisterSize) {
7830   if (VL.size() < 2)
7831     return false;
7832 
7833   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
7834                     << VL.size() << ".\n");
7835 
7836   // Check that all of the parts are instructions of the same type,
7837   // we permit an alternate opcode via InstructionsState.
7838   InstructionsState S = getSameOpcode(VL);
7839   if (!S.getOpcode())
7840     return false;
7841 
7842   Instruction *I0 = cast<Instruction>(S.OpValue);
7843   // Make sure invalid types (including vector type) are rejected before
7844   // determining vectorization factor for scalar instructions.
7845   for (Value *V : VL) {
7846     Type *Ty = V->getType();
7847     if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
7848       // NOTE: the following will give user internal llvm type name, which may
7849       // not be useful.
7850       R.getORE()->emit([&]() {
7851         std::string type_str;
7852         llvm::raw_string_ostream rso(type_str);
7853         Ty->print(rso);
7854         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
7855                << "Cannot SLP vectorize list: type "
7856                << rso.str() + " is unsupported by vectorizer";
7857       });
7858       return false;
7859     }
7860   }
7861 
7862   unsigned Sz = R.getVectorElementSize(I0);
7863   unsigned MinVF = R.getMinVF(Sz);
7864   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
7865   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
7866   if (MaxVF < 2) {
7867     R.getORE()->emit([&]() {
7868       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
7869              << "Cannot SLP vectorize list: vectorization factor "
7870              << "less than 2 is not supported";
7871     });
7872     return false;
7873   }
7874 
7875   bool Changed = false;
7876   bool CandidateFound = false;
7877   InstructionCost MinCost = SLPCostThreshold.getValue();
7878   Type *ScalarTy = VL[0]->getType();
7879   if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
7880     ScalarTy = IE->getOperand(1)->getType();
7881 
7882   unsigned NextInst = 0, MaxInst = VL.size();
7883   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
7884     // No actual vectorization should happen, if number of parts is the same as
7885     // provided vectorization factor (i.e. the scalar type is used for vector
7886     // code during codegen).
7887     auto *VecTy = FixedVectorType::get(ScalarTy, VF);
7888     if (TTI->getNumberOfParts(VecTy) == VF)
7889       continue;
7890     for (unsigned I = NextInst; I < MaxInst; ++I) {
7891       unsigned OpsWidth = 0;
7892 
7893       if (I + VF > MaxInst)
7894         OpsWidth = MaxInst - I;
7895       else
7896         OpsWidth = VF;
7897 
7898       if (!isPowerOf2_32(OpsWidth))
7899         continue;
7900 
7901       if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
7902           (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
7903         break;
7904 
7905       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
7906       // Check that a previous iteration of this loop did not delete the Value.
7907       if (llvm::any_of(Ops, [&R](Value *V) {
7908             auto *I = dyn_cast<Instruction>(V);
7909             return I && R.isDeleted(I);
7910           }))
7911         continue;
7912 
7913       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
7914                         << "\n");
7915 
7916       R.buildTree(Ops);
7917       if (R.isTreeTinyAndNotFullyVectorizable())
7918         continue;
7919       R.reorderTopToBottom();
7920       R.reorderBottomToTop();
7921       R.buildExternalUses();
7922 
7923       R.computeMinimumValueSizes();
7924       InstructionCost Cost = R.getTreeCost();
7925       CandidateFound = true;
7926       MinCost = std::min(MinCost, Cost);
7927 
7928       if (Cost < -SLPCostThreshold) {
7929         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
7930         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
7931                                                     cast<Instruction>(Ops[0]))
7932                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
7933                                  << " and with tree size "
7934                                  << ore::NV("TreeSize", R.getTreeSize()));
7935 
7936         R.vectorizeTree();
7937         // Move to the next bundle.
7938         I += VF - 1;
7939         NextInst = I + 1;
7940         Changed = true;
7941       }
7942     }
7943   }
7944 
7945   if (!Changed && CandidateFound) {
7946     R.getORE()->emit([&]() {
7947       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
7948              << "List vectorization was possible but not beneficial with cost "
7949              << ore::NV("Cost", MinCost) << " >= "
7950              << ore::NV("Treshold", -SLPCostThreshold);
7951     });
7952   } else if (!Changed) {
7953     R.getORE()->emit([&]() {
7954       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
7955              << "Cannot SLP vectorize list: vectorization was impossible"
7956              << " with available vectorization factors";
7957     });
7958   }
7959   return Changed;
7960 }
7961 
7962 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
7963   if (!I)
7964     return false;
7965 
7966   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
7967     return false;
7968 
7969   Value *P = I->getParent();
7970 
7971   // Vectorize in current basic block only.
7972   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
7973   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
7974   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
7975     return false;
7976 
7977   // Try to vectorize V.
7978   if (tryToVectorizePair(Op0, Op1, R))
7979     return true;
7980 
7981   auto *A = dyn_cast<BinaryOperator>(Op0);
7982   auto *B = dyn_cast<BinaryOperator>(Op1);
7983   // Try to skip B.
7984   if (B && B->hasOneUse()) {
7985     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
7986     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
7987     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
7988       return true;
7989     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
7990       return true;
7991   }
7992 
7993   // Try to skip A.
7994   if (A && A->hasOneUse()) {
7995     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
7996     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
7997     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
7998       return true;
7999     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
8000       return true;
8001   }
8002   return false;
8003 }
8004 
8005 namespace {
8006 
8007 /// Model horizontal reductions.
8008 ///
8009 /// A horizontal reduction is a tree of reduction instructions that has values
8010 /// that can be put into a vector as its leaves. For example:
8011 ///
8012 /// mul mul mul mul
8013 ///  \  /    \  /
8014 ///   +       +
8015 ///    \     /
8016 ///       +
8017 /// This tree has "mul" as its leaf values and "+" as its reduction
8018 /// instructions. A reduction can feed into a store or a binary operation
8019 /// feeding a phi.
8020 ///    ...
8021 ///    \  /
8022 ///     +
8023 ///     |
8024 ///  phi +=
8025 ///
8026 ///  Or:
8027 ///    ...
8028 ///    \  /
8029 ///     +
8030 ///     |
8031 ///   *p =
8032 ///
8033 class HorizontalReduction {
8034   using ReductionOpsType = SmallVector<Value *, 16>;
8035   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
8036   ReductionOpsListType ReductionOps;
8037   SmallVector<Value *, 32> ReducedVals;
8038   // Use map vector to make stable output.
8039   MapVector<Instruction *, Value *> ExtraArgs;
8040   WeakTrackingVH ReductionRoot;
8041   /// The type of reduction operation.
8042   RecurKind RdxKind;
8043 
8044   const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
8045 
8046   static bool isCmpSelMinMax(Instruction *I) {
8047     return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
8048            RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
8049   }
8050 
8051   // And/or are potentially poison-safe logical patterns like:
8052   // select x, y, false
8053   // select x, true, y
8054   static bool isBoolLogicOp(Instruction *I) {
8055     return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
8056            match(I, m_LogicalOr(m_Value(), m_Value()));
8057   }
8058 
8059   /// Checks if instruction is associative and can be vectorized.
8060   static bool isVectorizable(RecurKind Kind, Instruction *I) {
8061     if (Kind == RecurKind::None)
8062       return false;
8063 
8064     // Integer ops that map to select instructions or intrinsics are fine.
8065     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
8066         isBoolLogicOp(I))
8067       return true;
8068 
8069     if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
8070       // FP min/max are associative except for NaN and -0.0. We do not
8071       // have to rule out -0.0 here because the intrinsic semantics do not
8072       // specify a fixed result for it.
8073       return I->getFastMathFlags().noNaNs();
8074     }
8075 
8076     return I->isAssociative();
8077   }
8078 
8079   static Value *getRdxOperand(Instruction *I, unsigned Index) {
8080     // Poison-safe 'or' takes the form: select X, true, Y
8081     // To make that work with the normal operand processing, we skip the
8082     // true value operand.
8083     // TODO: Change the code and data structures to handle this without a hack.
8084     if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
8085       return I->getOperand(2);
8086     return I->getOperand(Index);
8087   }
8088 
8089   /// Checks if the ParentStackElem.first should be marked as a reduction
8090   /// operation with an extra argument or as extra argument itself.
8091   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
8092                     Value *ExtraArg) {
8093     if (ExtraArgs.count(ParentStackElem.first)) {
8094       ExtraArgs[ParentStackElem.first] = nullptr;
8095       // We ran into something like:
8096       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
8097       // The whole ParentStackElem.first should be considered as an extra value
8098       // in this case.
8099       // Do not perform analysis of remaining operands of ParentStackElem.first
8100       // instruction, this whole instruction is an extra argument.
8101       ParentStackElem.second = INVALID_OPERAND_INDEX;
8102     } else {
8103       // We ran into something like:
8104       // ParentStackElem.first += ... + ExtraArg + ...
8105       ExtraArgs[ParentStackElem.first] = ExtraArg;
8106     }
8107   }
8108 
8109   /// Creates reduction operation with the current opcode.
8110   static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
8111                          Value *RHS, const Twine &Name, bool UseSelect) {
8112     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
8113     switch (Kind) {
8114     case RecurKind::Or:
8115       if (UseSelect &&
8116           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8117         return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
8118       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8119                                  Name);
8120     case RecurKind::And:
8121       if (UseSelect &&
8122           LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
8123         return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
8124       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8125                                  Name);
8126     case RecurKind::Add:
8127     case RecurKind::Mul:
8128     case RecurKind::Xor:
8129     case RecurKind::FAdd:
8130     case RecurKind::FMul:
8131       return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
8132                                  Name);
8133     case RecurKind::FMax:
8134       return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
8135     case RecurKind::FMin:
8136       return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
8137     case RecurKind::SMax:
8138       if (UseSelect) {
8139         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
8140         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8141       }
8142       return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
8143     case RecurKind::SMin:
8144       if (UseSelect) {
8145         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
8146         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8147       }
8148       return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
8149     case RecurKind::UMax:
8150       if (UseSelect) {
8151         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
8152         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8153       }
8154       return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
8155     case RecurKind::UMin:
8156       if (UseSelect) {
8157         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
8158         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
8159       }
8160       return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
8161     default:
8162       llvm_unreachable("Unknown reduction operation.");
8163     }
8164   }
8165 
8166   /// Creates reduction operation with the current opcode with the IR flags
8167   /// from \p ReductionOps.
8168   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8169                          Value *RHS, const Twine &Name,
8170                          const ReductionOpsListType &ReductionOps) {
8171     bool UseSelect = ReductionOps.size() == 2 ||
8172                      // Logical or/and.
8173                      (ReductionOps.size() == 1 &&
8174                       isa<SelectInst>(ReductionOps.front().front()));
8175     assert((!UseSelect || ReductionOps.size() != 2 ||
8176             isa<SelectInst>(ReductionOps[1][0])) &&
8177            "Expected cmp + select pairs for reduction");
8178     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
8179     if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8180       if (auto *Sel = dyn_cast<SelectInst>(Op)) {
8181         propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
8182         propagateIRFlags(Op, ReductionOps[1]);
8183         return Op;
8184       }
8185     }
8186     propagateIRFlags(Op, ReductionOps[0]);
8187     return Op;
8188   }
8189 
8190   /// Creates reduction operation with the current opcode with the IR flags
8191   /// from \p I.
8192   static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
8193                          Value *RHS, const Twine &Name, Instruction *I) {
8194     auto *SelI = dyn_cast<SelectInst>(I);
8195     Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
8196     if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
8197       if (auto *Sel = dyn_cast<SelectInst>(Op))
8198         propagateIRFlags(Sel->getCondition(), SelI->getCondition());
8199     }
8200     propagateIRFlags(Op, I);
8201     return Op;
8202   }
8203 
8204   static RecurKind getRdxKind(Instruction *I) {
8205     assert(I && "Expected instruction for reduction matching");
8206     TargetTransformInfo::ReductionFlags RdxFlags;
8207     if (match(I, m_Add(m_Value(), m_Value())))
8208       return RecurKind::Add;
8209     if (match(I, m_Mul(m_Value(), m_Value())))
8210       return RecurKind::Mul;
8211     if (match(I, m_And(m_Value(), m_Value())) ||
8212         match(I, m_LogicalAnd(m_Value(), m_Value())))
8213       return RecurKind::And;
8214     if (match(I, m_Or(m_Value(), m_Value())) ||
8215         match(I, m_LogicalOr(m_Value(), m_Value())))
8216       return RecurKind::Or;
8217     if (match(I, m_Xor(m_Value(), m_Value())))
8218       return RecurKind::Xor;
8219     if (match(I, m_FAdd(m_Value(), m_Value())))
8220       return RecurKind::FAdd;
8221     if (match(I, m_FMul(m_Value(), m_Value())))
8222       return RecurKind::FMul;
8223 
8224     if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
8225       return RecurKind::FMax;
8226     if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
8227       return RecurKind::FMin;
8228 
8229     // This matches either cmp+select or intrinsics. SLP is expected to handle
8230     // either form.
8231     // TODO: If we are canonicalizing to intrinsics, we can remove several
8232     //       special-case paths that deal with selects.
8233     if (match(I, m_SMax(m_Value(), m_Value())))
8234       return RecurKind::SMax;
8235     if (match(I, m_SMin(m_Value(), m_Value())))
8236       return RecurKind::SMin;
8237     if (match(I, m_UMax(m_Value(), m_Value())))
8238       return RecurKind::UMax;
8239     if (match(I, m_UMin(m_Value(), m_Value())))
8240       return RecurKind::UMin;
8241 
8242     if (auto *Select = dyn_cast<SelectInst>(I)) {
8243       // Try harder: look for min/max pattern based on instructions producing
8244       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
8245       // During the intermediate stages of SLP, it's very common to have
8246       // pattern like this (since optimizeGatherSequence is run only once
8247       // at the end):
8248       // %1 = extractelement <2 x i32> %a, i32 0
8249       // %2 = extractelement <2 x i32> %a, i32 1
8250       // %cond = icmp sgt i32 %1, %2
8251       // %3 = extractelement <2 x i32> %a, i32 0
8252       // %4 = extractelement <2 x i32> %a, i32 1
8253       // %select = select i1 %cond, i32 %3, i32 %4
8254       CmpInst::Predicate Pred;
8255       Instruction *L1;
8256       Instruction *L2;
8257 
8258       Value *LHS = Select->getTrueValue();
8259       Value *RHS = Select->getFalseValue();
8260       Value *Cond = Select->getCondition();
8261 
8262       // TODO: Support inverse predicates.
8263       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
8264         if (!isa<ExtractElementInst>(RHS) ||
8265             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8266           return RecurKind::None;
8267       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
8268         if (!isa<ExtractElementInst>(LHS) ||
8269             !L1->isIdenticalTo(cast<Instruction>(LHS)))
8270           return RecurKind::None;
8271       } else {
8272         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
8273           return RecurKind::None;
8274         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
8275             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
8276             !L2->isIdenticalTo(cast<Instruction>(RHS)))
8277           return RecurKind::None;
8278       }
8279 
8280       TargetTransformInfo::ReductionFlags RdxFlags;
8281       switch (Pred) {
8282       default:
8283         return RecurKind::None;
8284       case CmpInst::ICMP_SGT:
8285       case CmpInst::ICMP_SGE:
8286         return RecurKind::SMax;
8287       case CmpInst::ICMP_SLT:
8288       case CmpInst::ICMP_SLE:
8289         return RecurKind::SMin;
8290       case CmpInst::ICMP_UGT:
8291       case CmpInst::ICMP_UGE:
8292         return RecurKind::UMax;
8293       case CmpInst::ICMP_ULT:
8294       case CmpInst::ICMP_ULE:
8295         return RecurKind::UMin;
8296       }
8297     }
8298     return RecurKind::None;
8299   }
8300 
8301   /// Get the index of the first operand.
8302   static unsigned getFirstOperandIndex(Instruction *I) {
8303     return isCmpSelMinMax(I) ? 1 : 0;
8304   }
8305 
8306   /// Total number of operands in the reduction operation.
8307   static unsigned getNumberOfOperands(Instruction *I) {
8308     return isCmpSelMinMax(I) ? 3 : 2;
8309   }
8310 
8311   /// Checks if the instruction is in basic block \p BB.
8312   /// For a cmp+sel min/max reduction check that both ops are in \p BB.
8313   static bool hasSameParent(Instruction *I, BasicBlock *BB) {
8314     if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
8315       auto *Sel = cast<SelectInst>(I);
8316       auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
8317       return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
8318     }
8319     return I->getParent() == BB;
8320   }
8321 
8322   /// Expected number of uses for reduction operations/reduced values.
8323   static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
8324     if (IsCmpSelMinMax) {
8325       // SelectInst must be used twice while the condition op must have single
8326       // use only.
8327       if (auto *Sel = dyn_cast<SelectInst>(I))
8328         return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
8329       return I->hasNUses(2);
8330     }
8331 
8332     // Arithmetic reduction operation must be used once only.
8333     return I->hasOneUse();
8334   }
8335 
8336   /// Initializes the list of reduction operations.
8337   void initReductionOps(Instruction *I) {
8338     if (isCmpSelMinMax(I))
8339       ReductionOps.assign(2, ReductionOpsType());
8340     else
8341       ReductionOps.assign(1, ReductionOpsType());
8342   }
8343 
8344   /// Add all reduction operations for the reduction instruction \p I.
8345   void addReductionOps(Instruction *I) {
8346     if (isCmpSelMinMax(I)) {
8347       ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
8348       ReductionOps[1].emplace_back(I);
8349     } else {
8350       ReductionOps[0].emplace_back(I);
8351     }
8352   }
8353 
8354   static Value *getLHS(RecurKind Kind, Instruction *I) {
8355     if (Kind == RecurKind::None)
8356       return nullptr;
8357     return I->getOperand(getFirstOperandIndex(I));
8358   }
8359   static Value *getRHS(RecurKind Kind, Instruction *I) {
8360     if (Kind == RecurKind::None)
8361       return nullptr;
8362     return I->getOperand(getFirstOperandIndex(I) + 1);
8363   }
8364 
8365 public:
8366   HorizontalReduction() = default;
8367 
8368   /// Try to find a reduction tree.
8369   bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
8370     assert((!Phi || is_contained(Phi->operands(), Inst)) &&
8371            "Phi needs to use the binary operator");
8372     assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
8373             isa<IntrinsicInst>(Inst)) &&
8374            "Expected binop, select, or intrinsic for reduction matching");
8375     RdxKind = getRdxKind(Inst);
8376 
8377     // We could have a initial reductions that is not an add.
8378     //  r *= v1 + v2 + v3 + v4
8379     // In such a case start looking for a tree rooted in the first '+'.
8380     if (Phi) {
8381       if (getLHS(RdxKind, Inst) == Phi) {
8382         Phi = nullptr;
8383         Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
8384         if (!Inst)
8385           return false;
8386         RdxKind = getRdxKind(Inst);
8387       } else if (getRHS(RdxKind, Inst) == Phi) {
8388         Phi = nullptr;
8389         Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
8390         if (!Inst)
8391           return false;
8392         RdxKind = getRdxKind(Inst);
8393       }
8394     }
8395 
8396     if (!isVectorizable(RdxKind, Inst))
8397       return false;
8398 
8399     // Analyze "regular" integer/FP types for reductions - no target-specific
8400     // types or pointers.
8401     Type *Ty = Inst->getType();
8402     if (!isValidElementType(Ty) || Ty->isPointerTy())
8403       return false;
8404 
8405     // Though the ultimate reduction may have multiple uses, its condition must
8406     // have only single use.
8407     if (auto *Sel = dyn_cast<SelectInst>(Inst))
8408       if (!Sel->getCondition()->hasOneUse())
8409         return false;
8410 
8411     ReductionRoot = Inst;
8412 
8413     // The opcode for leaf values that we perform a reduction on.
8414     // For example: load(x) + load(y) + load(z) + fptoui(w)
8415     // The leaf opcode for 'w' does not match, so we don't include it as a
8416     // potential candidate for the reduction.
8417     unsigned LeafOpcode = 0;
8418 
8419     // Post-order traverse the reduction tree starting at Inst. We only handle
8420     // true trees containing binary operators or selects.
8421     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
8422     Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
8423     initReductionOps(Inst);
8424     while (!Stack.empty()) {
8425       Instruction *TreeN = Stack.back().first;
8426       unsigned EdgeToVisit = Stack.back().second++;
8427       const RecurKind TreeRdxKind = getRdxKind(TreeN);
8428       bool IsReducedValue = TreeRdxKind != RdxKind;
8429 
8430       // Postorder visit.
8431       if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
8432         if (IsReducedValue)
8433           ReducedVals.push_back(TreeN);
8434         else {
8435           auto ExtraArgsIter = ExtraArgs.find(TreeN);
8436           if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
8437             // Check if TreeN is an extra argument of its parent operation.
8438             if (Stack.size() <= 1) {
8439               // TreeN can't be an extra argument as it is a root reduction
8440               // operation.
8441               return false;
8442             }
8443             // Yes, TreeN is an extra argument, do not add it to a list of
8444             // reduction operations.
8445             // Stack[Stack.size() - 2] always points to the parent operation.
8446             markExtraArg(Stack[Stack.size() - 2], TreeN);
8447             ExtraArgs.erase(TreeN);
8448           } else
8449             addReductionOps(TreeN);
8450         }
8451         // Retract.
8452         Stack.pop_back();
8453         continue;
8454       }
8455 
8456       // Visit operands.
8457       Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
8458       auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
8459       if (!EdgeInst) {
8460         // Edge value is not a reduction instruction or a leaf instruction.
8461         // (It may be a constant, function argument, or something else.)
8462         markExtraArg(Stack.back(), EdgeVal);
8463         continue;
8464       }
8465       RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
8466       // Continue analysis if the next operand is a reduction operation or
8467       // (possibly) a leaf value. If the leaf value opcode is not set,
8468       // the first met operation != reduction operation is considered as the
8469       // leaf opcode.
8470       // Only handle trees in the current basic block.
8471       // Each tree node needs to have minimal number of users except for the
8472       // ultimate reduction.
8473       const bool IsRdxInst = EdgeRdxKind == RdxKind;
8474       if (EdgeInst != Phi && EdgeInst != Inst &&
8475           hasSameParent(EdgeInst, Inst->getParent()) &&
8476           hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
8477           (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
8478         if (IsRdxInst) {
8479           // We need to be able to reassociate the reduction operations.
8480           if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
8481             // I is an extra argument for TreeN (its parent operation).
8482             markExtraArg(Stack.back(), EdgeInst);
8483             continue;
8484           }
8485         } else if (!LeafOpcode) {
8486           LeafOpcode = EdgeInst->getOpcode();
8487         }
8488         Stack.push_back(
8489             std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
8490         continue;
8491       }
8492       // I is an extra argument for TreeN (its parent operation).
8493       markExtraArg(Stack.back(), EdgeInst);
8494     }
8495     return true;
8496   }
8497 
8498   /// Attempt to vectorize the tree found by matchAssociativeReduction.
8499   Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
8500     // If there are a sufficient number of reduction values, reduce
8501     // to a nearby power-of-2. We can safely generate oversized
8502     // vectors and rely on the backend to split them to legal sizes.
8503     unsigned NumReducedVals = ReducedVals.size();
8504     if (NumReducedVals < 4)
8505       return nullptr;
8506 
8507     // Intersect the fast-math-flags from all reduction operations.
8508     FastMathFlags RdxFMF;
8509     RdxFMF.set();
8510     for (ReductionOpsType &RdxOp : ReductionOps) {
8511       for (Value *RdxVal : RdxOp) {
8512         if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
8513           RdxFMF &= FPMO->getFastMathFlags();
8514       }
8515     }
8516 
8517     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
8518     Builder.setFastMathFlags(RdxFMF);
8519 
8520     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
8521     // The same extra argument may be used several times, so log each attempt
8522     // to use it.
8523     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
8524       assert(Pair.first && "DebugLoc must be set.");
8525       ExternallyUsedValues[Pair.second].push_back(Pair.first);
8526     }
8527 
8528     // The compare instruction of a min/max is the insertion point for new
8529     // instructions and may be replaced with a new compare instruction.
8530     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
8531       assert(isa<SelectInst>(RdxRootInst) &&
8532              "Expected min/max reduction to have select root instruction");
8533       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
8534       assert(isa<Instruction>(ScalarCond) &&
8535              "Expected min/max reduction to have compare condition");
8536       return cast<Instruction>(ScalarCond);
8537     };
8538 
8539     // The reduction root is used as the insertion point for new instructions,
8540     // so set it as externally used to prevent it from being deleted.
8541     ExternallyUsedValues[ReductionRoot];
8542     SmallVector<Value *, 16> IgnoreList;
8543     for (ReductionOpsType &RdxOp : ReductionOps)
8544       IgnoreList.append(RdxOp.begin(), RdxOp.end());
8545 
8546     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
8547     if (NumReducedVals > ReduxWidth) {
8548       // In the loop below, we are building a tree based on a window of
8549       // 'ReduxWidth' values.
8550       // If the operands of those values have common traits (compare predicate,
8551       // constant operand, etc), then we want to group those together to
8552       // minimize the cost of the reduction.
8553 
8554       // TODO: This should be extended to count common operands for
8555       //       compares and binops.
8556 
8557       // Step 1: Count the number of times each compare predicate occurs.
8558       SmallDenseMap<unsigned, unsigned> PredCountMap;
8559       for (Value *RdxVal : ReducedVals) {
8560         CmpInst::Predicate Pred;
8561         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
8562           ++PredCountMap[Pred];
8563       }
8564       // Step 2: Sort the values so the most common predicates come first.
8565       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
8566         CmpInst::Predicate PredA, PredB;
8567         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
8568             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
8569           return PredCountMap[PredA] > PredCountMap[PredB];
8570         }
8571         return false;
8572       });
8573     }
8574 
8575     Value *VectorizedTree = nullptr;
8576     unsigned i = 0;
8577     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
8578       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
8579       V.buildTree(VL, IgnoreList);
8580       if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
8581         break;
8582       if (V.isLoadCombineReductionCandidate(RdxKind))
8583         break;
8584       V.reorderTopToBottom();
8585       V.reorderBottomToTop(/*IgnoreReorder=*/true);
8586       V.buildExternalUses(ExternallyUsedValues);
8587 
8588       // For a poison-safe boolean logic reduction, do not replace select
8589       // instructions with logic ops. All reduced values will be frozen (see
8590       // below) to prevent leaking poison.
8591       if (isa<SelectInst>(ReductionRoot) &&
8592           isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
8593           NumReducedVals != ReduxWidth)
8594         break;
8595 
8596       V.computeMinimumValueSizes();
8597 
8598       // Estimate cost.
8599       InstructionCost TreeCost =
8600           V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
8601       InstructionCost ReductionCost =
8602           getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
8603       InstructionCost Cost = TreeCost + ReductionCost;
8604       if (!Cost.isValid()) {
8605         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
8606         return nullptr;
8607       }
8608       if (Cost >= -SLPCostThreshold) {
8609         V.getORE()->emit([&]() {
8610           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
8611                                           cast<Instruction>(VL[0]))
8612                  << "Vectorizing horizontal reduction is possible"
8613                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
8614                  << " and threshold "
8615                  << ore::NV("Threshold", -SLPCostThreshold);
8616         });
8617         break;
8618       }
8619 
8620       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
8621                         << Cost << ". (HorRdx)\n");
8622       V.getORE()->emit([&]() {
8623         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
8624                                   cast<Instruction>(VL[0]))
8625                << "Vectorized horizontal reduction with cost "
8626                << ore::NV("Cost", Cost) << " and with tree size "
8627                << ore::NV("TreeSize", V.getTreeSize());
8628       });
8629 
8630       // Vectorize a tree.
8631       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
8632       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
8633 
8634       // Emit a reduction. If the root is a select (min/max idiom), the insert
8635       // point is the compare condition of that select.
8636       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
8637       if (isCmpSelMinMax(RdxRootInst))
8638         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
8639       else
8640         Builder.SetInsertPoint(RdxRootInst);
8641 
8642       // To prevent poison from leaking across what used to be sequential, safe,
8643       // scalar boolean logic operations, the reduction operand must be frozen.
8644       if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
8645         VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
8646 
8647       Value *ReducedSubTree =
8648           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
8649 
8650       if (!VectorizedTree) {
8651         // Initialize the final value in the reduction.
8652         VectorizedTree = ReducedSubTree;
8653       } else {
8654         // Update the final value in the reduction.
8655         Builder.SetCurrentDebugLocation(Loc);
8656         VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
8657                                   ReducedSubTree, "op.rdx", ReductionOps);
8658       }
8659       i += ReduxWidth;
8660       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
8661     }
8662 
8663     if (VectorizedTree) {
8664       // Finish the reduction.
8665       for (; i < NumReducedVals; ++i) {
8666         auto *I = cast<Instruction>(ReducedVals[i]);
8667         Builder.SetCurrentDebugLocation(I->getDebugLoc());
8668         VectorizedTree =
8669             createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
8670       }
8671       for (auto &Pair : ExternallyUsedValues) {
8672         // Add each externally used value to the final reduction.
8673         for (auto *I : Pair.second) {
8674           Builder.SetCurrentDebugLocation(I->getDebugLoc());
8675           VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
8676                                     Pair.first, "op.extra", I);
8677         }
8678       }
8679 
8680       ReductionRoot->replaceAllUsesWith(VectorizedTree);
8681 
8682       // Mark all scalar reduction ops for deletion, they are replaced by the
8683       // vector reductions.
8684       V.eraseInstructions(IgnoreList);
8685     }
8686     return VectorizedTree;
8687   }
8688 
8689   unsigned numReductionValues() const { return ReducedVals.size(); }
8690 
8691 private:
8692   /// Calculate the cost of a reduction.
8693   InstructionCost getReductionCost(TargetTransformInfo *TTI,
8694                                    Value *FirstReducedVal, unsigned ReduxWidth,
8695                                    FastMathFlags FMF) {
8696     TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
8697     Type *ScalarTy = FirstReducedVal->getType();
8698     FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
8699     InstructionCost VectorCost, ScalarCost;
8700     switch (RdxKind) {
8701     case RecurKind::Add:
8702     case RecurKind::Mul:
8703     case RecurKind::Or:
8704     case RecurKind::And:
8705     case RecurKind::Xor:
8706     case RecurKind::FAdd:
8707     case RecurKind::FMul: {
8708       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
8709       VectorCost =
8710           TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
8711       ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
8712       break;
8713     }
8714     case RecurKind::FMax:
8715     case RecurKind::FMin: {
8716       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
8717       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
8718       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
8719                                                /*unsigned=*/false, CostKind);
8720       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
8721       ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
8722                                            SclCondTy, RdxPred, CostKind) +
8723                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
8724                                            SclCondTy, RdxPred, CostKind);
8725       break;
8726     }
8727     case RecurKind::SMax:
8728     case RecurKind::SMin:
8729     case RecurKind::UMax:
8730     case RecurKind::UMin: {
8731       auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
8732       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
8733       bool IsUnsigned =
8734           RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
8735       VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
8736                                                CostKind);
8737       CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
8738       ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
8739                                            SclCondTy, RdxPred, CostKind) +
8740                    TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
8741                                            SclCondTy, RdxPred, CostKind);
8742       break;
8743     }
8744     default:
8745       llvm_unreachable("Expected arithmetic or min/max reduction operation");
8746     }
8747 
8748     // Scalar cost is repeated for N-1 elements.
8749     ScalarCost *= (ReduxWidth - 1);
8750     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
8751                       << " for reduction that starts with " << *FirstReducedVal
8752                       << " (It is a splitting reduction)\n");
8753     return VectorCost - ScalarCost;
8754   }
8755 
8756   /// Emit a horizontal reduction of the vectorized value.
8757   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
8758                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
8759     assert(VectorizedValue && "Need to have a vectorized tree node");
8760     assert(isPowerOf2_32(ReduxWidth) &&
8761            "We only handle power-of-two reductions for now");
8762 
8763     ++NumVectorInstructions;
8764     return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind,
8765                                        ReductionOps.back());
8766   }
8767 };
8768 
8769 } // end anonymous namespace
8770 
8771 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
8772   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
8773     return cast<FixedVectorType>(IE->getType())->getNumElements();
8774 
8775   unsigned AggregateSize = 1;
8776   auto *IV = cast<InsertValueInst>(InsertInst);
8777   Type *CurrentType = IV->getType();
8778   do {
8779     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
8780       for (auto *Elt : ST->elements())
8781         if (Elt != ST->getElementType(0)) // check homogeneity
8782           return None;
8783       AggregateSize *= ST->getNumElements();
8784       CurrentType = ST->getElementType(0);
8785     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
8786       AggregateSize *= AT->getNumElements();
8787       CurrentType = AT->getElementType();
8788     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
8789       AggregateSize *= VT->getNumElements();
8790       return AggregateSize;
8791     } else if (CurrentType->isSingleValueType()) {
8792       return AggregateSize;
8793     } else {
8794       return None;
8795     }
8796   } while (true);
8797 }
8798 
8799 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
8800                                    TargetTransformInfo *TTI,
8801                                    SmallVectorImpl<Value *> &BuildVectorOpds,
8802                                    SmallVectorImpl<Value *> &InsertElts,
8803                                    unsigned OperandOffset) {
8804   do {
8805     Value *InsertedOperand = LastInsertInst->getOperand(1);
8806     Optional<int> OperandIndex = getInsertIndex(LastInsertInst, OperandOffset);
8807     if (!OperandIndex)
8808       return false;
8809     if (isa<InsertElementInst>(InsertedOperand) ||
8810         isa<InsertValueInst>(InsertedOperand)) {
8811       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
8812                                   BuildVectorOpds, InsertElts, *OperandIndex))
8813         return false;
8814     } else {
8815       BuildVectorOpds[*OperandIndex] = InsertedOperand;
8816       InsertElts[*OperandIndex] = LastInsertInst;
8817     }
8818     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
8819   } while (LastInsertInst != nullptr &&
8820            (isa<InsertValueInst>(LastInsertInst) ||
8821             isa<InsertElementInst>(LastInsertInst)) &&
8822            LastInsertInst->hasOneUse());
8823   return true;
8824 }
8825 
8826 /// Recognize construction of vectors like
8827 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
8828 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
8829 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
8830 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
8831 ///  starting from the last insertelement or insertvalue instruction.
8832 ///
8833 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
8834 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
8835 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
8836 ///
8837 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
8838 ///
8839 /// \return true if it matches.
8840 static bool findBuildAggregate(Instruction *LastInsertInst,
8841                                TargetTransformInfo *TTI,
8842                                SmallVectorImpl<Value *> &BuildVectorOpds,
8843                                SmallVectorImpl<Value *> &InsertElts) {
8844 
8845   assert((isa<InsertElementInst>(LastInsertInst) ||
8846           isa<InsertValueInst>(LastInsertInst)) &&
8847          "Expected insertelement or insertvalue instruction!");
8848 
8849   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
8850          "Expected empty result vectors!");
8851 
8852   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
8853   if (!AggregateSize)
8854     return false;
8855   BuildVectorOpds.resize(*AggregateSize);
8856   InsertElts.resize(*AggregateSize);
8857 
8858   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
8859                              0)) {
8860     llvm::erase_value(BuildVectorOpds, nullptr);
8861     llvm::erase_value(InsertElts, nullptr);
8862     if (BuildVectorOpds.size() >= 2)
8863       return true;
8864   }
8865 
8866   return false;
8867 }
8868 
8869 /// Try and get a reduction value from a phi node.
8870 ///
8871 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
8872 /// if they come from either \p ParentBB or a containing loop latch.
8873 ///
8874 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
8875 /// if not possible.
8876 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
8877                                 BasicBlock *ParentBB, LoopInfo *LI) {
8878   // There are situations where the reduction value is not dominated by the
8879   // reduction phi. Vectorizing such cases has been reported to cause
8880   // miscompiles. See PR25787.
8881   auto DominatedReduxValue = [&](Value *R) {
8882     return isa<Instruction>(R) &&
8883            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
8884   };
8885 
8886   Value *Rdx = nullptr;
8887 
8888   // Return the incoming value if it comes from the same BB as the phi node.
8889   if (P->getIncomingBlock(0) == ParentBB) {
8890     Rdx = P->getIncomingValue(0);
8891   } else if (P->getIncomingBlock(1) == ParentBB) {
8892     Rdx = P->getIncomingValue(1);
8893   }
8894 
8895   if (Rdx && DominatedReduxValue(Rdx))
8896     return Rdx;
8897 
8898   // Otherwise, check whether we have a loop latch to look at.
8899   Loop *BBL = LI->getLoopFor(ParentBB);
8900   if (!BBL)
8901     return nullptr;
8902   BasicBlock *BBLatch = BBL->getLoopLatch();
8903   if (!BBLatch)
8904     return nullptr;
8905 
8906   // There is a loop latch, return the incoming value if it comes from
8907   // that. This reduction pattern occasionally turns up.
8908   if (P->getIncomingBlock(0) == BBLatch) {
8909     Rdx = P->getIncomingValue(0);
8910   } else if (P->getIncomingBlock(1) == BBLatch) {
8911     Rdx = P->getIncomingValue(1);
8912   }
8913 
8914   if (Rdx && DominatedReduxValue(Rdx))
8915     return Rdx;
8916 
8917   return nullptr;
8918 }
8919 
8920 static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
8921   if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
8922     return true;
8923   if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
8924     return true;
8925   if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
8926     return true;
8927   if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
8928     return true;
8929   if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
8930     return true;
8931   if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
8932     return true;
8933   if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
8934     return true;
8935   return false;
8936 }
8937 
8938 /// Attempt to reduce a horizontal reduction.
8939 /// If it is legal to match a horizontal reduction feeding the phi node \a P
8940 /// with reduction operators \a Root (or one of its operands) in a basic block
8941 /// \a BB, then check if it can be done. If horizontal reduction is not found
8942 /// and root instruction is a binary operation, vectorization of the operands is
8943 /// attempted.
8944 /// \returns true if a horizontal reduction was matched and reduced or operands
8945 /// of one of the binary instruction were vectorized.
8946 /// \returns false if a horizontal reduction was not matched (or not possible)
8947 /// or no vectorization of any binary operation feeding \a Root instruction was
8948 /// performed.
8949 static bool tryToVectorizeHorReductionOrInstOperands(
8950     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
8951     TargetTransformInfo *TTI,
8952     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
8953   if (!ShouldVectorizeHor)
8954     return false;
8955 
8956   if (!Root)
8957     return false;
8958 
8959   if (Root->getParent() != BB || isa<PHINode>(Root))
8960     return false;
8961   // Start analysis starting from Root instruction. If horizontal reduction is
8962   // found, try to vectorize it. If it is not a horizontal reduction or
8963   // vectorization is not possible or not effective, and currently analyzed
8964   // instruction is a binary operation, try to vectorize the operands, using
8965   // pre-order DFS traversal order. If the operands were not vectorized, repeat
8966   // the same procedure considering each operand as a possible root of the
8967   // horizontal reduction.
8968   // Interrupt the process if the Root instruction itself was vectorized or all
8969   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
8970   // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
8971   // CmpInsts so we can skip extra attempts in
8972   // tryToVectorizeHorReductionOrInstOperands and save compile time.
8973   std::queue<std::pair<Instruction *, unsigned>> Stack;
8974   Stack.emplace(Root, 0);
8975   SmallPtrSet<Value *, 8> VisitedInstrs;
8976   SmallVector<WeakTrackingVH> PostponedInsts;
8977   bool Res = false;
8978   auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
8979                                      Value *&B1) -> Value * {
8980     bool IsBinop = matchRdxBop(Inst, B0, B1);
8981     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
8982     if (IsBinop || IsSelect) {
8983       HorizontalReduction HorRdx;
8984       if (HorRdx.matchAssociativeReduction(P, Inst))
8985         return HorRdx.tryToReduce(R, TTI);
8986     }
8987     return nullptr;
8988   };
8989   while (!Stack.empty()) {
8990     Instruction *Inst;
8991     unsigned Level;
8992     std::tie(Inst, Level) = Stack.front();
8993     Stack.pop();
8994     // Do not try to analyze instruction that has already been vectorized.
8995     // This may happen when we vectorize instruction operands on a previous
8996     // iteration while stack was populated before that happened.
8997     if (R.isDeleted(Inst))
8998       continue;
8999     Value *B0 = nullptr, *B1 = nullptr;
9000     if (Value *V = TryToReduce(Inst, B0, B1)) {
9001       Res = true;
9002       // Set P to nullptr to avoid re-analysis of phi node in
9003       // matchAssociativeReduction function unless this is the root node.
9004       P = nullptr;
9005       if (auto *I = dyn_cast<Instruction>(V)) {
9006         // Try to find another reduction.
9007         Stack.emplace(I, Level);
9008         continue;
9009       }
9010     } else {
9011       bool IsBinop = B0 && B1;
9012       if (P && IsBinop) {
9013         Inst = dyn_cast<Instruction>(B0);
9014         if (Inst == P)
9015           Inst = dyn_cast<Instruction>(B1);
9016         if (!Inst) {
9017           // Set P to nullptr to avoid re-analysis of phi node in
9018           // matchAssociativeReduction function unless this is the root node.
9019           P = nullptr;
9020           continue;
9021         }
9022       }
9023       // Set P to nullptr to avoid re-analysis of phi node in
9024       // matchAssociativeReduction function unless this is the root node.
9025       P = nullptr;
9026       // Do not try to vectorize CmpInst operands, this is done separately.
9027       // Final attempt for binop args vectorization should happen after the loop
9028       // to try to find reductions.
9029       if (!isa<CmpInst>(Inst))
9030         PostponedInsts.push_back(Inst);
9031     }
9032 
9033     // Try to vectorize operands.
9034     // Continue analysis for the instruction from the same basic block only to
9035     // save compile time.
9036     if (++Level < RecursionMaxDepth)
9037       for (auto *Op : Inst->operand_values())
9038         if (VisitedInstrs.insert(Op).second)
9039           if (auto *I = dyn_cast<Instruction>(Op))
9040             // Do not try to vectorize CmpInst operands,  this is done
9041             // separately.
9042             if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
9043                 I->getParent() == BB)
9044               Stack.emplace(I, Level);
9045   }
9046   // Try to vectorized binops where reductions were not found.
9047   for (Value *V : PostponedInsts)
9048     if (auto *Inst = dyn_cast<Instruction>(V))
9049       if (!R.isDeleted(Inst))
9050         Res |= Vectorize(Inst, R);
9051   return Res;
9052 }
9053 
9054 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
9055                                                  BasicBlock *BB, BoUpSLP &R,
9056                                                  TargetTransformInfo *TTI) {
9057   auto *I = dyn_cast_or_null<Instruction>(V);
9058   if (!I)
9059     return false;
9060 
9061   if (!isa<BinaryOperator>(I))
9062     P = nullptr;
9063   // Try to match and vectorize a horizontal reduction.
9064   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
9065     return tryToVectorize(I, R);
9066   };
9067   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
9068                                                   ExtraVectorization);
9069 }
9070 
9071 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
9072                                                  BasicBlock *BB, BoUpSLP &R) {
9073   const DataLayout &DL = BB->getModule()->getDataLayout();
9074   if (!R.canMapToVector(IVI->getType(), DL))
9075     return false;
9076 
9077   SmallVector<Value *, 16> BuildVectorOpds;
9078   SmallVector<Value *, 16> BuildVectorInsts;
9079   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
9080     return false;
9081 
9082   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
9083   // Aggregate value is unlikely to be processed in vector register, we need to
9084   // extract scalars into scalar registers, so NeedExtraction is set true.
9085   return tryToVectorizeList(BuildVectorOpds, R);
9086 }
9087 
9088 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
9089                                                    BasicBlock *BB, BoUpSLP &R) {
9090   SmallVector<Value *, 16> BuildVectorInsts;
9091   SmallVector<Value *, 16> BuildVectorOpds;
9092   SmallVector<int> Mask;
9093   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
9094       (llvm::all_of(BuildVectorOpds,
9095                     [](Value *V) { return isa<ExtractElementInst>(V); }) &&
9096        isFixedVectorShuffle(BuildVectorOpds, Mask)))
9097     return false;
9098 
9099   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
9100   return tryToVectorizeList(BuildVectorInsts, R);
9101 }
9102 
9103 bool SLPVectorizerPass::vectorizeSimpleInstructions(
9104     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
9105     bool AtTerminator) {
9106   bool OpsChanged = false;
9107   SmallVector<Instruction *, 4> PostponedCmps;
9108   for (auto *I : reverse(Instructions)) {
9109     if (R.isDeleted(I))
9110       continue;
9111     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
9112       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
9113     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
9114       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
9115     else if (isa<CmpInst>(I))
9116       PostponedCmps.push_back(I);
9117   }
9118   if (AtTerminator) {
9119     // Try to find reductions first.
9120     for (Instruction *I : PostponedCmps) {
9121       if (R.isDeleted(I))
9122         continue;
9123       for (Value *Op : I->operands())
9124         OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
9125     }
9126     // Try to vectorize operands as vector bundles.
9127     for (Instruction *I : PostponedCmps) {
9128       if (R.isDeleted(I))
9129         continue;
9130       OpsChanged |= tryToVectorize(I, R);
9131     }
9132     Instructions.clear();
9133   } else {
9134     // Insert in reverse order since the PostponedCmps vector was filled in
9135     // reverse order.
9136     Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
9137   }
9138   return OpsChanged;
9139 }
9140 
9141 template <typename T>
9142 static bool
9143 tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
9144                        function_ref<unsigned(T *)> Limit,
9145                        function_ref<bool(T *, T *)> Comparator,
9146                        function_ref<bool(T *, T *)> AreCompatible,
9147                        function_ref<bool(ArrayRef<T *>, bool)> TryToVectorize,
9148                        bool LimitForRegisterSize) {
9149   bool Changed = false;
9150   // Sort by type, parent, operands.
9151   stable_sort(Incoming, Comparator);
9152 
9153   // Try to vectorize elements base on their type.
9154   SmallVector<T *> Candidates;
9155   for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
9156     // Look for the next elements with the same type, parent and operand
9157     // kinds.
9158     auto *SameTypeIt = IncIt;
9159     while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
9160       ++SameTypeIt;
9161 
9162     // Try to vectorize them.
9163     unsigned NumElts = (SameTypeIt - IncIt);
9164     LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
9165                       << NumElts << ")\n");
9166     // The vectorization is a 3-state attempt:
9167     // 1. Try to vectorize instructions with the same/alternate opcodes with the
9168     // size of maximal register at first.
9169     // 2. Try to vectorize remaining instructions with the same type, if
9170     // possible. This may result in the better vectorization results rather than
9171     // if we try just to vectorize instructions with the same/alternate opcodes.
9172     // 3. Final attempt to try to vectorize all instructions with the
9173     // same/alternate ops only, this may result in some extra final
9174     // vectorization.
9175     if (NumElts > 1 &&
9176         TryToVectorize(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
9177       // Success start over because instructions might have been changed.
9178       Changed = true;
9179     } else if (NumElts < Limit(*IncIt) &&
9180                (Candidates.empty() ||
9181                 Candidates.front()->getType() == (*IncIt)->getType())) {
9182       Candidates.append(IncIt, std::next(IncIt, NumElts));
9183     }
9184     // Final attempt to vectorize instructions with the same types.
9185     if (Candidates.size() > 1 &&
9186         (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
9187       if (TryToVectorize(Candidates, /*LimitForRegisterSize=*/false)) {
9188         // Success start over because instructions might have been changed.
9189         Changed = true;
9190       } else if (LimitForRegisterSize) {
9191         // Try to vectorize using small vectors.
9192         for (auto *It = Candidates.begin(), *End = Candidates.end();
9193              It != End;) {
9194           auto *SameTypeIt = It;
9195           while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
9196             ++SameTypeIt;
9197           unsigned NumElts = (SameTypeIt - It);
9198           if (NumElts > 1 && TryToVectorize(makeArrayRef(It, NumElts),
9199                                             /*LimitForRegisterSize=*/false))
9200             Changed = true;
9201           It = SameTypeIt;
9202         }
9203       }
9204       Candidates.clear();
9205     }
9206 
9207     // Start over at the next instruction of a different type (or the end).
9208     IncIt = SameTypeIt;
9209   }
9210   return Changed;
9211 }
9212 
9213 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
9214   bool Changed = false;
9215   SmallVector<Value *, 4> Incoming;
9216   SmallPtrSet<Value *, 16> VisitedInstrs;
9217   // Maps phi nodes to the non-phi nodes found in the use tree for each phi
9218   // node. Allows better to identify the chains that can be vectorized in the
9219   // better way.
9220   DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
9221   auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
9222     assert(isValidElementType(V1->getType()) &&
9223            isValidElementType(V2->getType()) &&
9224            "Expected vectorizable types only.");
9225     // It is fine to compare type IDs here, since we expect only vectorizable
9226     // types, like ints, floats and pointers, we don't care about other type.
9227     if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
9228       return true;
9229     if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
9230       return false;
9231     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9232     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9233     if (Opcodes1.size() < Opcodes2.size())
9234       return true;
9235     if (Opcodes1.size() > Opcodes2.size())
9236       return false;
9237     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9238       // Undefs are compatible with any other value.
9239       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9240         continue;
9241       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9242         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9243           DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
9244           DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
9245           if (!NodeI1)
9246             return NodeI2 != nullptr;
9247           if (!NodeI2)
9248             return false;
9249           assert((NodeI1 == NodeI2) ==
9250                      (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
9251                  "Different nodes should have different DFS numbers");
9252           if (NodeI1 != NodeI2)
9253             return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
9254           InstructionsState S = getSameOpcode({I1, I2});
9255           if (S.getOpcode())
9256             continue;
9257           return I1->getOpcode() < I2->getOpcode();
9258         }
9259       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9260         continue;
9261       if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
9262         return true;
9263       if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
9264         return false;
9265     }
9266     return false;
9267   };
9268   auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
9269     if (V1 == V2)
9270       return true;
9271     if (V1->getType() != V2->getType())
9272       return false;
9273     ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
9274     ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
9275     if (Opcodes1.size() != Opcodes2.size())
9276       return false;
9277     for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
9278       // Undefs are compatible with any other value.
9279       if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
9280         continue;
9281       if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
9282         if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
9283           if (I1->getParent() != I2->getParent())
9284             return false;
9285           InstructionsState S = getSameOpcode({I1, I2});
9286           if (S.getOpcode())
9287             continue;
9288           return false;
9289         }
9290       if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
9291         continue;
9292       if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
9293         return false;
9294     }
9295     return true;
9296   };
9297   auto Limit = [&R](Value *V) {
9298     unsigned EltSize = R.getVectorElementSize(V);
9299     return std::max(2U, R.getMaxVecRegSize() / EltSize);
9300   };
9301 
9302   bool HaveVectorizedPhiNodes = false;
9303   do {
9304     // Collect the incoming values from the PHIs.
9305     Incoming.clear();
9306     for (Instruction &I : *BB) {
9307       PHINode *P = dyn_cast<PHINode>(&I);
9308       if (!P)
9309         break;
9310 
9311       // No need to analyze deleted, vectorized and non-vectorizable
9312       // instructions.
9313       if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
9314           isValidElementType(P->getType()))
9315         Incoming.push_back(P);
9316     }
9317 
9318     // Find the corresponding non-phi nodes for better matching when trying to
9319     // build the tree.
9320     for (Value *V : Incoming) {
9321       SmallVectorImpl<Value *> &Opcodes =
9322           PHIToOpcodes.try_emplace(V).first->getSecond();
9323       if (!Opcodes.empty())
9324         continue;
9325       SmallVector<Value *, 4> Nodes(1, V);
9326       SmallPtrSet<Value *, 4> Visited;
9327       while (!Nodes.empty()) {
9328         auto *PHI = cast<PHINode>(Nodes.pop_back_val());
9329         if (!Visited.insert(PHI).second)
9330           continue;
9331         for (Value *V : PHI->incoming_values()) {
9332           if (auto *PHI1 = dyn_cast<PHINode>((V))) {
9333             Nodes.push_back(PHI1);
9334             continue;
9335           }
9336           Opcodes.emplace_back(V);
9337         }
9338       }
9339     }
9340 
9341     HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
9342         Incoming, Limit, PHICompare, AreCompatiblePHIs,
9343         [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
9344           return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
9345         },
9346         /*LimitForRegisterSize=*/true);
9347     Changed |= HaveVectorizedPhiNodes;
9348     VisitedInstrs.insert(Incoming.begin(), Incoming.end());
9349   } while (HaveVectorizedPhiNodes);
9350 
9351   VisitedInstrs.clear();
9352 
9353   SmallVector<Instruction *, 8> PostProcessInstructions;
9354   SmallDenseSet<Instruction *, 4> KeyNodes;
9355   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
9356     // Skip instructions with scalable type. The num of elements is unknown at
9357     // compile-time for scalable type.
9358     if (isa<ScalableVectorType>(it->getType()))
9359       continue;
9360 
9361     // Skip instructions marked for the deletion.
9362     if (R.isDeleted(&*it))
9363       continue;
9364     // We may go through BB multiple times so skip the one we have checked.
9365     if (!VisitedInstrs.insert(&*it).second) {
9366       if (it->use_empty() && KeyNodes.contains(&*it) &&
9367           vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
9368                                       it->isTerminator())) {
9369         // We would like to start over since some instructions are deleted
9370         // and the iterator may become invalid value.
9371         Changed = true;
9372         it = BB->begin();
9373         e = BB->end();
9374       }
9375       continue;
9376     }
9377 
9378     if (isa<DbgInfoIntrinsic>(it))
9379       continue;
9380 
9381     // Try to vectorize reductions that use PHINodes.
9382     if (PHINode *P = dyn_cast<PHINode>(it)) {
9383       // Check that the PHI is a reduction PHI.
9384       if (P->getNumIncomingValues() == 2) {
9385         // Try to match and vectorize a horizontal reduction.
9386         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
9387                                      TTI)) {
9388           Changed = true;
9389           it = BB->begin();
9390           e = BB->end();
9391           continue;
9392         }
9393       }
9394       // Try to vectorize the incoming values of the PHI, to catch reductions
9395       // that feed into PHIs.
9396       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
9397         // Skip if the incoming block is the current BB for now. Also, bypass
9398         // unreachable IR for efficiency and to avoid crashing.
9399         // TODO: Collect the skipped incoming values and try to vectorize them
9400         // after processing BB.
9401         if (BB == P->getIncomingBlock(I) ||
9402             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
9403           continue;
9404 
9405         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
9406                                             P->getIncomingBlock(I), R, TTI);
9407       }
9408       continue;
9409     }
9410 
9411     // Ran into an instruction without users, like terminator, or function call
9412     // with ignored return value, store. Ignore unused instructions (basing on
9413     // instruction type, except for CallInst and InvokeInst).
9414     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
9415                             isa<InvokeInst>(it))) {
9416       KeyNodes.insert(&*it);
9417       bool OpsChanged = false;
9418       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
9419         for (auto *V : it->operand_values()) {
9420           // Try to match and vectorize a horizontal reduction.
9421           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
9422         }
9423       }
9424       // Start vectorization of post-process list of instructions from the
9425       // top-tree instructions to try to vectorize as many instructions as
9426       // possible.
9427       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
9428                                                 it->isTerminator());
9429       if (OpsChanged) {
9430         // We would like to start over since some instructions are deleted
9431         // and the iterator may become invalid value.
9432         Changed = true;
9433         it = BB->begin();
9434         e = BB->end();
9435         continue;
9436       }
9437     }
9438 
9439     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
9440         isa<InsertValueInst>(it))
9441       PostProcessInstructions.push_back(&*it);
9442   }
9443 
9444   return Changed;
9445 }
9446 
9447 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
9448   auto Changed = false;
9449   for (auto &Entry : GEPs) {
9450     // If the getelementptr list has fewer than two elements, there's nothing
9451     // to do.
9452     if (Entry.second.size() < 2)
9453       continue;
9454 
9455     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
9456                       << Entry.second.size() << ".\n");
9457 
9458     // Process the GEP list in chunks suitable for the target's supported
9459     // vector size. If a vector register can't hold 1 element, we are done. We
9460     // are trying to vectorize the index computations, so the maximum number of
9461     // elements is based on the size of the index expression, rather than the
9462     // size of the GEP itself (the target's pointer size).
9463     unsigned MaxVecRegSize = R.getMaxVecRegSize();
9464     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
9465     if (MaxVecRegSize < EltSize)
9466       continue;
9467 
9468     unsigned MaxElts = MaxVecRegSize / EltSize;
9469     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
9470       auto Len = std::min<unsigned>(BE - BI, MaxElts);
9471       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
9472 
9473       // Initialize a set a candidate getelementptrs. Note that we use a
9474       // SetVector here to preserve program order. If the index computations
9475       // are vectorizable and begin with loads, we want to minimize the chance
9476       // of having to reorder them later.
9477       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
9478 
9479       // Some of the candidates may have already been vectorized after we
9480       // initially collected them. If so, they are marked as deleted, so remove
9481       // them from the set of candidates.
9482       Candidates.remove_if(
9483           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
9484 
9485       // Remove from the set of candidates all pairs of getelementptrs with
9486       // constant differences. Such getelementptrs are likely not good
9487       // candidates for vectorization in a bottom-up phase since one can be
9488       // computed from the other. We also ensure all candidate getelementptr
9489       // indices are unique.
9490       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
9491         auto *GEPI = GEPList[I];
9492         if (!Candidates.count(GEPI))
9493           continue;
9494         auto *SCEVI = SE->getSCEV(GEPList[I]);
9495         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
9496           auto *GEPJ = GEPList[J];
9497           auto *SCEVJ = SE->getSCEV(GEPList[J]);
9498           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
9499             Candidates.remove(GEPI);
9500             Candidates.remove(GEPJ);
9501           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
9502             Candidates.remove(GEPJ);
9503           }
9504         }
9505       }
9506 
9507       // We break out of the above computation as soon as we know there are
9508       // fewer than two candidates remaining.
9509       if (Candidates.size() < 2)
9510         continue;
9511 
9512       // Add the single, non-constant index of each candidate to the bundle. We
9513       // ensured the indices met these constraints when we originally collected
9514       // the getelementptrs.
9515       SmallVector<Value *, 16> Bundle(Candidates.size());
9516       auto BundleIndex = 0u;
9517       for (auto *V : Candidates) {
9518         auto *GEP = cast<GetElementPtrInst>(V);
9519         auto *GEPIdx = GEP->idx_begin()->get();
9520         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
9521         Bundle[BundleIndex++] = GEPIdx;
9522       }
9523 
9524       // Try and vectorize the indices. We are currently only interested in
9525       // gather-like cases of the form:
9526       //
9527       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
9528       //
9529       // where the loads of "a", the loads of "b", and the subtractions can be
9530       // performed in parallel. It's likely that detecting this pattern in a
9531       // bottom-up phase will be simpler and less costly than building a
9532       // full-blown top-down phase beginning at the consecutive loads.
9533       Changed |= tryToVectorizeList(Bundle, R);
9534     }
9535   }
9536   return Changed;
9537 }
9538 
9539 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
9540   bool Changed = false;
9541   // Sort by type, base pointers and values operand. Value operands must be
9542   // compatible (have the same opcode, same parent), otherwise it is
9543   // definitely not profitable to try to vectorize them.
9544   auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
9545     if (V->getPointerOperandType()->getTypeID() <
9546         V2->getPointerOperandType()->getTypeID())
9547       return true;
9548     if (V->getPointerOperandType()->getTypeID() >
9549         V2->getPointerOperandType()->getTypeID())
9550       return false;
9551     // UndefValues are compatible with all other values.
9552     if (isa<UndefValue>(V->getValueOperand()) ||
9553         isa<UndefValue>(V2->getValueOperand()))
9554       return false;
9555     if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
9556       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
9557         DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
9558             DT->getNode(I1->getParent());
9559         DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
9560             DT->getNode(I2->getParent());
9561         assert(NodeI1 && "Should only process reachable instructions");
9562         assert(NodeI1 && "Should only process reachable instructions");
9563         assert((NodeI1 == NodeI2) ==
9564                    (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
9565                "Different nodes should have different DFS numbers");
9566         if (NodeI1 != NodeI2)
9567           return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
9568         InstructionsState S = getSameOpcode({I1, I2});
9569         if (S.getOpcode())
9570           return false;
9571         return I1->getOpcode() < I2->getOpcode();
9572       }
9573     if (isa<Constant>(V->getValueOperand()) &&
9574         isa<Constant>(V2->getValueOperand()))
9575       return false;
9576     return V->getValueOperand()->getValueID() <
9577            V2->getValueOperand()->getValueID();
9578   };
9579 
9580   auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
9581     if (V1 == V2)
9582       return true;
9583     if (V1->getPointerOperandType() != V2->getPointerOperandType())
9584       return false;
9585     // Undefs are compatible with any other value.
9586     if (isa<UndefValue>(V1->getValueOperand()) ||
9587         isa<UndefValue>(V2->getValueOperand()))
9588       return true;
9589     if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
9590       if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
9591         if (I1->getParent() != I2->getParent())
9592           return false;
9593         InstructionsState S = getSameOpcode({I1, I2});
9594         return S.getOpcode() > 0;
9595       }
9596     if (isa<Constant>(V1->getValueOperand()) &&
9597         isa<Constant>(V2->getValueOperand()))
9598       return true;
9599     return V1->getValueOperand()->getValueID() ==
9600            V2->getValueOperand()->getValueID();
9601   };
9602   auto Limit = [&R, this](StoreInst *SI) {
9603     unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
9604     return R.getMinVF(EltSize);
9605   };
9606 
9607   // Attempt to sort and vectorize each of the store-groups.
9608   for (auto &Pair : Stores) {
9609     if (Pair.second.size() < 2)
9610       continue;
9611 
9612     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
9613                       << Pair.second.size() << ".\n");
9614 
9615     if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
9616       continue;
9617 
9618     Changed |= tryToVectorizeSequence<StoreInst>(
9619         Pair.second, Limit, StoreSorter, AreCompatibleStores,
9620         [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
9621           return vectorizeStores(Candidates, R);
9622         },
9623         /*LimitForRegisterSize=*/false);
9624   }
9625   return Changed;
9626 }
9627 
9628 char SLPVectorizer::ID = 0;
9629 
9630 static const char lv_name[] = "SLP Vectorizer";
9631 
9632 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
9633 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
9634 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
9635 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
9636 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
9637 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
9638 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
9639 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
9640 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
9641 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
9642 
9643 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
9644