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