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