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