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