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