1 //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10 // stores that can be put together into vector-stores. Next, it attempts to
11 // construct vectorizable tree using the use-def chains. If a profitable tree
12 // was found, the SLP vectorizer performs vectorization on the tree.
13 //
14 // The pass is inspired by the work described in the paper:
15 //  "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/DenseSet.h"
22 #include "llvm/ADT/Optional.h"
23 #include "llvm/ADT/PostOrderIterator.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SetVector.h"
26 #include "llvm/ADT/SmallBitVector.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallSet.h"
29 #include "llvm/ADT/SmallString.h"
30 #include "llvm/ADT/Statistic.h"
31 #include "llvm/ADT/iterator.h"
32 #include "llvm/ADT/iterator_range.h"
33 #include "llvm/Analysis/AliasAnalysis.h"
34 #include "llvm/Analysis/AssumptionCache.h"
35 #include "llvm/Analysis/CodeMetrics.h"
36 #include "llvm/Analysis/DemandedBits.h"
37 #include "llvm/Analysis/GlobalsModRef.h"
38 #include "llvm/Analysis/IVDescriptors.h"
39 #include "llvm/Analysis/LoopAccessAnalysis.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/MemoryLocation.h"
42 #include "llvm/Analysis/OptimizationRemarkEmitter.h"
43 #include "llvm/Analysis/ScalarEvolution.h"
44 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
45 #include "llvm/Analysis/TargetLibraryInfo.h"
46 #include "llvm/Analysis/TargetTransformInfo.h"
47 #include "llvm/Analysis/ValueTracking.h"
48 #include "llvm/Analysis/VectorUtils.h"
49 #include "llvm/IR/Attributes.h"
50 #include "llvm/IR/BasicBlock.h"
51 #include "llvm/IR/Constant.h"
52 #include "llvm/IR/Constants.h"
53 #include "llvm/IR/DataLayout.h"
54 #include "llvm/IR/DebugLoc.h"
55 #include "llvm/IR/DerivedTypes.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/Function.h"
58 #include "llvm/IR/IRBuilder.h"
59 #include "llvm/IR/InstrTypes.h"
60 #include "llvm/IR/Instruction.h"
61 #include "llvm/IR/Instructions.h"
62 #include "llvm/IR/IntrinsicInst.h"
63 #include "llvm/IR/Intrinsics.h"
64 #include "llvm/IR/Module.h"
65 #include "llvm/IR/NoFolder.h"
66 #include "llvm/IR/Operator.h"
67 #include "llvm/IR/PatternMatch.h"
68 #include "llvm/IR/Type.h"
69 #include "llvm/IR/Use.h"
70 #include "llvm/IR/User.h"
71 #include "llvm/IR/Value.h"
72 #include "llvm/IR/ValueHandle.h"
73 #include "llvm/IR/Verifier.h"
74 #include "llvm/InitializePasses.h"
75 #include "llvm/Pass.h"
76 #include "llvm/Support/Casting.h"
77 #include "llvm/Support/CommandLine.h"
78 #include "llvm/Support/Compiler.h"
79 #include "llvm/Support/DOTGraphTraits.h"
80 #include "llvm/Support/Debug.h"
81 #include "llvm/Support/ErrorHandling.h"
82 #include "llvm/Support/GraphWriter.h"
83 #include "llvm/Support/InstructionCost.h"
84 #include "llvm/Support/KnownBits.h"
85 #include "llvm/Support/MathExtras.h"
86 #include "llvm/Support/raw_ostream.h"
87 #include "llvm/Transforms/Utils/InjectTLIMappings.h"
88 #include "llvm/Transforms/Utils/LoopUtils.h"
89 #include "llvm/Transforms/Vectorize.h"
90 #include <algorithm>
91 #include <cassert>
92 #include <cstdint>
93 #include <iterator>
94 #include <memory>
95 #include <set>
96 #include <string>
97 #include <tuple>
98 #include <utility>
99 #include <vector>
100 
101 using namespace llvm;
102 using namespace llvm::PatternMatch;
103 using namespace slpvectorizer;
104 
105 #define SV_NAME "slp-vectorizer"
106 #define DEBUG_TYPE "SLP"
107 
108 STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
109 
110 cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
111                                   cl::desc("Run the SLP vectorization passes"));
112 
113 static cl::opt<int>
114     SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
115                      cl::desc("Only vectorize if you gain more than this "
116                               "number "));
117 
118 static cl::opt<bool>
119 ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
120                    cl::desc("Attempt to vectorize horizontal reductions"));
121 
122 static cl::opt<bool> ShouldStartVectorizeHorAtStore(
123     "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
124     cl::desc(
125         "Attempt to vectorize horizontal reductions feeding into a store"));
126 
127 static cl::opt<int>
128 MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
129     cl::desc("Attempt to vectorize for this register size in bits"));
130 
131 static cl::opt<unsigned>
132 MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
133     cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
134 
135 static cl::opt<int>
136 MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
137     cl::desc("Maximum depth of the lookup for consecutive stores."));
138 
139 /// Limits the size of scheduling regions in a block.
140 /// It avoid long compile times for _very_ large blocks where vector
141 /// instructions are spread over a wide range.
142 /// This limit is way higher than needed by real-world functions.
143 static cl::opt<int>
144 ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
145     cl::desc("Limit the size of the SLP scheduling region per block"));
146 
147 static cl::opt<int> MinVectorRegSizeOption(
148     "slp-min-reg-size", cl::init(128), cl::Hidden,
149     cl::desc("Attempt to vectorize for this register size in bits"));
150 
151 static cl::opt<unsigned> RecursionMaxDepth(
152     "slp-recursion-max-depth", cl::init(12), cl::Hidden,
153     cl::desc("Limit the recursion depth when building a vectorizable tree"));
154 
155 static cl::opt<unsigned> MinTreeSize(
156     "slp-min-tree-size", cl::init(3), cl::Hidden,
157     cl::desc("Only vectorize small trees if they are fully vectorizable"));
158 
159 // The maximum depth that the look-ahead score heuristic will explore.
160 // The higher this value, the higher the compilation time overhead.
161 static cl::opt<int> LookAheadMaxDepth(
162     "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
163     cl::desc("The maximum look-ahead depth for operand reordering scores"));
164 
165 // The Look-ahead heuristic goes through the users of the bundle to calculate
166 // the users cost in getExternalUsesCost(). To avoid compilation time increase
167 // we limit the number of users visited to this value.
168 static cl::opt<unsigned> LookAheadUsersBudget(
169     "slp-look-ahead-users-budget", cl::init(2), cl::Hidden,
170     cl::desc("The maximum number of users to visit while visiting the "
171              "predecessors. This prevents compilation time increase."));
172 
173 static cl::opt<bool>
174     ViewSLPTree("view-slp-tree", cl::Hidden,
175                 cl::desc("Display the SLP trees with Graphviz"));
176 
177 // Limit the number of alias checks. The limit is chosen so that
178 // it has no negative effect on the llvm benchmarks.
179 static const unsigned AliasedCheckLimit = 10;
180 
181 // Another limit for the alias checks: The maximum distance between load/store
182 // instructions where alias checks are done.
183 // This limit is useful for very large basic blocks.
184 static const unsigned MaxMemDepDistance = 160;
185 
186 /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
187 /// regions to be handled.
188 static const int MinScheduleRegionSize = 16;
189 
190 /// Predicate for the element types that the SLP vectorizer supports.
191 ///
192 /// The most important thing to filter here are types which are invalid in LLVM
193 /// vectors. We also filter target specific types which have absolutely no
194 /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
195 /// avoids spending time checking the cost model and realizing that they will
196 /// be inevitably scalarized.
197 static bool isValidElementType(Type *Ty) {
198   return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
199          !Ty->isPPC_FP128Ty();
200 }
201 
202 /// \returns true if all of the instructions in \p VL are in the same block or
203 /// false otherwise.
204 static bool allSameBlock(ArrayRef<Value *> VL) {
205   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
206   if (!I0)
207     return false;
208   BasicBlock *BB = I0->getParent();
209   for (int I = 1, E = VL.size(); I < E; I++) {
210     auto *II = dyn_cast<Instruction>(VL[I]);
211     if (!II)
212       return false;
213 
214     if (BB != II->getParent())
215       return false;
216   }
217   return true;
218 }
219 
220 /// \returns True if all of the values in \p VL are constants (but not
221 /// globals/constant expressions).
222 static bool allConstant(ArrayRef<Value *> VL) {
223   // Constant expressions and globals can't be vectorized like normal integer/FP
224   // constants.
225   for (Value *i : VL)
226     if (!isa<Constant>(i) || isa<ConstantExpr>(i) || isa<GlobalValue>(i))
227       return false;
228   return true;
229 }
230 
231 /// \returns True if all of the values in \p VL are identical.
232 static bool isSplat(ArrayRef<Value *> VL) {
233   for (unsigned i = 1, e = VL.size(); i < e; ++i)
234     if (VL[i] != VL[0])
235       return false;
236   return true;
237 }
238 
239 /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
240 static bool isCommutative(Instruction *I) {
241   if (auto *Cmp = dyn_cast<CmpInst>(I))
242     return Cmp->isCommutative();
243   if (auto *BO = dyn_cast<BinaryOperator>(I))
244     return BO->isCommutative();
245   // TODO: This should check for generic Instruction::isCommutative(), but
246   //       we need to confirm that the caller code correctly handles Intrinsics
247   //       for example (does not have 2 operands).
248   return false;
249 }
250 
251 /// Checks if the vector of instructions can be represented as a shuffle, like:
252 /// %x0 = extractelement <4 x i8> %x, i32 0
253 /// %x3 = extractelement <4 x i8> %x, i32 3
254 /// %y1 = extractelement <4 x i8> %y, i32 1
255 /// %y2 = extractelement <4 x i8> %y, i32 2
256 /// %x0x0 = mul i8 %x0, %x0
257 /// %x3x3 = mul i8 %x3, %x3
258 /// %y1y1 = mul i8 %y1, %y1
259 /// %y2y2 = mul i8 %y2, %y2
260 /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
261 /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
262 /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
263 /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
264 /// ret <4 x i8> %ins4
265 /// can be transformed into:
266 /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
267 ///                                                         i32 6>
268 /// %2 = mul <4 x i8> %1, %1
269 /// ret <4 x i8> %2
270 /// We convert this initially to something like:
271 /// %x0 = extractelement <4 x i8> %x, i32 0
272 /// %x3 = extractelement <4 x i8> %x, i32 3
273 /// %y1 = extractelement <4 x i8> %y, i32 1
274 /// %y2 = extractelement <4 x i8> %y, i32 2
275 /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
276 /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
277 /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
278 /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
279 /// %5 = mul <4 x i8> %4, %4
280 /// %6 = extractelement <4 x i8> %5, i32 0
281 /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
282 /// %7 = extractelement <4 x i8> %5, i32 1
283 /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
284 /// %8 = extractelement <4 x i8> %5, i32 2
285 /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
286 /// %9 = extractelement <4 x i8> %5, i32 3
287 /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
288 /// ret <4 x i8> %ins4
289 /// InstCombiner transforms this into a shuffle and vector mul
290 /// TODO: Can we split off and reuse the shuffle mask detection from
291 /// TargetTransformInfo::getInstructionThroughput?
292 static Optional<TargetTransformInfo::ShuffleKind>
293 isShuffle(ArrayRef<Value *> VL) {
294   auto *EI0 = cast<ExtractElementInst>(VL[0]);
295   unsigned Size =
296       cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
297   Value *Vec1 = nullptr;
298   Value *Vec2 = nullptr;
299   enum ShuffleMode { Unknown, Select, Permute };
300   ShuffleMode CommonShuffleMode = Unknown;
301   for (unsigned I = 0, E = VL.size(); I < E; ++I) {
302     auto *EI = cast<ExtractElementInst>(VL[I]);
303     auto *Vec = EI->getVectorOperand();
304     // All vector operands must have the same number of vector elements.
305     if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
306       return None;
307     auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
308     if (!Idx)
309       return None;
310     // Undefined behavior if Idx is negative or >= Size.
311     if (Idx->getValue().uge(Size))
312       continue;
313     unsigned IntIdx = Idx->getValue().getZExtValue();
314     // We can extractelement from undef or poison vector.
315     if (isa<UndefValue>(Vec))
316       continue;
317     // For correct shuffling we have to have at most 2 different vector operands
318     // in all extractelement instructions.
319     if (!Vec1 || Vec1 == Vec)
320       Vec1 = Vec;
321     else if (!Vec2 || Vec2 == Vec)
322       Vec2 = Vec;
323     else
324       return None;
325     if (CommonShuffleMode == Permute)
326       continue;
327     // If the extract index is not the same as the operation number, it is a
328     // permutation.
329     if (IntIdx != I) {
330       CommonShuffleMode = Permute;
331       continue;
332     }
333     CommonShuffleMode = Select;
334   }
335   // If we're not crossing lanes in different vectors, consider it as blending.
336   if (CommonShuffleMode == Select && Vec2)
337     return TargetTransformInfo::SK_Select;
338   // If Vec2 was never used, we have a permutation of a single vector, otherwise
339   // we have permutation of 2 vectors.
340   return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
341               : TargetTransformInfo::SK_PermuteSingleSrc;
342 }
343 
344 namespace {
345 
346 /// Main data required for vectorization of instructions.
347 struct InstructionsState {
348   /// The very first instruction in the list with the main opcode.
349   Value *OpValue = nullptr;
350 
351   /// The main/alternate instruction.
352   Instruction *MainOp = nullptr;
353   Instruction *AltOp = nullptr;
354 
355   /// The main/alternate opcodes for the list of instructions.
356   unsigned getOpcode() const {
357     return MainOp ? MainOp->getOpcode() : 0;
358   }
359 
360   unsigned getAltOpcode() const {
361     return AltOp ? AltOp->getOpcode() : 0;
362   }
363 
364   /// Some of the instructions in the list have alternate opcodes.
365   bool isAltShuffle() const { return getOpcode() != getAltOpcode(); }
366 
367   bool isOpcodeOrAlt(Instruction *I) const {
368     unsigned CheckedOpcode = I->getOpcode();
369     return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
370   }
371 
372   InstructionsState() = delete;
373   InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
374       : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
375 };
376 
377 } // end anonymous namespace
378 
379 /// Chooses the correct key for scheduling data. If \p Op has the same (or
380 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
381 /// OpValue.
382 static Value *isOneOf(const InstructionsState &S, Value *Op) {
383   auto *I = dyn_cast<Instruction>(Op);
384   if (I && S.isOpcodeOrAlt(I))
385     return Op;
386   return S.OpValue;
387 }
388 
389 /// \returns true if \p Opcode is allowed as part of of the main/alternate
390 /// instruction for SLP vectorization.
391 ///
392 /// Example of unsupported opcode is SDIV that can potentially cause UB if the
393 /// "shuffled out" lane would result in division by zero.
394 static bool isValidForAlternation(unsigned Opcode) {
395   if (Instruction::isIntDivRem(Opcode))
396     return false;
397 
398   return true;
399 }
400 
401 /// \returns analysis of the Instructions in \p VL described in
402 /// InstructionsState, the Opcode that we suppose the whole list
403 /// could be vectorized even if its structure is diverse.
404 static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
405                                        unsigned BaseIndex = 0) {
406   // Make sure these are all Instructions.
407   if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
408     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
409 
410   bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
411   bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
412   unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
413   unsigned AltOpcode = Opcode;
414   unsigned AltIndex = BaseIndex;
415 
416   // Check for one alternate opcode from another BinaryOperator.
417   // TODO - generalize to support all operators (types, calls etc.).
418   for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
419     unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
420     if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
421       if (InstOpcode == Opcode || InstOpcode == AltOpcode)
422         continue;
423       if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
424           isValidForAlternation(Opcode)) {
425         AltOpcode = InstOpcode;
426         AltIndex = Cnt;
427         continue;
428       }
429     } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
430       Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
431       Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
432       if (Ty0 == Ty1) {
433         if (InstOpcode == Opcode || InstOpcode == AltOpcode)
434           continue;
435         if (Opcode == AltOpcode) {
436           assert(isValidForAlternation(Opcode) &&
437                  isValidForAlternation(InstOpcode) &&
438                  "Cast isn't safe for alternation, logic needs to be updated!");
439           AltOpcode = InstOpcode;
440           AltIndex = Cnt;
441           continue;
442         }
443       }
444     } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
445       continue;
446     return InstructionsState(VL[BaseIndex], nullptr, nullptr);
447   }
448 
449   return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
450                            cast<Instruction>(VL[AltIndex]));
451 }
452 
453 /// \returns true if all of the values in \p VL have the same type or false
454 /// otherwise.
455 static bool allSameType(ArrayRef<Value *> VL) {
456   Type *Ty = VL[0]->getType();
457   for (int i = 1, e = VL.size(); i < e; i++)
458     if (VL[i]->getType() != Ty)
459       return false;
460 
461   return true;
462 }
463 
464 /// \returns True if Extract{Value,Element} instruction extracts element Idx.
465 static Optional<unsigned> getExtractIndex(Instruction *E) {
466   unsigned Opcode = E->getOpcode();
467   assert((Opcode == Instruction::ExtractElement ||
468           Opcode == Instruction::ExtractValue) &&
469          "Expected extractelement or extractvalue instruction.");
470   if (Opcode == Instruction::ExtractElement) {
471     auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
472     if (!CI)
473       return None;
474     return CI->getZExtValue();
475   }
476   ExtractValueInst *EI = cast<ExtractValueInst>(E);
477   if (EI->getNumIndices() != 1)
478     return None;
479   return *EI->idx_begin();
480 }
481 
482 /// \returns True if in-tree use also needs extract. This refers to
483 /// possible scalar operand in vectorized instruction.
484 static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
485                                     TargetLibraryInfo *TLI) {
486   unsigned Opcode = UserInst->getOpcode();
487   switch (Opcode) {
488   case Instruction::Load: {
489     LoadInst *LI = cast<LoadInst>(UserInst);
490     return (LI->getPointerOperand() == Scalar);
491   }
492   case Instruction::Store: {
493     StoreInst *SI = cast<StoreInst>(UserInst);
494     return (SI->getPointerOperand() == Scalar);
495   }
496   case Instruction::Call: {
497     CallInst *CI = cast<CallInst>(UserInst);
498     Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
499     for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
500       if (hasVectorInstrinsicScalarOpd(ID, i))
501         return (CI->getArgOperand(i) == Scalar);
502     }
503     LLVM_FALLTHROUGH;
504   }
505   default:
506     return false;
507   }
508 }
509 
510 /// \returns the AA location that is being access by the instruction.
511 static MemoryLocation getLocation(Instruction *I, AAResults *AA) {
512   if (StoreInst *SI = dyn_cast<StoreInst>(I))
513     return MemoryLocation::get(SI);
514   if (LoadInst *LI = dyn_cast<LoadInst>(I))
515     return MemoryLocation::get(LI);
516   return MemoryLocation();
517 }
518 
519 /// \returns True if the instruction is not a volatile or atomic load/store.
520 static bool isSimple(Instruction *I) {
521   if (LoadInst *LI = dyn_cast<LoadInst>(I))
522     return LI->isSimple();
523   if (StoreInst *SI = dyn_cast<StoreInst>(I))
524     return SI->isSimple();
525   if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
526     return !MI->isVolatile();
527   return true;
528 }
529 
530 namespace llvm {
531 
532 static void inversePermutation(ArrayRef<unsigned> Indices,
533                                SmallVectorImpl<int> &Mask) {
534   Mask.clear();
535   const unsigned E = Indices.size();
536   Mask.resize(E, E + 1);
537   for (unsigned I = 0; I < E; ++I)
538     Mask[Indices[I]] = I;
539 }
540 
541 namespace slpvectorizer {
542 
543 /// Bottom Up SLP Vectorizer.
544 class BoUpSLP {
545   struct TreeEntry;
546   struct ScheduleData;
547 
548 public:
549   using ValueList = SmallVector<Value *, 8>;
550   using InstrList = SmallVector<Instruction *, 16>;
551   using ValueSet = SmallPtrSet<Value *, 16>;
552   using StoreList = SmallVector<StoreInst *, 8>;
553   using ExtraValueToDebugLocsMap =
554       MapVector<Value *, SmallVector<Instruction *, 2>>;
555   using OrdersType = SmallVector<unsigned, 4>;
556 
557   BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
558           TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
559           DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
560           const DataLayout *DL, OptimizationRemarkEmitter *ORE)
561       : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
562         DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
563     CodeMetrics::collectEphemeralValues(F, AC, EphValues);
564     // Use the vector register size specified by the target unless overridden
565     // by a command-line option.
566     // TODO: It would be better to limit the vectorization factor based on
567     //       data type rather than just register size. For example, x86 AVX has
568     //       256-bit registers, but it does not support integer operations
569     //       at that width (that requires AVX2).
570     if (MaxVectorRegSizeOption.getNumOccurrences())
571       MaxVecRegSize = MaxVectorRegSizeOption;
572     else
573       MaxVecRegSize = TTI->getRegisterBitWidth(true);
574 
575     if (MinVectorRegSizeOption.getNumOccurrences())
576       MinVecRegSize = MinVectorRegSizeOption;
577     else
578       MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
579   }
580 
581   /// Vectorize the tree that starts with the elements in \p VL.
582   /// Returns the vectorized root.
583   Value *vectorizeTree();
584 
585   /// Vectorize the tree but with the list of externally used values \p
586   /// ExternallyUsedValues. Values in this MapVector can be replaced but the
587   /// generated extractvalue instructions.
588   Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
589 
590   /// \returns the cost incurred by unwanted spills and fills, caused by
591   /// holding live values over call sites.
592   InstructionCost getSpillCost() const;
593 
594   /// \returns the vectorization cost of the subtree that starts at \p VL.
595   /// A negative number means that this is profitable.
596   InstructionCost getTreeCost();
597 
598   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
599   /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
600   void buildTree(ArrayRef<Value *> Roots,
601                  ArrayRef<Value *> UserIgnoreLst = None);
602 
603   /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
604   /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking
605   /// into account (and updating it, if required) list of externally used
606   /// values stored in \p ExternallyUsedValues.
607   void buildTree(ArrayRef<Value *> Roots,
608                  ExtraValueToDebugLocsMap &ExternallyUsedValues,
609                  ArrayRef<Value *> UserIgnoreLst = None);
610 
611   /// Clear the internal data structures that are created by 'buildTree'.
612   void deleteTree() {
613     VectorizableTree.clear();
614     ScalarToTreeEntry.clear();
615     MustGather.clear();
616     ExternalUses.clear();
617     NumOpsWantToKeepOrder.clear();
618     NumOpsWantToKeepOriginalOrder = 0;
619     for (auto &Iter : BlocksSchedules) {
620       BlockScheduling *BS = Iter.second.get();
621       BS->clear();
622     }
623     MinBWs.clear();
624   }
625 
626   unsigned getTreeSize() const { return VectorizableTree.size(); }
627 
628   /// Perform LICM and CSE on the newly generated gather sequences.
629   void optimizeGatherSequence();
630 
631   /// \returns The best order of instructions for vectorization.
632   Optional<ArrayRef<unsigned>> bestOrder() const {
633     assert(llvm::all_of(
634                NumOpsWantToKeepOrder,
635                [this](const decltype(NumOpsWantToKeepOrder)::value_type &D) {
636                  return D.getFirst().size() ==
637                         VectorizableTree[0]->Scalars.size();
638                }) &&
639            "All orders must have the same size as number of instructions in "
640            "tree node.");
641     auto I = std::max_element(
642         NumOpsWantToKeepOrder.begin(), NumOpsWantToKeepOrder.end(),
643         [](const decltype(NumOpsWantToKeepOrder)::value_type &D1,
644            const decltype(NumOpsWantToKeepOrder)::value_type &D2) {
645           return D1.second < D2.second;
646         });
647     if (I == NumOpsWantToKeepOrder.end() ||
648         I->getSecond() <= NumOpsWantToKeepOriginalOrder)
649       return None;
650 
651     return makeArrayRef(I->getFirst());
652   }
653 
654   /// Builds the correct order for root instructions.
655   /// If some leaves have the same instructions to be vectorized, we may
656   /// incorrectly evaluate the best order for the root node (it is built for the
657   /// vector of instructions without repeated instructions and, thus, has less
658   /// elements than the root node). This function builds the correct order for
659   /// the root node.
660   /// For example, if the root node is \<a+b, a+c, a+d, f+e\>, then the leaves
661   /// are \<a, a, a, f\> and \<b, c, d, e\>. When we try to vectorize the first
662   /// leaf, it will be shrink to \<a, b\>. If instructions in this leaf should
663   /// be reordered, the best order will be \<1, 0\>. We need to extend this
664   /// order for the root node. For the root node this order should look like
665   /// \<3, 0, 1, 2\>. This function extends the order for the reused
666   /// instructions.
667   void findRootOrder(OrdersType &Order) {
668     // If the leaf has the same number of instructions to vectorize as the root
669     // - order must be set already.
670     unsigned RootSize = VectorizableTree[0]->Scalars.size();
671     if (Order.size() == RootSize)
672       return;
673     SmallVector<unsigned, 4> RealOrder(Order.size());
674     std::swap(Order, RealOrder);
675     SmallVector<int, 4> Mask;
676     inversePermutation(RealOrder, Mask);
677     Order.assign(Mask.begin(), Mask.end());
678     // The leaf has less number of instructions - need to find the true order of
679     // the root.
680     // Scan the nodes starting from the leaf back to the root.
681     const TreeEntry *PNode = VectorizableTree.back().get();
682     SmallVector<const TreeEntry *, 4> Nodes(1, PNode);
683     SmallPtrSet<const TreeEntry *, 4> Visited;
684     while (!Nodes.empty() && Order.size() != RootSize) {
685       const TreeEntry *PNode = Nodes.pop_back_val();
686       if (!Visited.insert(PNode).second)
687         continue;
688       const TreeEntry &Node = *PNode;
689       for (const EdgeInfo &EI : Node.UserTreeIndices)
690         if (EI.UserTE)
691           Nodes.push_back(EI.UserTE);
692       if (Node.ReuseShuffleIndices.empty())
693         continue;
694       // Build the order for the parent node.
695       OrdersType NewOrder(Node.ReuseShuffleIndices.size(), RootSize);
696       SmallVector<unsigned, 4> OrderCounter(Order.size(), 0);
697       // The algorithm of the order extension is:
698       // 1. Calculate the number of the same instructions for the order.
699       // 2. Calculate the index of the new order: total number of instructions
700       // with order less than the order of the current instruction + reuse
701       // number of the current instruction.
702       // 3. The new order is just the index of the instruction in the original
703       // vector of the instructions.
704       for (unsigned I : Node.ReuseShuffleIndices)
705         ++OrderCounter[Order[I]];
706       SmallVector<unsigned, 4> CurrentCounter(Order.size(), 0);
707       for (unsigned I = 0, E = Node.ReuseShuffleIndices.size(); I < E; ++I) {
708         unsigned ReusedIdx = Node.ReuseShuffleIndices[I];
709         unsigned OrderIdx = Order[ReusedIdx];
710         unsigned NewIdx = 0;
711         for (unsigned J = 0; J < OrderIdx; ++J)
712           NewIdx += OrderCounter[J];
713         NewIdx += CurrentCounter[OrderIdx];
714         ++CurrentCounter[OrderIdx];
715         assert(NewOrder[NewIdx] == RootSize &&
716                "The order index should not be written already.");
717         NewOrder[NewIdx] = I;
718       }
719       std::swap(Order, NewOrder);
720     }
721     assert(Order.size() == RootSize &&
722            "Root node is expected or the size of the order must be the same as "
723            "the number of elements in the root node.");
724     assert(llvm::all_of(Order,
725                         [RootSize](unsigned Val) { return Val != RootSize; }) &&
726            "All indices must be initialized");
727   }
728 
729   /// \return The vector element size in bits to use when vectorizing the
730   /// expression tree ending at \p V. If V is a store, the size is the width of
731   /// the stored value. Otherwise, the size is the width of the largest loaded
732   /// value reaching V. This method is used by the vectorizer to calculate
733   /// vectorization factors.
734   unsigned getVectorElementSize(Value *V);
735 
736   /// Compute the minimum type sizes required to represent the entries in a
737   /// vectorizable tree.
738   void computeMinimumValueSizes();
739 
740   // \returns maximum vector register size as set by TTI or overridden by cl::opt.
741   unsigned getMaxVecRegSize() const {
742     return MaxVecRegSize;
743   }
744 
745   // \returns minimum vector register size as set by cl::opt.
746   unsigned getMinVecRegSize() const {
747     return MinVecRegSize;
748   }
749 
750   unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
751     unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
752       MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
753     return MaxVF ? MaxVF : UINT_MAX;
754   }
755 
756   /// Check if homogeneous aggregate is isomorphic to some VectorType.
757   /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
758   /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
759   /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
760   ///
761   /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
762   unsigned canMapToVector(Type *T, const DataLayout &DL) const;
763 
764   /// \returns True if the VectorizableTree is both tiny and not fully
765   /// vectorizable. We do not vectorize such trees.
766   bool isTreeTinyAndNotFullyVectorizable() const;
767 
768   /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
769   /// can be load combined in the backend. Load combining may not be allowed in
770   /// the IR optimizer, so we do not want to alter the pattern. For example,
771   /// partially transforming a scalar bswap() pattern into vector code is
772   /// effectively impossible for the backend to undo.
773   /// TODO: If load combining is allowed in the IR optimizer, this analysis
774   ///       may not be necessary.
775   bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
776 
777   /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
778   /// can be load combined in the backend. Load combining may not be allowed in
779   /// the IR optimizer, so we do not want to alter the pattern. For example,
780   /// partially transforming a scalar bswap() pattern into vector code is
781   /// effectively impossible for the backend to undo.
782   /// TODO: If load combining is allowed in the IR optimizer, this analysis
783   ///       may not be necessary.
784   bool isLoadCombineCandidate() const;
785 
786   OptimizationRemarkEmitter *getORE() { return ORE; }
787 
788   /// This structure holds any data we need about the edges being traversed
789   /// during buildTree_rec(). We keep track of:
790   /// (i) the user TreeEntry index, and
791   /// (ii) the index of the edge.
792   struct EdgeInfo {
793     EdgeInfo() = default;
794     EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
795         : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
796     /// The user TreeEntry.
797     TreeEntry *UserTE = nullptr;
798     /// The operand index of the use.
799     unsigned EdgeIdx = UINT_MAX;
800 #ifndef NDEBUG
801     friend inline raw_ostream &operator<<(raw_ostream &OS,
802                                           const BoUpSLP::EdgeInfo &EI) {
803       EI.dump(OS);
804       return OS;
805     }
806     /// Debug print.
807     void dump(raw_ostream &OS) const {
808       OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
809          << " EdgeIdx:" << EdgeIdx << "}";
810     }
811     LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
812 #endif
813   };
814 
815   /// A helper data structure to hold the operands of a vector of instructions.
816   /// This supports a fixed vector length for all operand vectors.
817   class VLOperands {
818     /// For each operand we need (i) the value, and (ii) the opcode that it
819     /// would be attached to if the expression was in a left-linearized form.
820     /// This is required to avoid illegal operand reordering.
821     /// For example:
822     /// \verbatim
823     ///                         0 Op1
824     ///                         |/
825     /// Op1 Op2   Linearized    + Op2
826     ///   \ /     ---------->   |/
827     ///    -                    -
828     ///
829     /// Op1 - Op2            (0 + Op1) - Op2
830     /// \endverbatim
831     ///
832     /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
833     ///
834     /// Another way to think of this is to track all the operations across the
835     /// path from the operand all the way to the root of the tree and to
836     /// calculate the operation that corresponds to this path. For example, the
837     /// path from Op2 to the root crosses the RHS of the '-', therefore the
838     /// corresponding operation is a '-' (which matches the one in the
839     /// linearized tree, as shown above).
840     ///
841     /// For lack of a better term, we refer to this operation as Accumulated
842     /// Path Operation (APO).
843     struct OperandData {
844       OperandData() = default;
845       OperandData(Value *V, bool APO, bool IsUsed)
846           : V(V), APO(APO), IsUsed(IsUsed) {}
847       /// The operand value.
848       Value *V = nullptr;
849       /// TreeEntries only allow a single opcode, or an alternate sequence of
850       /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
851       /// APO. It is set to 'true' if 'V' is attached to an inverse operation
852       /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
853       /// (e.g., Add/Mul)
854       bool APO = false;
855       /// Helper data for the reordering function.
856       bool IsUsed = false;
857     };
858 
859     /// During operand reordering, we are trying to select the operand at lane
860     /// that matches best with the operand at the neighboring lane. Our
861     /// selection is based on the type of value we are looking for. For example,
862     /// if the neighboring lane has a load, we need to look for a load that is
863     /// accessing a consecutive address. These strategies are summarized in the
864     /// 'ReorderingMode' enumerator.
865     enum class ReorderingMode {
866       Load,     ///< Matching loads to consecutive memory addresses
867       Opcode,   ///< Matching instructions based on opcode (same or alternate)
868       Constant, ///< Matching constants
869       Splat,    ///< Matching the same instruction multiple times (broadcast)
870       Failed,   ///< We failed to create a vectorizable group
871     };
872 
873     using OperandDataVec = SmallVector<OperandData, 2>;
874 
875     /// A vector of operand vectors.
876     SmallVector<OperandDataVec, 4> OpsVec;
877 
878     const DataLayout &DL;
879     ScalarEvolution &SE;
880     const BoUpSLP &R;
881 
882     /// \returns the operand data at \p OpIdx and \p Lane.
883     OperandData &getData(unsigned OpIdx, unsigned Lane) {
884       return OpsVec[OpIdx][Lane];
885     }
886 
887     /// \returns the operand data at \p OpIdx and \p Lane. Const version.
888     const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
889       return OpsVec[OpIdx][Lane];
890     }
891 
892     /// Clears the used flag for all entries.
893     void clearUsed() {
894       for (unsigned OpIdx = 0, NumOperands = getNumOperands();
895            OpIdx != NumOperands; ++OpIdx)
896         for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
897              ++Lane)
898           OpsVec[OpIdx][Lane].IsUsed = false;
899     }
900 
901     /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
902     void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
903       std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
904     }
905 
906     // The hard-coded scores listed here are not very important. When computing
907     // the scores of matching one sub-tree with another, we are basically
908     // counting the number of values that are matching. So even if all scores
909     // are set to 1, we would still get a decent matching result.
910     // However, sometimes we have to break ties. For example we may have to
911     // choose between matching loads vs matching opcodes. This is what these
912     // scores are helping us with: they provide the order of preference.
913 
914     /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
915     static const int ScoreConsecutiveLoads = 3;
916     /// ExtractElementInst from same vector and consecutive indexes.
917     static const int ScoreConsecutiveExtracts = 3;
918     /// Constants.
919     static const int ScoreConstants = 2;
920     /// Instructions with the same opcode.
921     static const int ScoreSameOpcode = 2;
922     /// Instructions with alt opcodes (e.g, add + sub).
923     static const int ScoreAltOpcodes = 1;
924     /// Identical instructions (a.k.a. splat or broadcast).
925     static const int ScoreSplat = 1;
926     /// Matching with an undef is preferable to failing.
927     static const int ScoreUndef = 1;
928     /// Score for failing to find a decent match.
929     static const int ScoreFail = 0;
930     /// User exteranl to the vectorized code.
931     static const int ExternalUseCost = 1;
932     /// The user is internal but in a different lane.
933     static const int UserInDiffLaneCost = ExternalUseCost;
934 
935     /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
936     static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
937                                ScalarEvolution &SE) {
938       auto *LI1 = dyn_cast<LoadInst>(V1);
939       auto *LI2 = dyn_cast<LoadInst>(V2);
940       if (LI1 && LI2)
941         return isConsecutiveAccess(LI1, LI2, DL, SE)
942                    ? VLOperands::ScoreConsecutiveLoads
943                    : VLOperands::ScoreFail;
944 
945       auto *C1 = dyn_cast<Constant>(V1);
946       auto *C2 = dyn_cast<Constant>(V2);
947       if (C1 && C2)
948         return VLOperands::ScoreConstants;
949 
950       // Extracts from consecutive indexes of the same vector better score as
951       // the extracts could be optimized away.
952       Value *EV;
953       ConstantInt *Ex1Idx, *Ex2Idx;
954       if (match(V1, m_ExtractElt(m_Value(EV), m_ConstantInt(Ex1Idx))) &&
955           match(V2, m_ExtractElt(m_Deferred(EV), m_ConstantInt(Ex2Idx))) &&
956           Ex1Idx->getZExtValue() + 1 == Ex2Idx->getZExtValue())
957         return VLOperands::ScoreConsecutiveExtracts;
958 
959       auto *I1 = dyn_cast<Instruction>(V1);
960       auto *I2 = dyn_cast<Instruction>(V2);
961       if (I1 && I2) {
962         if (I1 == I2)
963           return VLOperands::ScoreSplat;
964         InstructionsState S = getSameOpcode({I1, I2});
965         // Note: Only consider instructions with <= 2 operands to avoid
966         // complexity explosion.
967         if (S.getOpcode() && S.MainOp->getNumOperands() <= 2)
968           return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
969                                   : VLOperands::ScoreSameOpcode;
970       }
971 
972       if (isa<UndefValue>(V2))
973         return VLOperands::ScoreUndef;
974 
975       return VLOperands::ScoreFail;
976     }
977 
978     /// Holds the values and their lane that are taking part in the look-ahead
979     /// score calculation. This is used in the external uses cost calculation.
980     SmallDenseMap<Value *, int> InLookAheadValues;
981 
982     /// \Returns the additinal cost due to uses of \p LHS and \p RHS that are
983     /// either external to the vectorized code, or require shuffling.
984     int getExternalUsesCost(const std::pair<Value *, int> &LHS,
985                             const std::pair<Value *, int> &RHS) {
986       int Cost = 0;
987       std::array<std::pair<Value *, int>, 2> Values = {{LHS, RHS}};
988       for (int Idx = 0, IdxE = Values.size(); Idx != IdxE; ++Idx) {
989         Value *V = Values[Idx].first;
990         // 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   LLVM_DEBUG(verifyFunction(*F));
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(RecurKind RdxKind) const {
3900   if (RdxKind != RecurKind::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           // We need to get the vectorized value but without shuffle.
4264           if (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
4265             V = SV->getOperand(0);
4266           } else {
4267             // Reshuffle to get only unique values.
4268             SmallVector<int, 4> UniqueIdxs;
4269             SmallSet<int, 4> UsedIdxs;
4270             for (int Idx : E->ReuseShuffleIndices)
4271               if (UsedIdxs.insert(Idx).second)
4272                 UniqueIdxs.emplace_back(Idx);
4273             V = Builder.CreateShuffleVector(V, UniqueIdxs);
4274           }
4275         }
4276         return V;
4277       }
4278     }
4279   }
4280 
4281   // Check that every instruction appears once in this bundle.
4282   SmallVector<int, 4> ReuseShuffleIndicies;
4283   SmallVector<Value *, 4> UniqueValues;
4284   if (VL.size() > 2) {
4285     DenseMap<Value *, unsigned> UniquePositions;
4286     for (Value *V : VL) {
4287       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4288       ReuseShuffleIndicies.emplace_back(Res.first->second);
4289       if (Res.second || isa<Constant>(V))
4290         UniqueValues.emplace_back(V);
4291     }
4292     // Do not shuffle single element or if number of unique values is not power
4293     // of 2.
4294     if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 ||
4295         !llvm::isPowerOf2_32(UniqueValues.size()))
4296       ReuseShuffleIndicies.clear();
4297     else
4298       VL = UniqueValues;
4299   }
4300 
4301   Value *Vec = gather(VL);
4302   if (!ReuseShuffleIndicies.empty()) {
4303     Vec = Builder.CreateShuffleVector(Vec, ReuseShuffleIndicies, "shuffle");
4304     if (auto *I = dyn_cast<Instruction>(Vec)) {
4305       GatherSeq.insert(I);
4306       CSEBlocks.insert(I->getParent());
4307     }
4308   }
4309   return Vec;
4310 }
4311 
4312 namespace {
4313 /// Merges shuffle masks and emits final shuffle instruction, if required.
4314 class ShuffleInstructionBuilder {
4315   IRBuilderBase &Builder;
4316   bool IsFinalized = false;
4317   SmallVector<int, 4> Mask;
4318 
4319 public:
4320   ShuffleInstructionBuilder(IRBuilderBase &Builder) : Builder(Builder) {}
4321 
4322   /// Adds a mask, inverting it before applying.
4323   void addInversedMask(ArrayRef<unsigned> SubMask) {
4324     if (SubMask.empty())
4325       return;
4326     SmallVector<int, 4> NewMask;
4327     inversePermutation(SubMask, NewMask);
4328     addMask(NewMask);
4329   }
4330 
4331   /// Functions adds masks, merging them into  single one.
4332   void addMask(ArrayRef<unsigned> SubMask) {
4333     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
4334     addMask(NewMask);
4335   }
4336 
4337   void addMask(ArrayRef<int> SubMask) {
4338     if (SubMask.empty())
4339       return;
4340     if (Mask.empty()) {
4341       Mask.append(SubMask.begin(), SubMask.end());
4342       return;
4343     }
4344     SmallVector<int, 4> NewMask(SubMask.size(), SubMask.size());
4345     int TermValue = std::min(Mask.size(), SubMask.size());
4346     for (int I = 0, E = SubMask.size(); I < E; ++I) {
4347       if (SubMask[I] >= TermValue || Mask[SubMask[I]] >= TermValue) {
4348         NewMask[I] = E;
4349         continue;
4350       }
4351       NewMask[I] = Mask[SubMask[I]];
4352     }
4353     Mask.swap(NewMask);
4354   }
4355 
4356   Value *finalize(Value *V) {
4357     IsFinalized = true;
4358     if (Mask.empty())
4359       return V;
4360     return Builder.CreateShuffleVector(V, Mask, "shuffle");
4361   }
4362 
4363   ~ShuffleInstructionBuilder() {
4364     assert((IsFinalized || Mask.empty()) &&
4365            "Must be finalized construction of the shuffles.");
4366   }
4367 };
4368 } // namespace
4369 
4370 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
4371   IRBuilder<>::InsertPointGuard Guard(Builder);
4372 
4373   if (E->VectorizedValue) {
4374     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
4375     return E->VectorizedValue;
4376   }
4377 
4378   ShuffleInstructionBuilder ShuffleBuilder(Builder);
4379   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4380   if (E->State == TreeEntry::NeedToGather) {
4381     setInsertPointAfterBundle(E);
4382     Value *Vec = gather(E->Scalars);
4383     if (NeedToShuffleReuses) {
4384       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4385       Vec = ShuffleBuilder.finalize(Vec);
4386       if (auto *I = dyn_cast<Instruction>(Vec)) {
4387         GatherSeq.insert(I);
4388         CSEBlocks.insert(I->getParent());
4389       }
4390     }
4391     E->VectorizedValue = Vec;
4392     return Vec;
4393   }
4394 
4395   assert((E->State == TreeEntry::Vectorize ||
4396           E->State == TreeEntry::ScatterVectorize) &&
4397          "Unhandled state");
4398   unsigned ShuffleOrOp =
4399       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
4400   Instruction *VL0 = E->getMainOp();
4401   Type *ScalarTy = VL0->getType();
4402   if (auto *Store = dyn_cast<StoreInst>(VL0))
4403     ScalarTy = Store->getValueOperand()->getType();
4404   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
4405   switch (ShuffleOrOp) {
4406     case Instruction::PHI: {
4407       auto *PH = cast<PHINode>(VL0);
4408       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
4409       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
4410       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
4411       Value *V = NewPhi;
4412       if (NeedToShuffleReuses)
4413         V = Builder.CreateShuffleVector(V, E->ReuseShuffleIndices, "shuffle");
4414 
4415       E->VectorizedValue = V;
4416 
4417       // PHINodes may have multiple entries from the same block. We want to
4418       // visit every block once.
4419       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
4420 
4421       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
4422         ValueList Operands;
4423         BasicBlock *IBB = PH->getIncomingBlock(i);
4424 
4425         if (!VisitedBBs.insert(IBB).second) {
4426           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
4427           continue;
4428         }
4429 
4430         Builder.SetInsertPoint(IBB->getTerminator());
4431         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
4432         Value *Vec = vectorizeTree(E->getOperand(i));
4433         NewPhi->addIncoming(Vec, IBB);
4434       }
4435 
4436       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
4437              "Invalid number of incoming values");
4438       return V;
4439     }
4440 
4441     case Instruction::ExtractElement: {
4442       Value *V = E->getSingleOperand(0);
4443       Builder.SetInsertPoint(VL0);
4444       ShuffleBuilder.addInversedMask(E->ReorderIndices);
4445       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4446       V = ShuffleBuilder.finalize(V);
4447       E->VectorizedValue = V;
4448       return V;
4449     }
4450     case Instruction::ExtractValue: {
4451       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
4452       Builder.SetInsertPoint(LI);
4453       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
4454       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
4455       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
4456       Value *NewV = propagateMetadata(V, E->Scalars);
4457       ShuffleBuilder.addInversedMask(E->ReorderIndices);
4458       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4459       NewV = ShuffleBuilder.finalize(NewV);
4460       E->VectorizedValue = NewV;
4461       return NewV;
4462     }
4463     case Instruction::ZExt:
4464     case Instruction::SExt:
4465     case Instruction::FPToUI:
4466     case Instruction::FPToSI:
4467     case Instruction::FPExt:
4468     case Instruction::PtrToInt:
4469     case Instruction::IntToPtr:
4470     case Instruction::SIToFP:
4471     case Instruction::UIToFP:
4472     case Instruction::Trunc:
4473     case Instruction::FPTrunc:
4474     case Instruction::BitCast: {
4475       setInsertPointAfterBundle(E);
4476 
4477       Value *InVec = vectorizeTree(E->getOperand(0));
4478 
4479       if (E->VectorizedValue) {
4480         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4481         return E->VectorizedValue;
4482       }
4483 
4484       auto *CI = cast<CastInst>(VL0);
4485       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
4486       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4487       V = ShuffleBuilder.finalize(V);
4488 
4489       E->VectorizedValue = V;
4490       ++NumVectorInstructions;
4491       return V;
4492     }
4493     case Instruction::FCmp:
4494     case Instruction::ICmp: {
4495       setInsertPointAfterBundle(E);
4496 
4497       Value *L = vectorizeTree(E->getOperand(0));
4498       Value *R = vectorizeTree(E->getOperand(1));
4499 
4500       if (E->VectorizedValue) {
4501         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4502         return E->VectorizedValue;
4503       }
4504 
4505       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4506       Value *V = Builder.CreateCmp(P0, L, R);
4507       propagateIRFlags(V, E->Scalars, VL0);
4508       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4509       V = ShuffleBuilder.finalize(V);
4510 
4511       E->VectorizedValue = V;
4512       ++NumVectorInstructions;
4513       return V;
4514     }
4515     case Instruction::Select: {
4516       setInsertPointAfterBundle(E);
4517 
4518       Value *Cond = vectorizeTree(E->getOperand(0));
4519       Value *True = vectorizeTree(E->getOperand(1));
4520       Value *False = vectorizeTree(E->getOperand(2));
4521 
4522       if (E->VectorizedValue) {
4523         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4524         return E->VectorizedValue;
4525       }
4526 
4527       Value *V = Builder.CreateSelect(Cond, True, False);
4528       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4529       V = ShuffleBuilder.finalize(V);
4530 
4531       E->VectorizedValue = V;
4532       ++NumVectorInstructions;
4533       return V;
4534     }
4535     case Instruction::FNeg: {
4536       setInsertPointAfterBundle(E);
4537 
4538       Value *Op = vectorizeTree(E->getOperand(0));
4539 
4540       if (E->VectorizedValue) {
4541         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4542         return E->VectorizedValue;
4543       }
4544 
4545       Value *V = Builder.CreateUnOp(
4546           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
4547       propagateIRFlags(V, E->Scalars, VL0);
4548       if (auto *I = dyn_cast<Instruction>(V))
4549         V = propagateMetadata(I, E->Scalars);
4550 
4551       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4552       V = ShuffleBuilder.finalize(V);
4553 
4554       E->VectorizedValue = V;
4555       ++NumVectorInstructions;
4556 
4557       return V;
4558     }
4559     case Instruction::Add:
4560     case Instruction::FAdd:
4561     case Instruction::Sub:
4562     case Instruction::FSub:
4563     case Instruction::Mul:
4564     case Instruction::FMul:
4565     case Instruction::UDiv:
4566     case Instruction::SDiv:
4567     case Instruction::FDiv:
4568     case Instruction::URem:
4569     case Instruction::SRem:
4570     case Instruction::FRem:
4571     case Instruction::Shl:
4572     case Instruction::LShr:
4573     case Instruction::AShr:
4574     case Instruction::And:
4575     case Instruction::Or:
4576     case Instruction::Xor: {
4577       setInsertPointAfterBundle(E);
4578 
4579       Value *LHS = vectorizeTree(E->getOperand(0));
4580       Value *RHS = vectorizeTree(E->getOperand(1));
4581 
4582       if (E->VectorizedValue) {
4583         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4584         return E->VectorizedValue;
4585       }
4586 
4587       Value *V = Builder.CreateBinOp(
4588           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
4589           RHS);
4590       propagateIRFlags(V, E->Scalars, VL0);
4591       if (auto *I = dyn_cast<Instruction>(V))
4592         V = propagateMetadata(I, E->Scalars);
4593 
4594       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4595       V = ShuffleBuilder.finalize(V);
4596 
4597       E->VectorizedValue = V;
4598       ++NumVectorInstructions;
4599 
4600       return V;
4601     }
4602     case Instruction::Load: {
4603       // Loads are inserted at the head of the tree because we don't want to
4604       // sink them all the way down past store instructions.
4605       bool IsReorder = E->updateStateIfReorder();
4606       if (IsReorder)
4607         VL0 = E->getMainOp();
4608       setInsertPointAfterBundle(E);
4609 
4610       LoadInst *LI = cast<LoadInst>(VL0);
4611       Instruction *NewLI;
4612       unsigned AS = LI->getPointerAddressSpace();
4613       Value *PO = LI->getPointerOperand();
4614       if (E->State == TreeEntry::Vectorize) {
4615 
4616         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
4617 
4618         // The pointer operand uses an in-tree scalar so we add the new BitCast
4619         // to ExternalUses list to make sure that an extract will be generated
4620         // in the future.
4621         if (getTreeEntry(PO))
4622           ExternalUses.emplace_back(PO, cast<User>(VecPtr), 0);
4623 
4624         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
4625       } else {
4626         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
4627         Value *VecPtr = vectorizeTree(E->getOperand(0));
4628         // Use the minimum alignment of the gathered loads.
4629         Align CommonAlignment = LI->getAlign();
4630         for (Value *V : E->Scalars)
4631           CommonAlignment =
4632               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4633         NewLI = Builder.CreateMaskedGather(VecPtr, CommonAlignment);
4634       }
4635       Value *V = propagateMetadata(NewLI, E->Scalars);
4636 
4637       ShuffleBuilder.addInversedMask(E->ReorderIndices);
4638       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4639       V = ShuffleBuilder.finalize(V);
4640       E->VectorizedValue = V;
4641       ++NumVectorInstructions;
4642       return V;
4643     }
4644     case Instruction::Store: {
4645       bool IsReorder = !E->ReorderIndices.empty();
4646       auto *SI = cast<StoreInst>(
4647           IsReorder ? E->Scalars[E->ReorderIndices.front()] : VL0);
4648       unsigned AS = SI->getPointerAddressSpace();
4649 
4650       setInsertPointAfterBundle(E);
4651 
4652       Value *VecValue = vectorizeTree(E->getOperand(0));
4653       ShuffleBuilder.addMask(E->ReorderIndices);
4654       VecValue = ShuffleBuilder.finalize(VecValue);
4655 
4656       Value *ScalarPtr = SI->getPointerOperand();
4657       Value *VecPtr = Builder.CreateBitCast(
4658           ScalarPtr, VecValue->getType()->getPointerTo(AS));
4659       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
4660                                                  SI->getAlign());
4661 
4662       // The pointer operand uses an in-tree scalar, so add the new BitCast to
4663       // ExternalUses to make sure that an extract will be generated in the
4664       // future.
4665       if (getTreeEntry(ScalarPtr))
4666         ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
4667 
4668       Value *V = propagateMetadata(ST, E->Scalars);
4669 
4670       E->VectorizedValue = V;
4671       ++NumVectorInstructions;
4672       return V;
4673     }
4674     case Instruction::GetElementPtr: {
4675       setInsertPointAfterBundle(E);
4676 
4677       Value *Op0 = vectorizeTree(E->getOperand(0));
4678 
4679       std::vector<Value *> OpVecs;
4680       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
4681            ++j) {
4682         ValueList &VL = E->getOperand(j);
4683         // Need to cast all elements to the same type before vectorization to
4684         // avoid crash.
4685         Type *VL0Ty = VL0->getOperand(j)->getType();
4686         Type *Ty = llvm::all_of(
4687                        VL, [VL0Ty](Value *V) { return VL0Ty == V->getType(); })
4688                        ? VL0Ty
4689                        : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4690                                               ->getPointerOperandType()
4691                                               ->getScalarType());
4692         for (Value *&V : VL) {
4693           auto *CI = cast<ConstantInt>(V);
4694           V = ConstantExpr::getIntegerCast(CI, Ty,
4695                                            CI->getValue().isSignBitSet());
4696         }
4697         Value *OpVec = vectorizeTree(VL);
4698         OpVecs.push_back(OpVec);
4699       }
4700 
4701       Value *V = Builder.CreateGEP(
4702           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
4703       if (Instruction *I = dyn_cast<Instruction>(V))
4704         V = propagateMetadata(I, E->Scalars);
4705 
4706       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4707       V = ShuffleBuilder.finalize(V);
4708 
4709       E->VectorizedValue = V;
4710       ++NumVectorInstructions;
4711 
4712       return V;
4713     }
4714     case Instruction::Call: {
4715       CallInst *CI = cast<CallInst>(VL0);
4716       setInsertPointAfterBundle(E);
4717 
4718       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
4719       if (Function *FI = CI->getCalledFunction())
4720         IID = FI->getIntrinsicID();
4721 
4722       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4723 
4724       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
4725       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
4726                           VecCallCosts.first <= VecCallCosts.second;
4727 
4728       Value *ScalarArg = nullptr;
4729       std::vector<Value *> OpVecs;
4730       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
4731         ValueList OpVL;
4732         // Some intrinsics have scalar arguments. This argument should not be
4733         // vectorized.
4734         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
4735           CallInst *CEI = cast<CallInst>(VL0);
4736           ScalarArg = CEI->getArgOperand(j);
4737           OpVecs.push_back(CEI->getArgOperand(j));
4738           continue;
4739         }
4740 
4741         Value *OpVec = vectorizeTree(E->getOperand(j));
4742         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
4743         OpVecs.push_back(OpVec);
4744       }
4745 
4746       Function *CF;
4747       if (!UseIntrinsic) {
4748         VFShape Shape =
4749             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4750                                   VecTy->getNumElements())),
4751                          false /*HasGlobalPred*/);
4752         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
4753       } else {
4754         Type *Tys[] = {FixedVectorType::get(CI->getType(), E->Scalars.size())};
4755         CF = Intrinsic::getDeclaration(F->getParent(), ID, Tys);
4756       }
4757 
4758       SmallVector<OperandBundleDef, 1> OpBundles;
4759       CI->getOperandBundlesAsDefs(OpBundles);
4760       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
4761 
4762       // The scalar argument uses an in-tree scalar so we add the new vectorized
4763       // call to ExternalUses list to make sure that an extract will be
4764       // generated in the future.
4765       if (ScalarArg && getTreeEntry(ScalarArg))
4766         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
4767 
4768       propagateIRFlags(V, E->Scalars, VL0);
4769       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4770       V = ShuffleBuilder.finalize(V);
4771 
4772       E->VectorizedValue = V;
4773       ++NumVectorInstructions;
4774       return V;
4775     }
4776     case Instruction::ShuffleVector: {
4777       assert(E->isAltShuffle() &&
4778              ((Instruction::isBinaryOp(E->getOpcode()) &&
4779                Instruction::isBinaryOp(E->getAltOpcode())) ||
4780               (Instruction::isCast(E->getOpcode()) &&
4781                Instruction::isCast(E->getAltOpcode()))) &&
4782              "Invalid Shuffle Vector Operand");
4783 
4784       Value *LHS = nullptr, *RHS = nullptr;
4785       if (Instruction::isBinaryOp(E->getOpcode())) {
4786         setInsertPointAfterBundle(E);
4787         LHS = vectorizeTree(E->getOperand(0));
4788         RHS = vectorizeTree(E->getOperand(1));
4789       } else {
4790         setInsertPointAfterBundle(E);
4791         LHS = vectorizeTree(E->getOperand(0));
4792       }
4793 
4794       if (E->VectorizedValue) {
4795         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4796         return E->VectorizedValue;
4797       }
4798 
4799       Value *V0, *V1;
4800       if (Instruction::isBinaryOp(E->getOpcode())) {
4801         V0 = Builder.CreateBinOp(
4802             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
4803         V1 = Builder.CreateBinOp(
4804             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
4805       } else {
4806         V0 = Builder.CreateCast(
4807             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
4808         V1 = Builder.CreateCast(
4809             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
4810       }
4811 
4812       // Create shuffle to take alternate operations from the vector.
4813       // Also, gather up main and alt scalar ops to propagate IR flags to
4814       // each vector operation.
4815       ValueList OpScalars, AltScalars;
4816       unsigned e = E->Scalars.size();
4817       SmallVector<int, 8> Mask(e);
4818       for (unsigned i = 0; i < e; ++i) {
4819         auto *OpInst = cast<Instruction>(E->Scalars[i]);
4820         assert(E->isOpcodeOrAlt(OpInst) && "Unexpected main/alternate opcode");
4821         if (OpInst->getOpcode() == E->getAltOpcode()) {
4822           Mask[i] = e + i;
4823           AltScalars.push_back(E->Scalars[i]);
4824         } else {
4825           Mask[i] = i;
4826           OpScalars.push_back(E->Scalars[i]);
4827         }
4828       }
4829 
4830       propagateIRFlags(V0, OpScalars);
4831       propagateIRFlags(V1, AltScalars);
4832 
4833       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
4834       if (Instruction *I = dyn_cast<Instruction>(V))
4835         V = propagateMetadata(I, E->Scalars);
4836       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4837       V = ShuffleBuilder.finalize(V);
4838 
4839       E->VectorizedValue = V;
4840       ++NumVectorInstructions;
4841 
4842       return V;
4843     }
4844     default:
4845     llvm_unreachable("unknown inst");
4846   }
4847   return nullptr;
4848 }
4849 
4850 Value *BoUpSLP::vectorizeTree() {
4851   ExtraValueToDebugLocsMap ExternallyUsedValues;
4852   return vectorizeTree(ExternallyUsedValues);
4853 }
4854 
4855 Value *
4856 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4857   // All blocks must be scheduled before any instructions are inserted.
4858   for (auto &BSIter : BlocksSchedules) {
4859     scheduleBlock(BSIter.second.get());
4860   }
4861 
4862   Builder.SetInsertPoint(&F->getEntryBlock().front());
4863   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
4864 
4865   // If the vectorized tree can be rewritten in a smaller type, we truncate the
4866   // vectorized root. InstCombine will then rewrite the entire expression. We
4867   // sign extend the extracted values below.
4868   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
4869   if (MinBWs.count(ScalarRoot)) {
4870     if (auto *I = dyn_cast<Instruction>(VectorRoot))
4871       Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
4872     auto BundleWidth = VectorizableTree[0]->Scalars.size();
4873     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
4874     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
4875     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
4876     VectorizableTree[0]->VectorizedValue = Trunc;
4877   }
4878 
4879   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
4880                     << " values .\n");
4881 
4882   // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
4883   // specified by ScalarType.
4884   auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
4885     if (!MinBWs.count(ScalarRoot))
4886       return Ex;
4887     if (MinBWs[ScalarRoot].second)
4888       return Builder.CreateSExt(Ex, ScalarType);
4889     return Builder.CreateZExt(Ex, ScalarType);
4890   };
4891 
4892   // Extract all of the elements with the external uses.
4893   for (const auto &ExternalUse : ExternalUses) {
4894     Value *Scalar = ExternalUse.Scalar;
4895     llvm::User *User = ExternalUse.User;
4896 
4897     // Skip users that we already RAUW. This happens when one instruction
4898     // has multiple uses of the same value.
4899     if (User && !is_contained(Scalar->users(), User))
4900       continue;
4901     TreeEntry *E = getTreeEntry(Scalar);
4902     assert(E && "Invalid scalar");
4903     assert(E->State != TreeEntry::NeedToGather &&
4904            "Extracting from a gather list");
4905 
4906     Value *Vec = E->VectorizedValue;
4907     assert(Vec && "Can't find vectorizable value");
4908 
4909     Value *Lane = Builder.getInt32(ExternalUse.Lane);
4910     // If User == nullptr, the Scalar is used as extra arg. Generate
4911     // ExtractElement instruction and update the record for this scalar in
4912     // ExternallyUsedValues.
4913     if (!User) {
4914       assert(ExternallyUsedValues.count(Scalar) &&
4915              "Scalar with nullptr as an external user must be registered in "
4916              "ExternallyUsedValues map");
4917       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
4918         Builder.SetInsertPoint(VecI->getParent(),
4919                                std::next(VecI->getIterator()));
4920       } else {
4921         Builder.SetInsertPoint(&F->getEntryBlock().front());
4922       }
4923       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4924       Ex = extend(ScalarRoot, Ex, Scalar->getType());
4925       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
4926       auto &Locs = ExternallyUsedValues[Scalar];
4927       ExternallyUsedValues.insert({Ex, Locs});
4928       ExternallyUsedValues.erase(Scalar);
4929       // Required to update internally referenced instructions.
4930       Scalar->replaceAllUsesWith(Ex);
4931       continue;
4932     }
4933 
4934     // Generate extracts for out-of-tree users.
4935     // Find the insertion point for the extractelement lane.
4936     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
4937       if (PHINode *PH = dyn_cast<PHINode>(User)) {
4938         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
4939           if (PH->getIncomingValue(i) == Scalar) {
4940             Instruction *IncomingTerminator =
4941                 PH->getIncomingBlock(i)->getTerminator();
4942             if (isa<CatchSwitchInst>(IncomingTerminator)) {
4943               Builder.SetInsertPoint(VecI->getParent(),
4944                                      std::next(VecI->getIterator()));
4945             } else {
4946               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
4947             }
4948             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4949             Ex = extend(ScalarRoot, Ex, Scalar->getType());
4950             CSEBlocks.insert(PH->getIncomingBlock(i));
4951             PH->setOperand(i, Ex);
4952           }
4953         }
4954       } else {
4955         Builder.SetInsertPoint(cast<Instruction>(User));
4956         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4957         Ex = extend(ScalarRoot, Ex, Scalar->getType());
4958         CSEBlocks.insert(cast<Instruction>(User)->getParent());
4959         User->replaceUsesOfWith(Scalar, Ex);
4960       }
4961     } else {
4962       Builder.SetInsertPoint(&F->getEntryBlock().front());
4963       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4964       Ex = extend(ScalarRoot, Ex, Scalar->getType());
4965       CSEBlocks.insert(&F->getEntryBlock());
4966       User->replaceUsesOfWith(Scalar, Ex);
4967     }
4968 
4969     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
4970   }
4971 
4972   // For each vectorized value:
4973   for (auto &TEPtr : VectorizableTree) {
4974     TreeEntry *Entry = TEPtr.get();
4975 
4976     // No need to handle users of gathered values.
4977     if (Entry->State == TreeEntry::NeedToGather)
4978       continue;
4979 
4980     assert(Entry->VectorizedValue && "Can't find vectorizable value");
4981 
4982     // For each lane:
4983     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4984       Value *Scalar = Entry->Scalars[Lane];
4985 
4986 #ifndef NDEBUG
4987       Type *Ty = Scalar->getType();
4988       if (!Ty->isVoidTy()) {
4989         for (User *U : Scalar->users()) {
4990           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
4991 
4992           // It is legal to delete users in the ignorelist.
4993           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
4994                  "Deleting out-of-tree value");
4995         }
4996       }
4997 #endif
4998       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
4999       eraseInstruction(cast<Instruction>(Scalar));
5000     }
5001   }
5002 
5003   Builder.ClearInsertionPoint();
5004   InstrElementSize.clear();
5005 
5006   return VectorizableTree[0]->VectorizedValue;
5007 }
5008 
5009 void BoUpSLP::optimizeGatherSequence() {
5010   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
5011                     << " gather sequences instructions.\n");
5012   // LICM InsertElementInst sequences.
5013   for (Instruction *I : GatherSeq) {
5014     if (isDeleted(I))
5015       continue;
5016 
5017     // Check if this block is inside a loop.
5018     Loop *L = LI->getLoopFor(I->getParent());
5019     if (!L)
5020       continue;
5021 
5022     // Check if it has a preheader.
5023     BasicBlock *PreHeader = L->getLoopPreheader();
5024     if (!PreHeader)
5025       continue;
5026 
5027     // If the vector or the element that we insert into it are
5028     // instructions that are defined in this basic block then we can't
5029     // hoist this instruction.
5030     auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
5031     auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
5032     if (Op0 && L->contains(Op0))
5033       continue;
5034     if (Op1 && L->contains(Op1))
5035       continue;
5036 
5037     // We can hoist this instruction. Move it to the pre-header.
5038     I->moveBefore(PreHeader->getTerminator());
5039   }
5040 
5041   // Make a list of all reachable blocks in our CSE queue.
5042   SmallVector<const DomTreeNode *, 8> CSEWorkList;
5043   CSEWorkList.reserve(CSEBlocks.size());
5044   for (BasicBlock *BB : CSEBlocks)
5045     if (DomTreeNode *N = DT->getNode(BB)) {
5046       assert(DT->isReachableFromEntry(N));
5047       CSEWorkList.push_back(N);
5048     }
5049 
5050   // Sort blocks by domination. This ensures we visit a block after all blocks
5051   // dominating it are visited.
5052   llvm::stable_sort(CSEWorkList,
5053                     [this](const DomTreeNode *A, const DomTreeNode *B) {
5054                       return DT->properlyDominates(A, B);
5055                     });
5056 
5057   // Perform O(N^2) search over the gather sequences and merge identical
5058   // instructions. TODO: We can further optimize this scan if we split the
5059   // instructions into different buckets based on the insert lane.
5060   SmallVector<Instruction *, 16> Visited;
5061   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
5062     assert(*I &&
5063            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
5064            "Worklist not sorted properly!");
5065     BasicBlock *BB = (*I)->getBlock();
5066     // For all instructions in blocks containing gather sequences:
5067     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
5068       Instruction *In = &*it++;
5069       if (isDeleted(In))
5070         continue;
5071       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
5072         continue;
5073 
5074       // Check if we can replace this instruction with any of the
5075       // visited instructions.
5076       for (Instruction *v : Visited) {
5077         if (In->isIdenticalTo(v) &&
5078             DT->dominates(v->getParent(), In->getParent())) {
5079           In->replaceAllUsesWith(v);
5080           eraseInstruction(In);
5081           In = nullptr;
5082           break;
5083         }
5084       }
5085       if (In) {
5086         assert(!is_contained(Visited, In));
5087         Visited.push_back(In);
5088       }
5089     }
5090   }
5091   CSEBlocks.clear();
5092   GatherSeq.clear();
5093 }
5094 
5095 // Groups the instructions to a bundle (which is then a single scheduling entity)
5096 // and schedules instructions until the bundle gets ready.
5097 Optional<BoUpSLP::ScheduleData *>
5098 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
5099                                             const InstructionsState &S) {
5100   if (isa<PHINode>(S.OpValue))
5101     return nullptr;
5102 
5103   // Initialize the instruction bundle.
5104   Instruction *OldScheduleEnd = ScheduleEnd;
5105   ScheduleData *PrevInBundle = nullptr;
5106   ScheduleData *Bundle = nullptr;
5107   bool ReSchedule = false;
5108   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
5109 
5110   // Make sure that the scheduling region contains all
5111   // instructions of the bundle.
5112   for (Value *V : VL) {
5113     if (!extendSchedulingRegion(V, S))
5114       return None;
5115   }
5116 
5117   for (Value *V : VL) {
5118     ScheduleData *BundleMember = getScheduleData(V);
5119     assert(BundleMember &&
5120            "no ScheduleData for bundle member (maybe not in same basic block)");
5121     if (BundleMember->IsScheduled) {
5122       // A bundle member was scheduled as single instruction before and now
5123       // needs to be scheduled as part of the bundle. We just get rid of the
5124       // existing schedule.
5125       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
5126                         << " was already scheduled\n");
5127       ReSchedule = true;
5128     }
5129     assert(BundleMember->isSchedulingEntity() &&
5130            "bundle member already part of other bundle");
5131     if (PrevInBundle) {
5132       PrevInBundle->NextInBundle = BundleMember;
5133     } else {
5134       Bundle = BundleMember;
5135     }
5136     BundleMember->UnscheduledDepsInBundle = 0;
5137     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
5138 
5139     // Group the instructions to a bundle.
5140     BundleMember->FirstInBundle = Bundle;
5141     PrevInBundle = BundleMember;
5142   }
5143   if (ScheduleEnd != OldScheduleEnd) {
5144     // The scheduling region got new instructions at the lower end (or it is a
5145     // new region for the first bundle). This makes it necessary to
5146     // recalculate all dependencies.
5147     // It is seldom that this needs to be done a second time after adding the
5148     // initial bundle to the region.
5149     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
5150       doForAllOpcodes(I, [](ScheduleData *SD) {
5151         SD->clearDependencies();
5152       });
5153     }
5154     ReSchedule = true;
5155   }
5156   if (ReSchedule) {
5157     resetSchedule();
5158     initialFillReadyList(ReadyInsts);
5159   }
5160   assert(Bundle && "Failed to find schedule bundle");
5161 
5162   LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
5163                     << BB->getName() << "\n");
5164 
5165   calculateDependencies(Bundle, true, SLP);
5166 
5167   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
5168   // means that there are no cyclic dependencies and we can schedule it.
5169   // Note that's important that we don't "schedule" the bundle yet (see
5170   // cancelScheduling).
5171   while (!Bundle->isReady() && !ReadyInsts.empty()) {
5172 
5173     ScheduleData *pickedSD = ReadyInsts.back();
5174     ReadyInsts.pop_back();
5175 
5176     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
5177       schedule(pickedSD, ReadyInsts);
5178     }
5179   }
5180   if (!Bundle->isReady()) {
5181     cancelScheduling(VL, S.OpValue);
5182     return None;
5183   }
5184   return Bundle;
5185 }
5186 
5187 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
5188                                                 Value *OpValue) {
5189   if (isa<PHINode>(OpValue))
5190     return;
5191 
5192   ScheduleData *Bundle = getScheduleData(OpValue);
5193   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
5194   assert(!Bundle->IsScheduled &&
5195          "Can't cancel bundle which is already scheduled");
5196   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
5197          "tried to unbundle something which is not a bundle");
5198 
5199   // Un-bundle: make single instructions out of the bundle.
5200   ScheduleData *BundleMember = Bundle;
5201   while (BundleMember) {
5202     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
5203     BundleMember->FirstInBundle = BundleMember;
5204     ScheduleData *Next = BundleMember->NextInBundle;
5205     BundleMember->NextInBundle = nullptr;
5206     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
5207     if (BundleMember->UnscheduledDepsInBundle == 0) {
5208       ReadyInsts.insert(BundleMember);
5209     }
5210     BundleMember = Next;
5211   }
5212 }
5213 
5214 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
5215   // Allocate a new ScheduleData for the instruction.
5216   if (ChunkPos >= ChunkSize) {
5217     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
5218     ChunkPos = 0;
5219   }
5220   return &(ScheduleDataChunks.back()[ChunkPos++]);
5221 }
5222 
5223 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
5224                                                       const InstructionsState &S) {
5225   if (getScheduleData(V, isOneOf(S, V)))
5226     return true;
5227   Instruction *I = dyn_cast<Instruction>(V);
5228   assert(I && "bundle member must be an instruction");
5229   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
5230   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
5231     ScheduleData *ISD = getScheduleData(I);
5232     if (!ISD)
5233       return false;
5234     assert(isInSchedulingRegion(ISD) &&
5235            "ScheduleData not in scheduling region");
5236     ScheduleData *SD = allocateScheduleDataChunks();
5237     SD->Inst = I;
5238     SD->init(SchedulingRegionID, S.OpValue);
5239     ExtraScheduleDataMap[I][S.OpValue] = SD;
5240     return true;
5241   };
5242   if (CheckSheduleForI(I))
5243     return true;
5244   if (!ScheduleStart) {
5245     // It's the first instruction in the new region.
5246     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
5247     ScheduleStart = I;
5248     ScheduleEnd = I->getNextNode();
5249     if (isOneOf(S, I) != I)
5250       CheckSheduleForI(I);
5251     assert(ScheduleEnd && "tried to vectorize a terminator?");
5252     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
5253     return true;
5254   }
5255   // Search up and down at the same time, because we don't know if the new
5256   // instruction is above or below the existing scheduling region.
5257   BasicBlock::reverse_iterator UpIter =
5258       ++ScheduleStart->getIterator().getReverse();
5259   BasicBlock::reverse_iterator UpperEnd = BB->rend();
5260   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
5261   BasicBlock::iterator LowerEnd = BB->end();
5262   while (true) {
5263     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
5264       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
5265       return false;
5266     }
5267 
5268     if (UpIter != UpperEnd) {
5269       if (&*UpIter == I) {
5270         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
5271         ScheduleStart = I;
5272         if (isOneOf(S, I) != I)
5273           CheckSheduleForI(I);
5274         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
5275                           << "\n");
5276         return true;
5277       }
5278       ++UpIter;
5279     }
5280     if (DownIter != LowerEnd) {
5281       if (&*DownIter == I) {
5282         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
5283                          nullptr);
5284         ScheduleEnd = I->getNextNode();
5285         if (isOneOf(S, I) != I)
5286           CheckSheduleForI(I);
5287         assert(ScheduleEnd && "tried to vectorize a terminator?");
5288         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I
5289                           << "\n");
5290         return true;
5291       }
5292       ++DownIter;
5293     }
5294     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
5295            "instruction not found in block");
5296   }
5297   return true;
5298 }
5299 
5300 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
5301                                                 Instruction *ToI,
5302                                                 ScheduleData *PrevLoadStore,
5303                                                 ScheduleData *NextLoadStore) {
5304   ScheduleData *CurrentLoadStore = PrevLoadStore;
5305   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
5306     ScheduleData *SD = ScheduleDataMap[I];
5307     if (!SD) {
5308       SD = allocateScheduleDataChunks();
5309       ScheduleDataMap[I] = SD;
5310       SD->Inst = I;
5311     }
5312     assert(!isInSchedulingRegion(SD) &&
5313            "new ScheduleData already in scheduling region");
5314     SD->init(SchedulingRegionID, I);
5315 
5316     if (I->mayReadOrWriteMemory() &&
5317         (!isa<IntrinsicInst>(I) ||
5318          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
5319           cast<IntrinsicInst>(I)->getIntrinsicID() !=
5320               Intrinsic::pseudoprobe))) {
5321       // Update the linked list of memory accessing instructions.
5322       if (CurrentLoadStore) {
5323         CurrentLoadStore->NextLoadStore = SD;
5324       } else {
5325         FirstLoadStoreInRegion = SD;
5326       }
5327       CurrentLoadStore = SD;
5328     }
5329   }
5330   if (NextLoadStore) {
5331     if (CurrentLoadStore)
5332       CurrentLoadStore->NextLoadStore = NextLoadStore;
5333   } else {
5334     LastLoadStoreInRegion = CurrentLoadStore;
5335   }
5336 }
5337 
5338 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
5339                                                      bool InsertInReadyList,
5340                                                      BoUpSLP *SLP) {
5341   assert(SD->isSchedulingEntity());
5342 
5343   SmallVector<ScheduleData *, 10> WorkList;
5344   WorkList.push_back(SD);
5345 
5346   while (!WorkList.empty()) {
5347     ScheduleData *SD = WorkList.back();
5348     WorkList.pop_back();
5349 
5350     ScheduleData *BundleMember = SD;
5351     while (BundleMember) {
5352       assert(isInSchedulingRegion(BundleMember));
5353       if (!BundleMember->hasValidDependencies()) {
5354 
5355         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
5356                           << "\n");
5357         BundleMember->Dependencies = 0;
5358         BundleMember->resetUnscheduledDeps();
5359 
5360         // Handle def-use chain dependencies.
5361         if (BundleMember->OpValue != BundleMember->Inst) {
5362           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
5363           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
5364             BundleMember->Dependencies++;
5365             ScheduleData *DestBundle = UseSD->FirstInBundle;
5366             if (!DestBundle->IsScheduled)
5367               BundleMember->incrementUnscheduledDeps(1);
5368             if (!DestBundle->hasValidDependencies())
5369               WorkList.push_back(DestBundle);
5370           }
5371         } else {
5372           for (User *U : BundleMember->Inst->users()) {
5373             if (isa<Instruction>(U)) {
5374               ScheduleData *UseSD = getScheduleData(U);
5375               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
5376                 BundleMember->Dependencies++;
5377                 ScheduleData *DestBundle = UseSD->FirstInBundle;
5378                 if (!DestBundle->IsScheduled)
5379                   BundleMember->incrementUnscheduledDeps(1);
5380                 if (!DestBundle->hasValidDependencies())
5381                   WorkList.push_back(DestBundle);
5382               }
5383             } else {
5384               // I'm not sure if this can ever happen. But we need to be safe.
5385               // This lets the instruction/bundle never be scheduled and
5386               // eventually disable vectorization.
5387               BundleMember->Dependencies++;
5388               BundleMember->incrementUnscheduledDeps(1);
5389             }
5390           }
5391         }
5392 
5393         // Handle the memory dependencies.
5394         ScheduleData *DepDest = BundleMember->NextLoadStore;
5395         if (DepDest) {
5396           Instruction *SrcInst = BundleMember->Inst;
5397           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
5398           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
5399           unsigned numAliased = 0;
5400           unsigned DistToSrc = 1;
5401 
5402           while (DepDest) {
5403             assert(isInSchedulingRegion(DepDest));
5404 
5405             // We have two limits to reduce the complexity:
5406             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
5407             //    SLP->isAliased (which is the expensive part in this loop).
5408             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
5409             //    the whole loop (even if the loop is fast, it's quadratic).
5410             //    It's important for the loop break condition (see below) to
5411             //    check this limit even between two read-only instructions.
5412             if (DistToSrc >= MaxMemDepDistance ||
5413                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
5414                      (numAliased >= AliasedCheckLimit ||
5415                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
5416 
5417               // We increment the counter only if the locations are aliased
5418               // (instead of counting all alias checks). This gives a better
5419               // balance between reduced runtime and accurate dependencies.
5420               numAliased++;
5421 
5422               DepDest->MemoryDependencies.push_back(BundleMember);
5423               BundleMember->Dependencies++;
5424               ScheduleData *DestBundle = DepDest->FirstInBundle;
5425               if (!DestBundle->IsScheduled) {
5426                 BundleMember->incrementUnscheduledDeps(1);
5427               }
5428               if (!DestBundle->hasValidDependencies()) {
5429                 WorkList.push_back(DestBundle);
5430               }
5431             }
5432             DepDest = DepDest->NextLoadStore;
5433 
5434             // Example, explaining the loop break condition: Let's assume our
5435             // starting instruction is i0 and MaxMemDepDistance = 3.
5436             //
5437             //                      +--------v--v--v
5438             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
5439             //             +--------^--^--^
5440             //
5441             // MaxMemDepDistance let us stop alias-checking at i3 and we add
5442             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
5443             // Previously we already added dependencies from i3 to i6,i7,i8
5444             // (because of MaxMemDepDistance). As we added a dependency from
5445             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
5446             // and we can abort this loop at i6.
5447             if (DistToSrc >= 2 * MaxMemDepDistance)
5448               break;
5449             DistToSrc++;
5450           }
5451         }
5452       }
5453       BundleMember = BundleMember->NextInBundle;
5454     }
5455     if (InsertInReadyList && SD->isReady()) {
5456       ReadyInsts.push_back(SD);
5457       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
5458                         << "\n");
5459     }
5460   }
5461 }
5462 
5463 void BoUpSLP::BlockScheduling::resetSchedule() {
5464   assert(ScheduleStart &&
5465          "tried to reset schedule on block which has not been scheduled");
5466   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
5467     doForAllOpcodes(I, [&](ScheduleData *SD) {
5468       assert(isInSchedulingRegion(SD) &&
5469              "ScheduleData not in scheduling region");
5470       SD->IsScheduled = false;
5471       SD->resetUnscheduledDeps();
5472     });
5473   }
5474   ReadyInsts.clear();
5475 }
5476 
5477 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
5478   if (!BS->ScheduleStart)
5479     return;
5480 
5481   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
5482 
5483   BS->resetSchedule();
5484 
5485   // For the real scheduling we use a more sophisticated ready-list: it is
5486   // sorted by the original instruction location. This lets the final schedule
5487   // be as  close as possible to the original instruction order.
5488   struct ScheduleDataCompare {
5489     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
5490       return SD2->SchedulingPriority < SD1->SchedulingPriority;
5491     }
5492   };
5493   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
5494 
5495   // Ensure that all dependency data is updated and fill the ready-list with
5496   // initial instructions.
5497   int Idx = 0;
5498   int NumToSchedule = 0;
5499   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
5500        I = I->getNextNode()) {
5501     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
5502       assert(SD->isPartOfBundle() ==
5503                  (getTreeEntry(SD->Inst) != nullptr) &&
5504              "scheduler and vectorizer bundle mismatch");
5505       SD->FirstInBundle->SchedulingPriority = Idx++;
5506       if (SD->isSchedulingEntity()) {
5507         BS->calculateDependencies(SD, false, this);
5508         NumToSchedule++;
5509       }
5510     });
5511   }
5512   BS->initialFillReadyList(ReadyInsts);
5513 
5514   Instruction *LastScheduledInst = BS->ScheduleEnd;
5515 
5516   // Do the "real" scheduling.
5517   while (!ReadyInsts.empty()) {
5518     ScheduleData *picked = *ReadyInsts.begin();
5519     ReadyInsts.erase(ReadyInsts.begin());
5520 
5521     // Move the scheduled instruction(s) to their dedicated places, if not
5522     // there yet.
5523     ScheduleData *BundleMember = picked;
5524     while (BundleMember) {
5525       Instruction *pickedInst = BundleMember->Inst;
5526       if (LastScheduledInst->getNextNode() != pickedInst) {
5527         BS->BB->getInstList().remove(pickedInst);
5528         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
5529                                      pickedInst);
5530       }
5531       LastScheduledInst = pickedInst;
5532       BundleMember = BundleMember->NextInBundle;
5533     }
5534 
5535     BS->schedule(picked, ReadyInsts);
5536     NumToSchedule--;
5537   }
5538   assert(NumToSchedule == 0 && "could not schedule all instructions");
5539 
5540   // Avoid duplicate scheduling of the block.
5541   BS->ScheduleStart = nullptr;
5542 }
5543 
5544 unsigned BoUpSLP::getVectorElementSize(Value *V) {
5545   // If V is a store, just return the width of the stored value (or value
5546   // truncated just before storing) without traversing the expression tree.
5547   // This is the common case.
5548   if (auto *Store = dyn_cast<StoreInst>(V)) {
5549     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
5550       return DL->getTypeSizeInBits(Trunc->getSrcTy());
5551     else
5552       return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
5553   }
5554 
5555   auto E = InstrElementSize.find(V);
5556   if (E != InstrElementSize.end())
5557     return E->second;
5558 
5559   // If V is not a store, we can traverse the expression tree to find loads
5560   // that feed it. The type of the loaded value may indicate a more suitable
5561   // width than V's type. We want to base the vector element size on the width
5562   // of memory operations where possible.
5563   SmallVector<Instruction *, 16> Worklist;
5564   SmallPtrSet<Instruction *, 16> Visited;
5565   if (auto *I = dyn_cast<Instruction>(V)) {
5566     Worklist.push_back(I);
5567     Visited.insert(I);
5568   }
5569 
5570   // Traverse the expression tree in bottom-up order looking for loads. If we
5571   // encounter an instruction we don't yet handle, we give up.
5572   auto MaxWidth = 0u;
5573   auto FoundUnknownInst = false;
5574   while (!Worklist.empty() && !FoundUnknownInst) {
5575     auto *I = Worklist.pop_back_val();
5576 
5577     // We should only be looking at scalar instructions here. If the current
5578     // instruction has a vector type, give up.
5579     auto *Ty = I->getType();
5580     if (isa<VectorType>(Ty))
5581       FoundUnknownInst = true;
5582 
5583     // If the current instruction is a load, update MaxWidth to reflect the
5584     // width of the loaded value.
5585     else if (isa<LoadInst>(I))
5586       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
5587 
5588     // Otherwise, we need to visit the operands of the instruction. We only
5589     // handle the interesting cases from buildTree here. If an operand is an
5590     // instruction we haven't yet visited, we add it to the worklist.
5591     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5592              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
5593       for (Use &U : I->operands())
5594         if (auto *J = dyn_cast<Instruction>(U.get()))
5595           if (Visited.insert(J).second)
5596             Worklist.push_back(J);
5597     }
5598 
5599     // If we don't yet handle the instruction, give up.
5600     else
5601       FoundUnknownInst = true;
5602   }
5603 
5604   int Width = MaxWidth;
5605   // If we didn't encounter a memory access in the expression tree, or if we
5606   // gave up for some reason, just return the width of V. Otherwise, return the
5607   // maximum width we found.
5608   if (!MaxWidth || FoundUnknownInst)
5609     Width = DL->getTypeSizeInBits(V->getType());
5610 
5611   for (Instruction *I : Visited)
5612     InstrElementSize[I] = Width;
5613 
5614   return Width;
5615 }
5616 
5617 // Determine if a value V in a vectorizable expression Expr can be demoted to a
5618 // smaller type with a truncation. We collect the values that will be demoted
5619 // in ToDemote and additional roots that require investigating in Roots.
5620 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
5621                                   SmallVectorImpl<Value *> &ToDemote,
5622                                   SmallVectorImpl<Value *> &Roots) {
5623   // We can always demote constants.
5624   if (isa<Constant>(V)) {
5625     ToDemote.push_back(V);
5626     return true;
5627   }
5628 
5629   // If the value is not an instruction in the expression with only one use, it
5630   // cannot be demoted.
5631   auto *I = dyn_cast<Instruction>(V);
5632   if (!I || !I->hasOneUse() || !Expr.count(I))
5633     return false;
5634 
5635   switch (I->getOpcode()) {
5636 
5637   // We can always demote truncations and extensions. Since truncations can
5638   // seed additional demotion, we save the truncated value.
5639   case Instruction::Trunc:
5640     Roots.push_back(I->getOperand(0));
5641     break;
5642   case Instruction::ZExt:
5643   case Instruction::SExt:
5644     break;
5645 
5646   // We can demote certain binary operations if we can demote both of their
5647   // operands.
5648   case Instruction::Add:
5649   case Instruction::Sub:
5650   case Instruction::Mul:
5651   case Instruction::And:
5652   case Instruction::Or:
5653   case Instruction::Xor:
5654     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
5655         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
5656       return false;
5657     break;
5658 
5659   // We can demote selects if we can demote their true and false values.
5660   case Instruction::Select: {
5661     SelectInst *SI = cast<SelectInst>(I);
5662     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
5663         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
5664       return false;
5665     break;
5666   }
5667 
5668   // We can demote phis if we can demote all their incoming operands. Note that
5669   // we don't need to worry about cycles since we ensure single use above.
5670   case Instruction::PHI: {
5671     PHINode *PN = cast<PHINode>(I);
5672     for (Value *IncValue : PN->incoming_values())
5673       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
5674         return false;
5675     break;
5676   }
5677 
5678   // Otherwise, conservatively give up.
5679   default:
5680     return false;
5681   }
5682 
5683   // Record the value that we can demote.
5684   ToDemote.push_back(V);
5685   return true;
5686 }
5687 
5688 void BoUpSLP::computeMinimumValueSizes() {
5689   // If there are no external uses, the expression tree must be rooted by a
5690   // store. We can't demote in-memory values, so there is nothing to do here.
5691   if (ExternalUses.empty())
5692     return;
5693 
5694   // We only attempt to truncate integer expressions.
5695   auto &TreeRoot = VectorizableTree[0]->Scalars;
5696   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
5697   if (!TreeRootIT)
5698     return;
5699 
5700   // If the expression is not rooted by a store, these roots should have
5701   // external uses. We will rely on InstCombine to rewrite the expression in
5702   // the narrower type. However, InstCombine only rewrites single-use values.
5703   // This means that if a tree entry other than a root is used externally, it
5704   // must have multiple uses and InstCombine will not rewrite it. The code
5705   // below ensures that only the roots are used externally.
5706   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
5707   for (auto &EU : ExternalUses)
5708     if (!Expr.erase(EU.Scalar))
5709       return;
5710   if (!Expr.empty())
5711     return;
5712 
5713   // Collect the scalar values of the vectorizable expression. We will use this
5714   // context to determine which values can be demoted. If we see a truncation,
5715   // we mark it as seeding another demotion.
5716   for (auto &EntryPtr : VectorizableTree)
5717     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
5718 
5719   // Ensure the roots of the vectorizable tree don't form a cycle. They must
5720   // have a single external user that is not in the vectorizable tree.
5721   for (auto *Root : TreeRoot)
5722     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
5723       return;
5724 
5725   // Conservatively determine if we can actually truncate the roots of the
5726   // expression. Collect the values that can be demoted in ToDemote and
5727   // additional roots that require investigating in Roots.
5728   SmallVector<Value *, 32> ToDemote;
5729   SmallVector<Value *, 4> Roots;
5730   for (auto *Root : TreeRoot)
5731     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
5732       return;
5733 
5734   // The maximum bit width required to represent all the values that can be
5735   // demoted without loss of precision. It would be safe to truncate the roots
5736   // of the expression to this width.
5737   auto MaxBitWidth = 8u;
5738 
5739   // We first check if all the bits of the roots are demanded. If they're not,
5740   // we can truncate the roots to this narrower type.
5741   for (auto *Root : TreeRoot) {
5742     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
5743     MaxBitWidth = std::max<unsigned>(
5744         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
5745   }
5746 
5747   // True if the roots can be zero-extended back to their original type, rather
5748   // than sign-extended. We know that if the leading bits are not demanded, we
5749   // can safely zero-extend. So we initialize IsKnownPositive to True.
5750   bool IsKnownPositive = true;
5751 
5752   // If all the bits of the roots are demanded, we can try a little harder to
5753   // compute a narrower type. This can happen, for example, if the roots are
5754   // getelementptr indices. InstCombine promotes these indices to the pointer
5755   // width. Thus, all their bits are technically demanded even though the
5756   // address computation might be vectorized in a smaller type.
5757   //
5758   // We start by looking at each entry that can be demoted. We compute the
5759   // maximum bit width required to store the scalar by using ValueTracking to
5760   // compute the number of high-order bits we can truncate.
5761   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
5762       llvm::all_of(TreeRoot, [](Value *R) {
5763         assert(R->hasOneUse() && "Root should have only one use!");
5764         return isa<GetElementPtrInst>(R->user_back());
5765       })) {
5766     MaxBitWidth = 8u;
5767 
5768     // Determine if the sign bit of all the roots is known to be zero. If not,
5769     // IsKnownPositive is set to False.
5770     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
5771       KnownBits Known = computeKnownBits(R, *DL);
5772       return Known.isNonNegative();
5773     });
5774 
5775     // Determine the maximum number of bits required to store the scalar
5776     // values.
5777     for (auto *Scalar : ToDemote) {
5778       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
5779       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
5780       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
5781     }
5782 
5783     // If we can't prove that the sign bit is zero, we must add one to the
5784     // maximum bit width to account for the unknown sign bit. This preserves
5785     // the existing sign bit so we can safely sign-extend the root back to the
5786     // original type. Otherwise, if we know the sign bit is zero, we will
5787     // zero-extend the root instead.
5788     //
5789     // FIXME: This is somewhat suboptimal, as there will be cases where adding
5790     //        one to the maximum bit width will yield a larger-than-necessary
5791     //        type. In general, we need to add an extra bit only if we can't
5792     //        prove that the upper bit of the original type is equal to the
5793     //        upper bit of the proposed smaller type. If these two bits are the
5794     //        same (either zero or one) we know that sign-extending from the
5795     //        smaller type will result in the same value. Here, since we can't
5796     //        yet prove this, we are just making the proposed smaller type
5797     //        larger to ensure correctness.
5798     if (!IsKnownPositive)
5799       ++MaxBitWidth;
5800   }
5801 
5802   // Round MaxBitWidth up to the next power-of-two.
5803   if (!isPowerOf2_64(MaxBitWidth))
5804     MaxBitWidth = NextPowerOf2(MaxBitWidth);
5805 
5806   // If the maximum bit width we compute is less than the with of the roots'
5807   // type, we can proceed with the narrowing. Otherwise, do nothing.
5808   if (MaxBitWidth >= TreeRootIT->getBitWidth())
5809     return;
5810 
5811   // If we can truncate the root, we must collect additional values that might
5812   // be demoted as a result. That is, those seeded by truncations we will
5813   // modify.
5814   while (!Roots.empty())
5815     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
5816 
5817   // Finally, map the values we can demote to the maximum bit with we computed.
5818   for (auto *Scalar : ToDemote)
5819     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
5820 }
5821 
5822 namespace {
5823 
5824 /// The SLPVectorizer Pass.
5825 struct SLPVectorizer : public FunctionPass {
5826   SLPVectorizerPass Impl;
5827 
5828   /// Pass identification, replacement for typeid
5829   static char ID;
5830 
5831   explicit SLPVectorizer() : FunctionPass(ID) {
5832     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
5833   }
5834 
5835   bool doInitialization(Module &M) override {
5836     return false;
5837   }
5838 
5839   bool runOnFunction(Function &F) override {
5840     if (skipFunction(F))
5841       return false;
5842 
5843     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5844     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
5845     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5846     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
5847     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
5848     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5849     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5850     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
5851     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
5852     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
5853 
5854     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5855   }
5856 
5857   void getAnalysisUsage(AnalysisUsage &AU) const override {
5858     FunctionPass::getAnalysisUsage(AU);
5859     AU.addRequired<AssumptionCacheTracker>();
5860     AU.addRequired<ScalarEvolutionWrapperPass>();
5861     AU.addRequired<AAResultsWrapperPass>();
5862     AU.addRequired<TargetTransformInfoWrapperPass>();
5863     AU.addRequired<LoopInfoWrapperPass>();
5864     AU.addRequired<DominatorTreeWrapperPass>();
5865     AU.addRequired<DemandedBitsWrapperPass>();
5866     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
5867     AU.addRequired<InjectTLIMappingsLegacy>();
5868     AU.addPreserved<LoopInfoWrapperPass>();
5869     AU.addPreserved<DominatorTreeWrapperPass>();
5870     AU.addPreserved<AAResultsWrapperPass>();
5871     AU.addPreserved<GlobalsAAWrapperPass>();
5872     AU.setPreservesCFG();
5873   }
5874 };
5875 
5876 } // end anonymous namespace
5877 
5878 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
5879   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
5880   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
5881   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
5882   auto *AA = &AM.getResult<AAManager>(F);
5883   auto *LI = &AM.getResult<LoopAnalysis>(F);
5884   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
5885   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
5886   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
5887   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5888 
5889   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5890   if (!Changed)
5891     return PreservedAnalyses::all();
5892 
5893   PreservedAnalyses PA;
5894   PA.preserveSet<CFGAnalyses>();
5895   PA.preserve<AAManager>();
5896   PA.preserve<GlobalsAA>();
5897   return PA;
5898 }
5899 
5900 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
5901                                 TargetTransformInfo *TTI_,
5902                                 TargetLibraryInfo *TLI_, AAResults *AA_,
5903                                 LoopInfo *LI_, DominatorTree *DT_,
5904                                 AssumptionCache *AC_, DemandedBits *DB_,
5905                                 OptimizationRemarkEmitter *ORE_) {
5906   if (!RunSLPVectorization)
5907     return false;
5908   SE = SE_;
5909   TTI = TTI_;
5910   TLI = TLI_;
5911   AA = AA_;
5912   LI = LI_;
5913   DT = DT_;
5914   AC = AC_;
5915   DB = DB_;
5916   DL = &F.getParent()->getDataLayout();
5917 
5918   Stores.clear();
5919   GEPs.clear();
5920   bool Changed = false;
5921 
5922   // If the target claims to have no vector registers don't attempt
5923   // vectorization.
5924   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)))
5925     return false;
5926 
5927   // Don't vectorize when the attribute NoImplicitFloat is used.
5928   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
5929     return false;
5930 
5931   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
5932 
5933   // Use the bottom up slp vectorizer to construct chains that start with
5934   // store instructions.
5935   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
5936 
5937   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
5938   // delete instructions.
5939 
5940   // Scan the blocks in the function in post order.
5941   for (auto BB : post_order(&F.getEntryBlock())) {
5942     collectSeedInstructions(BB);
5943 
5944     // Vectorize trees that end at stores.
5945     if (!Stores.empty()) {
5946       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
5947                         << " underlying objects.\n");
5948       Changed |= vectorizeStoreChains(R);
5949     }
5950 
5951     // Vectorize trees that end at reductions.
5952     Changed |= vectorizeChainsInBlock(BB, R);
5953 
5954     // Vectorize the index computations of getelementptr instructions. This
5955     // is primarily intended to catch gather-like idioms ending at
5956     // non-consecutive loads.
5957     if (!GEPs.empty()) {
5958       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
5959                         << " underlying objects.\n");
5960       Changed |= vectorizeGEPIndices(BB, R);
5961     }
5962   }
5963 
5964   if (Changed) {
5965     R.optimizeGatherSequence();
5966     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
5967   }
5968   return Changed;
5969 }
5970 
5971 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
5972                                             unsigned Idx) {
5973   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
5974                     << "\n");
5975   const unsigned Sz = R.getVectorElementSize(Chain[0]);
5976   const unsigned MinVF = R.getMinVecRegSize() / Sz;
5977   unsigned VF = Chain.size();
5978 
5979   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
5980     return false;
5981 
5982   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
5983                     << "\n");
5984 
5985   R.buildTree(Chain);
5986   Optional<ArrayRef<unsigned>> Order = R.bestOrder();
5987   // TODO: Handle orders of size less than number of elements in the vector.
5988   if (Order && Order->size() == Chain.size()) {
5989     // TODO: reorder tree nodes without tree rebuilding.
5990     SmallVector<Value *, 4> ReorderedOps(Chain.rbegin(), Chain.rend());
5991     llvm::transform(*Order, ReorderedOps.begin(),
5992                     [Chain](const unsigned Idx) { return Chain[Idx]; });
5993     R.buildTree(ReorderedOps);
5994   }
5995   if (R.isTreeTinyAndNotFullyVectorizable())
5996     return false;
5997   if (R.isLoadCombineCandidate())
5998     return false;
5999 
6000   R.computeMinimumValueSizes();
6001 
6002   InstructionCost Cost = R.getTreeCost();
6003 
6004   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
6005   if (Cost.isValid() && Cost < -SLPCostThreshold) {
6006     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
6007 
6008     using namespace ore;
6009 
6010     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
6011                                         cast<StoreInst>(Chain[0]))
6012                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
6013                      << " and with tree size "
6014                      << NV("TreeSize", R.getTreeSize()));
6015 
6016     R.vectorizeTree();
6017     return true;
6018   }
6019 
6020   return false;
6021 }
6022 
6023 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
6024                                         BoUpSLP &R) {
6025   // We may run into multiple chains that merge into a single chain. We mark the
6026   // stores that we vectorized so that we don't visit the same store twice.
6027   BoUpSLP::ValueSet VectorizedStores;
6028   bool Changed = false;
6029 
6030   int E = Stores.size();
6031   SmallBitVector Tails(E, false);
6032   SmallVector<int, 16> ConsecutiveChain(E, E + 1);
6033   int MaxIter = MaxStoreLookup.getValue();
6034   int IterCnt;
6035   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
6036                                   &ConsecutiveChain](int K, int Idx) {
6037     if (IterCnt >= MaxIter)
6038       return true;
6039     ++IterCnt;
6040     if (!isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE))
6041       return false;
6042 
6043     Tails.set(Idx);
6044     ConsecutiveChain[K] = Idx;
6045     return true;
6046   };
6047   // Do a quadratic search on all of the given stores in reverse order and find
6048   // all of the pairs of stores that follow each other.
6049   for (int Idx = E - 1; Idx >= 0; --Idx) {
6050     // If a store has multiple consecutive store candidates, search according
6051     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
6052     // This is because usually pairing with immediate succeeding or preceding
6053     // candidate create the best chance to find slp vectorization opportunity.
6054     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
6055     IterCnt = 0;
6056     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
6057       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
6058           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
6059         break;
6060   }
6061 
6062   // For stores that start but don't end a link in the chain:
6063   for (int Cnt = E; Cnt > 0; --Cnt) {
6064     int I = Cnt - 1;
6065     if (ConsecutiveChain[I] == E + 1 || Tails.test(I))
6066       continue;
6067     // We found a store instr that starts a chain. Now follow the chain and try
6068     // to vectorize it.
6069     BoUpSLP::ValueList Operands;
6070     // Collect the chain into a list.
6071     while (I != E + 1 && !VectorizedStores.count(Stores[I])) {
6072       Operands.push_back(Stores[I]);
6073       // Move to the next value in the chain.
6074       I = ConsecutiveChain[I];
6075     }
6076 
6077     // If a vector register can't hold 1 element, we are done.
6078     unsigned MaxVecRegSize = R.getMaxVecRegSize();
6079     unsigned EltSize = R.getVectorElementSize(Operands[0]);
6080     if (MaxVecRegSize % EltSize != 0)
6081       continue;
6082 
6083     unsigned MaxElts = MaxVecRegSize / EltSize;
6084     // FIXME: Is division-by-2 the correct step? Should we assert that the
6085     // register size is a power-of-2?
6086     unsigned StartIdx = 0;
6087     for (unsigned Size = llvm::PowerOf2Ceil(MaxElts); Size >= 2; Size /= 2) {
6088       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
6089         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
6090         if (!VectorizedStores.count(Slice.front()) &&
6091             !VectorizedStores.count(Slice.back()) &&
6092             vectorizeStoreChain(Slice, R, Cnt)) {
6093           // Mark the vectorized stores so that we don't vectorize them again.
6094           VectorizedStores.insert(Slice.begin(), Slice.end());
6095           Changed = true;
6096           // If we vectorized initial block, no need to try to vectorize it
6097           // again.
6098           if (Cnt == StartIdx)
6099             StartIdx += Size;
6100           Cnt += Size;
6101           continue;
6102         }
6103         ++Cnt;
6104       }
6105       // Check if the whole array was vectorized already - exit.
6106       if (StartIdx >= Operands.size())
6107         break;
6108     }
6109   }
6110 
6111   return Changed;
6112 }
6113 
6114 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
6115   // Initialize the collections. We will make a single pass over the block.
6116   Stores.clear();
6117   GEPs.clear();
6118 
6119   // Visit the store and getelementptr instructions in BB and organize them in
6120   // Stores and GEPs according to the underlying objects of their pointer
6121   // operands.
6122   for (Instruction &I : *BB) {
6123     // Ignore store instructions that are volatile or have a pointer operand
6124     // that doesn't point to a scalar type.
6125     if (auto *SI = dyn_cast<StoreInst>(&I)) {
6126       if (!SI->isSimple())
6127         continue;
6128       if (!isValidElementType(SI->getValueOperand()->getType()))
6129         continue;
6130       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
6131     }
6132 
6133     // Ignore getelementptr instructions that have more than one index, a
6134     // constant index, or a pointer operand that doesn't point to a scalar
6135     // type.
6136     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
6137       auto Idx = GEP->idx_begin()->get();
6138       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
6139         continue;
6140       if (!isValidElementType(Idx->getType()))
6141         continue;
6142       if (GEP->getType()->isVectorTy())
6143         continue;
6144       GEPs[GEP->getPointerOperand()].push_back(GEP);
6145     }
6146   }
6147 }
6148 
6149 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
6150   if (!A || !B)
6151     return false;
6152   Value *VL[] = {A, B};
6153   return tryToVectorizeList(VL, R, /*AllowReorder=*/true);
6154 }
6155 
6156 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
6157                                            bool AllowReorder,
6158                                            ArrayRef<Value *> InsertUses) {
6159   if (VL.size() < 2)
6160     return false;
6161 
6162   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
6163                     << VL.size() << ".\n");
6164 
6165   // Check that all of the parts are instructions of the same type,
6166   // we permit an alternate opcode via InstructionsState.
6167   InstructionsState S = getSameOpcode(VL);
6168   if (!S.getOpcode())
6169     return false;
6170 
6171   Instruction *I0 = cast<Instruction>(S.OpValue);
6172   // Make sure invalid types (including vector type) are rejected before
6173   // determining vectorization factor for scalar instructions.
6174   for (Value *V : VL) {
6175     Type *Ty = V->getType();
6176     if (!isValidElementType(Ty)) {
6177       // NOTE: the following will give user internal llvm type name, which may
6178       // not be useful.
6179       R.getORE()->emit([&]() {
6180         std::string type_str;
6181         llvm::raw_string_ostream rso(type_str);
6182         Ty->print(rso);
6183         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
6184                << "Cannot SLP vectorize list: type "
6185                << rso.str() + " is unsupported by vectorizer";
6186       });
6187       return false;
6188     }
6189   }
6190 
6191   unsigned Sz = R.getVectorElementSize(I0);
6192   unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
6193   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
6194   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
6195   if (MaxVF < 2) {
6196     R.getORE()->emit([&]() {
6197       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
6198              << "Cannot SLP vectorize list: vectorization factor "
6199              << "less than 2 is not supported";
6200     });
6201     return false;
6202   }
6203 
6204   bool Changed = false;
6205   bool CandidateFound = false;
6206   InstructionCost MinCost = SLPCostThreshold.getValue();
6207 
6208   bool CompensateUseCost =
6209       !InsertUses.empty() && llvm::all_of(InsertUses, [](const Value *V) {
6210         return V && isa<InsertElementInst>(V);
6211       });
6212   assert((!CompensateUseCost || InsertUses.size() == VL.size()) &&
6213          "Each scalar expected to have an associated InsertElement user.");
6214 
6215   unsigned NextInst = 0, MaxInst = VL.size();
6216   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
6217     // No actual vectorization should happen, if number of parts is the same as
6218     // provided vectorization factor (i.e. the scalar type is used for vector
6219     // code during codegen).
6220     auto *VecTy = FixedVectorType::get(VL[0]->getType(), VF);
6221     if (TTI->getNumberOfParts(VecTy) == VF)
6222       continue;
6223     for (unsigned I = NextInst; I < MaxInst; ++I) {
6224       unsigned OpsWidth = 0;
6225 
6226       if (I + VF > MaxInst)
6227         OpsWidth = MaxInst - I;
6228       else
6229         OpsWidth = VF;
6230 
6231       if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
6232         break;
6233 
6234       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
6235       // Check that a previous iteration of this loop did not delete the Value.
6236       if (llvm::any_of(Ops, [&R](Value *V) {
6237             auto *I = dyn_cast<Instruction>(V);
6238             return I && R.isDeleted(I);
6239           }))
6240         continue;
6241 
6242       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
6243                         << "\n");
6244 
6245       R.buildTree(Ops);
6246       Optional<ArrayRef<unsigned>> Order = R.bestOrder();
6247       // TODO: check if we can allow reordering for more cases.
6248       if (AllowReorder && Order) {
6249         // TODO: reorder tree nodes without tree rebuilding.
6250         // Conceptually, there is nothing actually preventing us from trying to
6251         // reorder a larger list. In fact, we do exactly this when vectorizing
6252         // reductions. However, at this point, we only expect to get here when
6253         // there are exactly two operations.
6254         assert(Ops.size() == 2);
6255         Value *ReorderedOps[] = {Ops[1], Ops[0]};
6256         R.buildTree(ReorderedOps, None);
6257       }
6258       if (R.isTreeTinyAndNotFullyVectorizable())
6259         continue;
6260 
6261       R.computeMinimumValueSizes();
6262       InstructionCost Cost = R.getTreeCost();
6263       CandidateFound = true;
6264       if (CompensateUseCost) {
6265         // TODO: Use TTI's getScalarizationOverhead for sequence of inserts
6266         // rather than sum of single inserts as the latter may overestimate
6267         // cost. This work should imply improving cost estimation for extracts
6268         // that added in for external (for vectorization tree) users,i.e. that
6269         // part should also switch to same interface.
6270         // For example, the following case is projected code after SLP:
6271         //  %4 = extractelement <4 x i64> %3, i32 0
6272         //  %v0 = insertelement <4 x i64> poison, i64 %4, i32 0
6273         //  %5 = extractelement <4 x i64> %3, i32 1
6274         //  %v1 = insertelement <4 x i64> %v0, i64 %5, i32 1
6275         //  %6 = extractelement <4 x i64> %3, i32 2
6276         //  %v2 = insertelement <4 x i64> %v1, i64 %6, i32 2
6277         //  %7 = extractelement <4 x i64> %3, i32 3
6278         //  %v3 = insertelement <4 x i64> %v2, i64 %7, i32 3
6279         //
6280         // Extracts here added by SLP in order to feed users (the inserts) of
6281         // original scalars and contribute to "ExtractCost" at cost evaluation.
6282         // The inserts in turn form sequence to build an aggregate that
6283         // detected by findBuildAggregate routine.
6284         // SLP makes an assumption that such sequence will be optimized away
6285         // later (instcombine) so it tries to compensate ExctractCost with
6286         // cost of insert sequence.
6287         // Current per element cost calculation approach is not quite accurate
6288         // and tends to create bias toward favoring vectorization.
6289         // Switching to the TTI interface might help a bit.
6290         // Alternative solution could be pattern-match to detect a no-op or
6291         // shuffle.
6292         InstructionCost UserCost = 0;
6293         for (unsigned Lane = 0; Lane < OpsWidth; Lane++) {
6294           auto *IE = cast<InsertElementInst>(InsertUses[I + Lane]);
6295           if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2)))
6296             UserCost += TTI->getVectorInstrCost(
6297                 Instruction::InsertElement, IE->getType(), CI->getZExtValue());
6298         }
6299         LLVM_DEBUG(dbgs() << "SLP: Compensate cost of users by: " << UserCost
6300                           << ".\n");
6301         Cost -= UserCost;
6302       }
6303 
6304       MinCost = InstructionCost::min(MinCost, Cost);
6305 
6306       if (Cost.isValid() && Cost < -SLPCostThreshold) {
6307         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
6308         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
6309                                                     cast<Instruction>(Ops[0]))
6310                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
6311                                  << " and with tree size "
6312                                  << ore::NV("TreeSize", R.getTreeSize()));
6313 
6314         R.vectorizeTree();
6315         // Move to the next bundle.
6316         I += VF - 1;
6317         NextInst = I + 1;
6318         Changed = true;
6319       }
6320     }
6321   }
6322 
6323   if (!Changed && CandidateFound) {
6324     R.getORE()->emit([&]() {
6325       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
6326              << "List vectorization was possible but not beneficial with cost "
6327              << ore::NV("Cost", MinCost) << " >= "
6328              << ore::NV("Treshold", -SLPCostThreshold);
6329     });
6330   } else if (!Changed) {
6331     R.getORE()->emit([&]() {
6332       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
6333              << "Cannot SLP vectorize list: vectorization was impossible"
6334              << " with available vectorization factors";
6335     });
6336   }
6337   return Changed;
6338 }
6339 
6340 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
6341   if (!I)
6342     return false;
6343 
6344   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
6345     return false;
6346 
6347   Value *P = I->getParent();
6348 
6349   // Vectorize in current basic block only.
6350   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
6351   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
6352   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
6353     return false;
6354 
6355   // Try to vectorize V.
6356   if (tryToVectorizePair(Op0, Op1, R))
6357     return true;
6358 
6359   auto *A = dyn_cast<BinaryOperator>(Op0);
6360   auto *B = dyn_cast<BinaryOperator>(Op1);
6361   // Try to skip B.
6362   if (B && B->hasOneUse()) {
6363     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
6364     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
6365     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
6366       return true;
6367     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
6368       return true;
6369   }
6370 
6371   // Try to skip A.
6372   if (A && A->hasOneUse()) {
6373     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
6374     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
6375     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
6376       return true;
6377     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
6378       return true;
6379   }
6380   return false;
6381 }
6382 
6383 namespace {
6384 
6385 /// Model horizontal reductions.
6386 ///
6387 /// A horizontal reduction is a tree of reduction instructions that has values
6388 /// that can be put into a vector as its leaves. For example:
6389 ///
6390 /// mul mul mul mul
6391 ///  \  /    \  /
6392 ///   +       +
6393 ///    \     /
6394 ///       +
6395 /// This tree has "mul" as its leaf values and "+" as its reduction
6396 /// instructions. A reduction can feed into a store or a binary operation
6397 /// feeding a phi.
6398 ///    ...
6399 ///    \  /
6400 ///     +
6401 ///     |
6402 ///  phi +=
6403 ///
6404 ///  Or:
6405 ///    ...
6406 ///    \  /
6407 ///     +
6408 ///     |
6409 ///   *p =
6410 ///
6411 class HorizontalReduction {
6412   using ReductionOpsType = SmallVector<Value *, 16>;
6413   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
6414   ReductionOpsListType  ReductionOps;
6415   SmallVector<Value *, 32> ReducedVals;
6416   // Use map vector to make stable output.
6417   MapVector<Instruction *, Value *> ExtraArgs;
6418 
6419   /// Contains info about operation, like its opcode, left and right operands.
6420   class OperationData {
6421     /// Opcode of the instruction.
6422     unsigned Opcode = 0;
6423 
6424     /// Kind of the reduction operation.
6425     RecurKind Kind = RecurKind::None;
6426 
6427     /// Checks if the reduction operation can be vectorized.
6428     bool isVectorizable() const {
6429       switch (Kind) {
6430       case RecurKind::Add:
6431         return Opcode == Instruction::Add;
6432       case RecurKind::Mul:
6433         return Opcode == Instruction::Mul;
6434       case RecurKind::Or:
6435         return Opcode == Instruction::Or;
6436       case RecurKind::And:
6437         return Opcode == Instruction::And;
6438       case RecurKind::Xor:
6439         return Opcode == Instruction::Xor;
6440       case RecurKind::FAdd:
6441         return Opcode == Instruction::FAdd;
6442       case RecurKind::FMul:
6443         return Opcode == Instruction::FMul;
6444       case RecurKind::SMax:
6445       case RecurKind::SMin:
6446       case RecurKind::UMax:
6447       case RecurKind::UMin:
6448         return Opcode == Instruction::ICmp;
6449       default:
6450         return false;
6451       }
6452     }
6453 
6454     /// Creates reduction operation with the current opcode.
6455     Value *createOp(IRBuilder<> &Builder, Value *LHS, Value *RHS,
6456                     const Twine &Name) const {
6457       assert(isVectorizable() && "Unhandled reduction operation.");
6458       unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
6459       switch (Kind) {
6460       case RecurKind::Add:
6461       case RecurKind::Mul:
6462       case RecurKind::Or:
6463       case RecurKind::And:
6464       case RecurKind::Xor:
6465       case RecurKind::FAdd:
6466       case RecurKind::FMul:
6467         return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
6468                                    Name);
6469 
6470       case RecurKind::SMax: {
6471         Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
6472         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6473       }
6474       case RecurKind::SMin: {
6475         Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
6476         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6477       }
6478       case RecurKind::UMax: {
6479         Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
6480         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6481       }
6482       case RecurKind::UMin: {
6483         Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
6484         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6485       }
6486       default:
6487         llvm_unreachable("Unknown reduction operation.");
6488       }
6489     }
6490 
6491   public:
6492     explicit OperationData() = default;
6493 
6494     /// Construction for reduced values. They are identified by opcode only and
6495     /// don't have associated LHS/RHS values.
6496     explicit OperationData(Instruction &I) {
6497       Opcode = I.getOpcode();
6498     }
6499 
6500     /// Constructor for reduction operations with opcode and type.
6501     OperationData(unsigned Opcode, RecurKind RdxKind)
6502         : Opcode(Opcode), Kind(RdxKind) {
6503       assert(Kind != RecurKind::None && "Expected reduction operation.");
6504     }
6505 
6506     explicit operator bool() const { return Opcode; }
6507 
6508     /// Return true if this operation is any kind of minimum or maximum.
6509     bool isMinMax() const {
6510       assert(Kind != RecurKind::None && "Expected reduction operation.");
6511       return RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind);
6512     }
6513 
6514     /// Get the index of the first operand.
6515     unsigned getFirstOperandIndex() const {
6516       assert(!!*this && "The opcode is not set.");
6517       // We allow calling this before 'Kind' is set, so handle that specially.
6518       if (Kind == RecurKind::None)
6519         return 0;
6520       return isMinMax() ? 1 : 0;
6521     }
6522 
6523     /// Total number of operands in the reduction operation.
6524     unsigned getNumberOfOperands() const {
6525       assert(Kind != RecurKind::None && !!*this &&
6526              "Expected reduction operation.");
6527       return isMinMax() ? 3 : 2;
6528     }
6529 
6530     /// Checks if the instruction is in basic block \p BB.
6531     /// For a min/max reduction check that both compare and select are in \p BB.
6532     bool hasSameParent(Instruction *I, BasicBlock *BB, bool IsRedOp) const {
6533       assert(Kind != RecurKind::None && !!*this &&
6534              "Expected reduction operation.");
6535       if (IsRedOp && isMinMax()) {
6536         auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition());
6537         return I->getParent() == BB && Cmp && Cmp->getParent() == BB;
6538       }
6539       return I->getParent() == BB;
6540     }
6541 
6542     /// Expected number of uses for reduction operations/reduced values.
6543     bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const {
6544       assert(Kind != RecurKind::None && !!*this &&
6545              "Expected reduction operation.");
6546       // SelectInst must be used twice while the condition op must have single
6547       // use only.
6548       if (isMinMax())
6549         return I->hasNUses(2) &&
6550                (!IsReductionOp ||
6551                 cast<SelectInst>(I)->getCondition()->hasOneUse());
6552 
6553       // Arithmetic reduction operation must be used once only.
6554       return I->hasOneUse();
6555     }
6556 
6557     /// Initializes the list of reduction operations.
6558     void initReductionOps(ReductionOpsListType &ReductionOps) {
6559       assert(Kind != RecurKind::None && !!*this &&
6560              "Expected reduction operation.");
6561       if (isMinMax())
6562         ReductionOps.assign(2, ReductionOpsType());
6563       else
6564         ReductionOps.assign(1, ReductionOpsType());
6565     }
6566 
6567     /// Add all reduction operations for the reduction instruction \p I.
6568     void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) {
6569       assert(Kind != RecurKind::None && !!*this &&
6570              "Expected reduction operation.");
6571       if (isMinMax()) {
6572         ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
6573         ReductionOps[1].emplace_back(I);
6574       } else {
6575         ReductionOps[0].emplace_back(I);
6576       }
6577     }
6578 
6579     /// Checks if instruction is associative and can be vectorized.
6580     bool isAssociative(Instruction *I) const {
6581       assert(Kind != RecurKind::None && *this &&
6582              "Expected reduction operation.");
6583       if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind)) {
6584         assert(Opcode == Instruction::ICmp &&
6585                "Only integer compare operation is expected.");
6586         return true;
6587       }
6588       return I->isAssociative();
6589     }
6590 
6591     /// Checks if the reduction operation can be vectorized.
6592     bool isVectorizable(Instruction *I) const {
6593       return isVectorizable() && isAssociative(I);
6594     }
6595 
6596     /// Checks if two operation data are both a reduction op or both a reduced
6597     /// value.
6598     bool operator==(const OperationData &OD) const {
6599       assert(((Kind != OD.Kind) || (Opcode != 0 && OD.Opcode != 0)) &&
6600              "One of the comparing operations is incorrect.");
6601       return Kind == OD.Kind && Opcode == OD.Opcode;
6602     }
6603     bool operator!=(const OperationData &OD) const { return !(*this == OD); }
6604     void clear() {
6605       Opcode = 0;
6606       Kind = RecurKind::None;
6607     }
6608 
6609     /// Get the opcode of the reduction operation.
6610     unsigned getOpcode() const {
6611       assert(isVectorizable() && "Expected vectorizable operation.");
6612       return Opcode;
6613     }
6614 
6615     /// Get kind of reduction data.
6616     RecurKind getKind() const { return Kind; }
6617     Value *getLHS(Instruction *I) const {
6618       if (Kind == RecurKind::None)
6619         return nullptr;
6620       return I->getOperand(getFirstOperandIndex());
6621     }
6622     Value *getRHS(Instruction *I) const {
6623       if (Kind == RecurKind::None)
6624         return nullptr;
6625       return I->getOperand(getFirstOperandIndex() + 1);
6626     }
6627 
6628     /// Creates reduction operation with the current opcode with the IR flags
6629     /// from \p ReductionOps.
6630     Value *createOp(IRBuilder<> &Builder, Value *LHS, Value *RHS,
6631                     const Twine &Name,
6632                     const ReductionOpsListType &ReductionOps) const {
6633       assert(isVectorizable() &&
6634              "Expected add|fadd or min/max reduction operation.");
6635       Value *Op = createOp(Builder, LHS, RHS, Name);
6636       if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind)) {
6637         if (auto *Sel = dyn_cast<SelectInst>(Op))
6638           propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
6639         propagateIRFlags(Op, ReductionOps[1]);
6640         return Op;
6641       }
6642       propagateIRFlags(Op, ReductionOps[0]);
6643       return Op;
6644     }
6645     /// Creates reduction operation with the current opcode with the IR flags
6646     /// from \p I.
6647     Value *createOp(IRBuilder<> &Builder, Value *LHS, Value *RHS,
6648                     const Twine &Name, Instruction *I) const {
6649       assert(isVectorizable() &&
6650              "Expected add|fadd or min/max reduction operation.");
6651       Value *Op = createOp(Builder, LHS, RHS, Name);
6652       if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind)) {
6653         if (auto *Sel = dyn_cast<SelectInst>(Op)) {
6654           propagateIRFlags(Sel->getCondition(),
6655                            cast<SelectInst>(I)->getCondition());
6656         }
6657       }
6658       propagateIRFlags(Op, I);
6659       return Op;
6660     }
6661   };
6662 
6663   WeakTrackingVH ReductionRoot;
6664 
6665   /// The operation data of the reduction operation.
6666   OperationData RdxTreeInst;
6667 
6668   /// The operation data for the leaf values that we perform a reduction on.
6669   OperationData RdxLeafVal;
6670 
6671   /// Checks if the ParentStackElem.first should be marked as a reduction
6672   /// operation with an extra argument or as extra argument itself.
6673   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
6674                     Value *ExtraArg) {
6675     if (ExtraArgs.count(ParentStackElem.first)) {
6676       ExtraArgs[ParentStackElem.first] = nullptr;
6677       // We ran into something like:
6678       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
6679       // The whole ParentStackElem.first should be considered as an extra value
6680       // in this case.
6681       // Do not perform analysis of remaining operands of ParentStackElem.first
6682       // instruction, this whole instruction is an extra argument.
6683       OperationData OpData = getOperationData(ParentStackElem.first);
6684       ParentStackElem.second = OpData.getNumberOfOperands();
6685     } else {
6686       // We ran into something like:
6687       // ParentStackElem.first += ... + ExtraArg + ...
6688       ExtraArgs[ParentStackElem.first] = ExtraArg;
6689     }
6690   }
6691 
6692   static OperationData getOperationData(Instruction *I) {
6693     if (!I)
6694       return OperationData();
6695 
6696     TargetTransformInfo::ReductionFlags RdxFlags;
6697     if (match(I, m_Add(m_Value(), m_Value())))
6698       return OperationData(I->getOpcode(), RecurKind::Add);
6699     if (match(I, m_Mul(m_Value(), m_Value())))
6700       return OperationData(I->getOpcode(), RecurKind::Mul);
6701     if (match(I, m_And(m_Value(), m_Value())))
6702       return OperationData(I->getOpcode(), RecurKind::And);
6703     if (match(I, m_Or(m_Value(), m_Value())))
6704       return OperationData(I->getOpcode(), RecurKind::Or);
6705     if (match(I, m_Xor(m_Value(), m_Value())))
6706       return OperationData(I->getOpcode(), RecurKind::Xor);
6707     if (match(I, m_FAdd(m_Value(), m_Value())))
6708       return OperationData(I->getOpcode(), RecurKind::FAdd);
6709     if (match(I, m_FMul(m_Value(), m_Value())))
6710       return OperationData(I->getOpcode(), RecurKind::FMul);
6711 
6712     if (match(I, m_SMax(m_Value(), m_Value())))
6713       return OperationData(Instruction::ICmp, RecurKind::SMax);
6714     if (match(I, m_SMin(m_Value(), m_Value())))
6715       return OperationData(Instruction::ICmp, RecurKind::SMin);
6716     if (match(I, m_UMax(m_Value(), m_Value())))
6717       return OperationData(Instruction::ICmp, RecurKind::UMax);
6718     if (match(I, m_UMin(m_Value(), m_Value())))
6719       return OperationData(Instruction::ICmp, RecurKind::UMin);
6720 
6721     if (auto *Select = dyn_cast<SelectInst>(I)) {
6722       // Try harder: look for min/max pattern based on instructions producing
6723       // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
6724       // During the intermediate stages of SLP, it's very common to have
6725       // pattern like this (since optimizeGatherSequence is run only once
6726       // at the end):
6727       // %1 = extractelement <2 x i32> %a, i32 0
6728       // %2 = extractelement <2 x i32> %a, i32 1
6729       // %cond = icmp sgt i32 %1, %2
6730       // %3 = extractelement <2 x i32> %a, i32 0
6731       // %4 = extractelement <2 x i32> %a, i32 1
6732       // %select = select i1 %cond, i32 %3, i32 %4
6733       CmpInst::Predicate Pred;
6734       Instruction *L1;
6735       Instruction *L2;
6736 
6737       Value *LHS = Select->getTrueValue();
6738       Value *RHS = Select->getFalseValue();
6739       Value *Cond = Select->getCondition();
6740 
6741       // TODO: Support inverse predicates.
6742       if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
6743         if (!isa<ExtractElementInst>(RHS) ||
6744             !L2->isIdenticalTo(cast<Instruction>(RHS)))
6745           return OperationData(*I);
6746       } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
6747         if (!isa<ExtractElementInst>(LHS) ||
6748             !L1->isIdenticalTo(cast<Instruction>(LHS)))
6749           return OperationData(*I);
6750       } else {
6751         if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
6752           return OperationData(*I);
6753         if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
6754             !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
6755             !L2->isIdenticalTo(cast<Instruction>(RHS)))
6756           return OperationData(*I);
6757       }
6758 
6759       TargetTransformInfo::ReductionFlags RdxFlags;
6760       switch (Pred) {
6761       default:
6762         return OperationData(*I);
6763       case CmpInst::ICMP_SGT:
6764       case CmpInst::ICMP_SGE:
6765         return OperationData(Instruction::ICmp, RecurKind::SMax);
6766       case CmpInst::ICMP_SLT:
6767       case CmpInst::ICMP_SLE:
6768         return OperationData(Instruction::ICmp, RecurKind::SMin);
6769       case CmpInst::ICMP_UGT:
6770       case CmpInst::ICMP_UGE:
6771         return OperationData(Instruction::ICmp, RecurKind::UMax);
6772       case CmpInst::ICMP_ULT:
6773       case CmpInst::ICMP_ULE:
6774         return OperationData(Instruction::ICmp, RecurKind::UMin);
6775       }
6776     }
6777     return OperationData(*I);
6778   }
6779 
6780 public:
6781   HorizontalReduction() = default;
6782 
6783   /// Try to find a reduction tree.
6784   bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
6785     assert((!Phi || is_contained(Phi->operands(), B)) &&
6786            "Thi phi needs to use the binary operator");
6787 
6788     RdxTreeInst = getOperationData(B);
6789 
6790     // We could have a initial reductions that is not an add.
6791     //  r *= v1 + v2 + v3 + v4
6792     // In such a case start looking for a tree rooted in the first '+'.
6793     if (Phi) {
6794       if (RdxTreeInst.getLHS(B) == Phi) {
6795         Phi = nullptr;
6796         B = dyn_cast<Instruction>(RdxTreeInst.getRHS(B));
6797         RdxTreeInst = getOperationData(B);
6798       } else if (RdxTreeInst.getRHS(B) == Phi) {
6799         Phi = nullptr;
6800         B = dyn_cast<Instruction>(RdxTreeInst.getLHS(B));
6801         RdxTreeInst = getOperationData(B);
6802       }
6803     }
6804 
6805     if (!RdxTreeInst.isVectorizable(B))
6806       return false;
6807 
6808     Type *Ty = B->getType();
6809     if (!isValidElementType(Ty))
6810       return false;
6811     if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy())
6812       return false;
6813 
6814     RdxLeafVal.clear();
6815     ReductionRoot = B;
6816 
6817     // Post order traverse the reduction tree starting at B. We only handle true
6818     // trees containing only binary operators.
6819     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
6820     Stack.push_back(std::make_pair(B, RdxTreeInst.getFirstOperandIndex()));
6821     RdxTreeInst.initReductionOps(ReductionOps);
6822     while (!Stack.empty()) {
6823       Instruction *TreeN = Stack.back().first;
6824       unsigned EdgeToVisit = Stack.back().second++;
6825       OperationData OpData = getOperationData(TreeN);
6826       bool IsReducedValue = OpData != RdxTreeInst;
6827 
6828       // Postorder vist.
6829       if (IsReducedValue || EdgeToVisit == OpData.getNumberOfOperands()) {
6830         if (IsReducedValue)
6831           ReducedVals.push_back(TreeN);
6832         else {
6833           auto I = ExtraArgs.find(TreeN);
6834           if (I != ExtraArgs.end() && !I->second) {
6835             // Check if TreeN is an extra argument of its parent operation.
6836             if (Stack.size() <= 1) {
6837               // TreeN can't be an extra argument as it is a root reduction
6838               // operation.
6839               return false;
6840             }
6841             // Yes, TreeN is an extra argument, do not add it to a list of
6842             // reduction operations.
6843             // Stack[Stack.size() - 2] always points to the parent operation.
6844             markExtraArg(Stack[Stack.size() - 2], TreeN);
6845             ExtraArgs.erase(TreeN);
6846           } else
6847             RdxTreeInst.addReductionOps(TreeN, ReductionOps);
6848         }
6849         // Retract.
6850         Stack.pop_back();
6851         continue;
6852       }
6853 
6854       // Visit left or right.
6855       Value *NextV = TreeN->getOperand(EdgeToVisit);
6856       if (NextV != Phi) {
6857         auto *I = dyn_cast<Instruction>(NextV);
6858         OpData = getOperationData(I);
6859         // Continue analysis if the next operand is a reduction operation or
6860         // (possibly) a reduced value. If the reduced value opcode is not set,
6861         // the first met operation != reduction operation is considered as the
6862         // reduced value class.
6863         const bool IsRdxInst = OpData == RdxTreeInst;
6864         if (I && (!RdxLeafVal || OpData == RdxLeafVal || IsRdxInst)) {
6865           // Only handle trees in the current basic block.
6866           if (!RdxTreeInst.hasSameParent(I, B->getParent(), IsRdxInst)) {
6867             // I is an extra argument for TreeN (its parent operation).
6868             markExtraArg(Stack.back(), I);
6869             continue;
6870           }
6871 
6872           // Each tree node needs to have minimal number of users except for the
6873           // ultimate reduction.
6874           if (!RdxTreeInst.hasRequiredNumberOfUses(I, IsRdxInst) && I != B) {
6875             // I is an extra argument for TreeN (its parent operation).
6876             markExtraArg(Stack.back(), I);
6877             continue;
6878           }
6879 
6880           if (IsRdxInst) {
6881             // We need to be able to reassociate the reduction operations.
6882             if (!OpData.isAssociative(I)) {
6883               // I is an extra argument for TreeN (its parent operation).
6884               markExtraArg(Stack.back(), I);
6885               continue;
6886             }
6887           } else if (RdxLeafVal && RdxLeafVal != OpData) {
6888             // Make sure that the opcodes of the operations that we are going to
6889             // reduce match.
6890             // I is an extra argument for TreeN (its parent operation).
6891             markExtraArg(Stack.back(), I);
6892             continue;
6893           } else if (!RdxLeafVal) {
6894             RdxLeafVal = OpData;
6895           }
6896           Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
6897           continue;
6898         }
6899       }
6900       // NextV is an extra argument for TreeN (its parent operation).
6901       markExtraArg(Stack.back(), NextV);
6902     }
6903     return true;
6904   }
6905 
6906   /// Attempt to vectorize the tree found by matchAssociativeReduction.
6907   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
6908     // If there are a sufficient number of reduction values, reduce
6909     // to a nearby power-of-2. We can safely generate oversized
6910     // vectors and rely on the backend to split them to legal sizes.
6911     unsigned NumReducedVals = ReducedVals.size();
6912     if (NumReducedVals < 4)
6913       return false;
6914 
6915     // FIXME: Fast-math-flags should be set based on the instructions in the
6916     //        reduction (not all of 'fast' are required).
6917     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
6918     FastMathFlags Unsafe;
6919     Unsafe.setFast();
6920     Builder.setFastMathFlags(Unsafe);
6921 
6922     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
6923     // The same extra argument may be used several times, so log each attempt
6924     // to use it.
6925     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
6926       assert(Pair.first && "DebugLoc must be set.");
6927       ExternallyUsedValues[Pair.second].push_back(Pair.first);
6928     }
6929 
6930     // The compare instruction of a min/max is the insertion point for new
6931     // instructions and may be replaced with a new compare instruction.
6932     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
6933       assert(isa<SelectInst>(RdxRootInst) &&
6934              "Expected min/max reduction to have select root instruction");
6935       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
6936       assert(isa<Instruction>(ScalarCond) &&
6937              "Expected min/max reduction to have compare condition");
6938       return cast<Instruction>(ScalarCond);
6939     };
6940 
6941     // The reduction root is used as the insertion point for new instructions,
6942     // so set it as externally used to prevent it from being deleted.
6943     ExternallyUsedValues[ReductionRoot];
6944     SmallVector<Value *, 16> IgnoreList;
6945     for (ReductionOpsType &RdxOp : ReductionOps)
6946       IgnoreList.append(RdxOp.begin(), RdxOp.end());
6947 
6948     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
6949     if (NumReducedVals > ReduxWidth) {
6950       // In the loop below, we are building a tree based on a window of
6951       // 'ReduxWidth' values.
6952       // If the operands of those values have common traits (compare predicate,
6953       // constant operand, etc), then we want to group those together to
6954       // minimize the cost of the reduction.
6955 
6956       // TODO: This should be extended to count common operands for
6957       //       compares and binops.
6958 
6959       // Step 1: Count the number of times each compare predicate occurs.
6960       SmallDenseMap<unsigned, unsigned> PredCountMap;
6961       for (Value *RdxVal : ReducedVals) {
6962         CmpInst::Predicate Pred;
6963         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
6964           ++PredCountMap[Pred];
6965       }
6966       // Step 2: Sort the values so the most common predicates come first.
6967       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
6968         CmpInst::Predicate PredA, PredB;
6969         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
6970             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
6971           return PredCountMap[PredA] > PredCountMap[PredB];
6972         }
6973         return false;
6974       });
6975     }
6976 
6977     Value *VectorizedTree = nullptr;
6978     unsigned i = 0;
6979     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
6980       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
6981       V.buildTree(VL, ExternallyUsedValues, IgnoreList);
6982       Optional<ArrayRef<unsigned>> Order = V.bestOrder();
6983       if (Order) {
6984         assert(Order->size() == VL.size() &&
6985                "Order size must be the same as number of vectorized "
6986                "instructions.");
6987         // TODO: reorder tree nodes without tree rebuilding.
6988         SmallVector<Value *, 4> ReorderedOps(VL.size());
6989         llvm::transform(*Order, ReorderedOps.begin(),
6990                         [VL](const unsigned Idx) { return VL[Idx]; });
6991         V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
6992       }
6993       if (V.isTreeTinyAndNotFullyVectorizable())
6994         break;
6995       if (V.isLoadCombineReductionCandidate(RdxTreeInst.getKind()))
6996         break;
6997 
6998       V.computeMinimumValueSizes();
6999 
7000       // Estimate cost.
7001       InstructionCost TreeCost = V.getTreeCost();
7002       InstructionCost ReductionCost =
7003           getReductionCost(TTI, ReducedVals[i], ReduxWidth);
7004       InstructionCost Cost = TreeCost + ReductionCost;
7005       if (!Cost.isValid()) {
7006         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
7007         return false;
7008       }
7009       if (Cost >= -SLPCostThreshold) {
7010         V.getORE()->emit([&]() {
7011           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
7012                                           cast<Instruction>(VL[0]))
7013                  << "Vectorizing horizontal reduction is possible"
7014                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
7015                  << " and threshold "
7016                  << ore::NV("Threshold", -SLPCostThreshold);
7017         });
7018         break;
7019       }
7020 
7021       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
7022                         << Cost << ". (HorRdx)\n");
7023       V.getORE()->emit([&]() {
7024         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
7025                                   cast<Instruction>(VL[0]))
7026                << "Vectorized horizontal reduction with cost "
7027                << ore::NV("Cost", Cost) << " and with tree size "
7028                << ore::NV("TreeSize", V.getTreeSize());
7029       });
7030 
7031       // Vectorize a tree.
7032       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
7033       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
7034 
7035       // Emit a reduction. For min/max, the root is a select, but the insertion
7036       // point is the compare condition of that select.
7037       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
7038       if (RdxTreeInst.isMinMax())
7039         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
7040       else
7041         Builder.SetInsertPoint(RdxRootInst);
7042 
7043       Value *ReducedSubTree =
7044           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
7045 
7046       if (!VectorizedTree) {
7047         // Initialize the final value in the reduction.
7048         VectorizedTree = ReducedSubTree;
7049       } else {
7050         // Update the final value in the reduction.
7051         Builder.SetCurrentDebugLocation(Loc);
7052         VectorizedTree = RdxTreeInst.createOp(
7053             Builder, VectorizedTree, ReducedSubTree, "op.rdx", ReductionOps);
7054       }
7055       i += ReduxWidth;
7056       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
7057     }
7058 
7059     if (VectorizedTree) {
7060       // Finish the reduction.
7061       for (; i < NumReducedVals; ++i) {
7062         auto *I = cast<Instruction>(ReducedVals[i]);
7063         Builder.SetCurrentDebugLocation(I->getDebugLoc());
7064         VectorizedTree = RdxTreeInst.createOp(Builder, VectorizedTree, I, "",
7065                                               ReductionOps);
7066       }
7067       for (auto &Pair : ExternallyUsedValues) {
7068         // Add each externally used value to the final reduction.
7069         for (auto *I : Pair.second) {
7070           Builder.SetCurrentDebugLocation(I->getDebugLoc());
7071           VectorizedTree = RdxTreeInst.createOp(Builder, VectorizedTree,
7072                                                 Pair.first, "op.extra", I);
7073         }
7074       }
7075 
7076       // Update users. For a min/max reduction that ends with a compare and
7077       // select, we also have to RAUW for the compare instruction feeding the
7078       // reduction root. That's because the original compare may have extra uses
7079       // besides the final select of the reduction.
7080       if (RdxTreeInst.isMinMax()) {
7081         if (auto *VecSelect = dyn_cast<SelectInst>(VectorizedTree)) {
7082           Instruction *ScalarCmp =
7083               getCmpForMinMaxReduction(cast<Instruction>(ReductionRoot));
7084           ScalarCmp->replaceAllUsesWith(VecSelect->getCondition());
7085         }
7086       }
7087       ReductionRoot->replaceAllUsesWith(VectorizedTree);
7088 
7089       // Mark all scalar reduction ops for deletion, they are replaced by the
7090       // vector reductions.
7091       V.eraseInstructions(IgnoreList);
7092     }
7093     return VectorizedTree != nullptr;
7094   }
7095 
7096   unsigned numReductionValues() const {
7097     return ReducedVals.size();
7098   }
7099 
7100 private:
7101   /// Calculate the cost of a reduction.
7102   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
7103                        unsigned ReduxWidth) {
7104     Type *ScalarTy = FirstReducedVal->getType();
7105     auto *VecTy = FixedVectorType::get(ScalarTy, ReduxWidth);
7106 
7107     RecurKind Kind = RdxTreeInst.getKind();
7108     unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
7109     int SplittingRdxCost;
7110     int ScalarReduxCost;
7111     switch (Kind) {
7112     case RecurKind::Add:
7113     case RecurKind::Mul:
7114     case RecurKind::Or:
7115     case RecurKind::And:
7116     case RecurKind::Xor:
7117     case RecurKind::FAdd:
7118     case RecurKind::FMul:
7119       SplittingRdxCost = TTI->getArithmeticReductionCost(
7120           RdxOpcode, VecTy, /*IsPairwiseForm=*/false);
7121       ScalarReduxCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy);
7122       break;
7123     case RecurKind::SMax:
7124     case RecurKind::SMin:
7125     case RecurKind::UMax:
7126     case RecurKind::UMin: {
7127       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VecTy));
7128       bool IsUnsigned = Kind == RecurKind::UMax || Kind == RecurKind::UMin;
7129       SplittingRdxCost =
7130           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
7131                                       /*IsPairwiseForm=*/false, IsUnsigned);
7132       ScalarReduxCost =
7133           TTI->getCmpSelInstrCost(RdxOpcode, ScalarTy) +
7134           TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
7135                                   CmpInst::makeCmpResultType(ScalarTy));
7136       break;
7137     }
7138     default:
7139       llvm_unreachable("Expected arithmetic or min/max reduction operation");
7140     }
7141 
7142     ScalarReduxCost *= (ReduxWidth - 1);
7143     LLVM_DEBUG(dbgs() << "SLP: Adding cost "
7144                       << SplittingRdxCost - ScalarReduxCost
7145                       << " for reduction that starts with " << *FirstReducedVal
7146                       << " (It is a splitting reduction)\n");
7147     return SplittingRdxCost - ScalarReduxCost;
7148   }
7149 
7150   /// Emit a horizontal reduction of the vectorized value.
7151   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
7152                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
7153     assert(VectorizedValue && "Need to have a vectorized tree node");
7154     assert(isPowerOf2_32(ReduxWidth) &&
7155            "We only handle power-of-two reductions for now");
7156 
7157     // FIXME: The builder should use an FMF guard. It should not be hard-coded
7158     //        to 'fast'.
7159     assert(Builder.getFastMathFlags().isFast() && "Expected 'fast' FMF");
7160     return createSimpleTargetReduction(Builder, TTI, VectorizedValue,
7161                                        RdxTreeInst.getKind(),
7162                                        ReductionOps.back());
7163   }
7164 };
7165 
7166 } // end anonymous namespace
7167 
7168 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
7169   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
7170     return cast<FixedVectorType>(IE->getType())->getNumElements();
7171 
7172   unsigned AggregateSize = 1;
7173   auto *IV = cast<InsertValueInst>(InsertInst);
7174   Type *CurrentType = IV->getType();
7175   do {
7176     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
7177       for (auto *Elt : ST->elements())
7178         if (Elt != ST->getElementType(0)) // check homogeneity
7179           return None;
7180       AggregateSize *= ST->getNumElements();
7181       CurrentType = ST->getElementType(0);
7182     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
7183       AggregateSize *= AT->getNumElements();
7184       CurrentType = AT->getElementType();
7185     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
7186       AggregateSize *= VT->getNumElements();
7187       return AggregateSize;
7188     } else if (CurrentType->isSingleValueType()) {
7189       return AggregateSize;
7190     } else {
7191       return None;
7192     }
7193   } while (true);
7194 }
7195 
7196 static Optional<unsigned> getOperandIndex(Instruction *InsertInst,
7197                                           unsigned OperandOffset) {
7198   unsigned OperandIndex = OperandOffset;
7199   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
7200     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
7201       auto *VT = cast<FixedVectorType>(IE->getType());
7202       OperandIndex *= VT->getNumElements();
7203       OperandIndex += CI->getZExtValue();
7204       return OperandIndex;
7205     }
7206     return None;
7207   }
7208 
7209   auto *IV = cast<InsertValueInst>(InsertInst);
7210   Type *CurrentType = IV->getType();
7211   for (unsigned int Index : IV->indices()) {
7212     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
7213       OperandIndex *= ST->getNumElements();
7214       CurrentType = ST->getElementType(Index);
7215     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
7216       OperandIndex *= AT->getNumElements();
7217       CurrentType = AT->getElementType();
7218     } else {
7219       return None;
7220     }
7221     OperandIndex += Index;
7222   }
7223   return OperandIndex;
7224 }
7225 
7226 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
7227                                    TargetTransformInfo *TTI,
7228                                    SmallVectorImpl<Value *> &BuildVectorOpds,
7229                                    SmallVectorImpl<Value *> &InsertElts,
7230                                    unsigned OperandOffset) {
7231   do {
7232     Value *InsertedOperand = LastInsertInst->getOperand(1);
7233     Optional<unsigned> OperandIndex =
7234         getOperandIndex(LastInsertInst, OperandOffset);
7235     if (!OperandIndex)
7236       return false;
7237     if (isa<InsertElementInst>(InsertedOperand) ||
7238         isa<InsertValueInst>(InsertedOperand)) {
7239       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
7240                                   BuildVectorOpds, InsertElts, *OperandIndex))
7241         return false;
7242     } else {
7243       BuildVectorOpds[*OperandIndex] = InsertedOperand;
7244       InsertElts[*OperandIndex] = LastInsertInst;
7245     }
7246     if (isa<UndefValue>(LastInsertInst->getOperand(0)))
7247       return true;
7248     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
7249   } while (LastInsertInst != nullptr &&
7250            (isa<InsertValueInst>(LastInsertInst) ||
7251             isa<InsertElementInst>(LastInsertInst)) &&
7252            LastInsertInst->hasOneUse());
7253   return false;
7254 }
7255 
7256 /// Recognize construction of vectors like
7257 ///  %ra = insertelement <4 x float> poison, float %s0, i32 0
7258 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
7259 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
7260 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
7261 ///  starting from the last insertelement or insertvalue instruction.
7262 ///
7263 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
7264 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
7265 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
7266 ///
7267 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
7268 ///
7269 /// \return true if it matches.
7270 static bool findBuildAggregate(Instruction *LastInsertInst,
7271                                TargetTransformInfo *TTI,
7272                                SmallVectorImpl<Value *> &BuildVectorOpds,
7273                                SmallVectorImpl<Value *> &InsertElts) {
7274 
7275   assert((isa<InsertElementInst>(LastInsertInst) ||
7276           isa<InsertValueInst>(LastInsertInst)) &&
7277          "Expected insertelement or insertvalue instruction!");
7278 
7279   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
7280          "Expected empty result vectors!");
7281 
7282   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
7283   if (!AggregateSize)
7284     return false;
7285   BuildVectorOpds.resize(*AggregateSize);
7286   InsertElts.resize(*AggregateSize);
7287 
7288   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
7289                              0)) {
7290     llvm::erase_value(BuildVectorOpds, nullptr);
7291     llvm::erase_value(InsertElts, nullptr);
7292     if (BuildVectorOpds.size() >= 2)
7293       return true;
7294   }
7295 
7296   return false;
7297 }
7298 
7299 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
7300   return V->getType() < V2->getType();
7301 }
7302 
7303 /// Try and get a reduction value from a phi node.
7304 ///
7305 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
7306 /// if they come from either \p ParentBB or a containing loop latch.
7307 ///
7308 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
7309 /// if not possible.
7310 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
7311                                 BasicBlock *ParentBB, LoopInfo *LI) {
7312   // There are situations where the reduction value is not dominated by the
7313   // reduction phi. Vectorizing such cases has been reported to cause
7314   // miscompiles. See PR25787.
7315   auto DominatedReduxValue = [&](Value *R) {
7316     return isa<Instruction>(R) &&
7317            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
7318   };
7319 
7320   Value *Rdx = nullptr;
7321 
7322   // Return the incoming value if it comes from the same BB as the phi node.
7323   if (P->getIncomingBlock(0) == ParentBB) {
7324     Rdx = P->getIncomingValue(0);
7325   } else if (P->getIncomingBlock(1) == ParentBB) {
7326     Rdx = P->getIncomingValue(1);
7327   }
7328 
7329   if (Rdx && DominatedReduxValue(Rdx))
7330     return Rdx;
7331 
7332   // Otherwise, check whether we have a loop latch to look at.
7333   Loop *BBL = LI->getLoopFor(ParentBB);
7334   if (!BBL)
7335     return nullptr;
7336   BasicBlock *BBLatch = BBL->getLoopLatch();
7337   if (!BBLatch)
7338     return nullptr;
7339 
7340   // There is a loop latch, return the incoming value if it comes from
7341   // that. This reduction pattern occasionally turns up.
7342   if (P->getIncomingBlock(0) == BBLatch) {
7343     Rdx = P->getIncomingValue(0);
7344   } else if (P->getIncomingBlock(1) == BBLatch) {
7345     Rdx = P->getIncomingValue(1);
7346   }
7347 
7348   if (Rdx && DominatedReduxValue(Rdx))
7349     return Rdx;
7350 
7351   return nullptr;
7352 }
7353 
7354 /// Attempt to reduce a horizontal reduction.
7355 /// If it is legal to match a horizontal reduction feeding the phi node \a P
7356 /// with reduction operators \a Root (or one of its operands) in a basic block
7357 /// \a BB, then check if it can be done. If horizontal reduction is not found
7358 /// and root instruction is a binary operation, vectorization of the operands is
7359 /// attempted.
7360 /// \returns true if a horizontal reduction was matched and reduced or operands
7361 /// of one of the binary instruction were vectorized.
7362 /// \returns false if a horizontal reduction was not matched (or not possible)
7363 /// or no vectorization of any binary operation feeding \a Root instruction was
7364 /// performed.
7365 static bool tryToVectorizeHorReductionOrInstOperands(
7366     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
7367     TargetTransformInfo *TTI,
7368     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
7369   if (!ShouldVectorizeHor)
7370     return false;
7371 
7372   if (!Root)
7373     return false;
7374 
7375   if (Root->getParent() != BB || isa<PHINode>(Root))
7376     return false;
7377   // Start analysis starting from Root instruction. If horizontal reduction is
7378   // found, try to vectorize it. If it is not a horizontal reduction or
7379   // vectorization is not possible or not effective, and currently analyzed
7380   // instruction is a binary operation, try to vectorize the operands, using
7381   // pre-order DFS traversal order. If the operands were not vectorized, repeat
7382   // the same procedure considering each operand as a possible root of the
7383   // horizontal reduction.
7384   // Interrupt the process if the Root instruction itself was vectorized or all
7385   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
7386   SmallVector<std::pair<Instruction *, unsigned>, 8> Stack(1, {Root, 0});
7387   SmallPtrSet<Value *, 8> VisitedInstrs;
7388   bool Res = false;
7389   while (!Stack.empty()) {
7390     Instruction *Inst;
7391     unsigned Level;
7392     std::tie(Inst, Level) = Stack.pop_back_val();
7393     Value *B0, *B1;
7394     bool IsBinop = match(Inst, m_BinOp(m_Value(B0), m_Value(B1)));
7395     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
7396     if (IsBinop || IsSelect) {
7397       HorizontalReduction HorRdx;
7398       if (HorRdx.matchAssociativeReduction(P, Inst)) {
7399         if (HorRdx.tryToReduce(R, TTI)) {
7400           Res = true;
7401           // Set P to nullptr to avoid re-analysis of phi node in
7402           // matchAssociativeReduction function unless this is the root node.
7403           P = nullptr;
7404           continue;
7405         }
7406       }
7407       if (P && IsBinop) {
7408         Inst = dyn_cast<Instruction>(B0);
7409         if (Inst == P)
7410           Inst = dyn_cast<Instruction>(B1);
7411         if (!Inst) {
7412           // Set P to nullptr to avoid re-analysis of phi node in
7413           // matchAssociativeReduction function unless this is the root node.
7414           P = nullptr;
7415           continue;
7416         }
7417       }
7418     }
7419     // Set P to nullptr to avoid re-analysis of phi node in
7420     // matchAssociativeReduction function unless this is the root node.
7421     P = nullptr;
7422     if (Vectorize(Inst, R)) {
7423       Res = true;
7424       continue;
7425     }
7426 
7427     // Try to vectorize operands.
7428     // Continue analysis for the instruction from the same basic block only to
7429     // save compile time.
7430     if (++Level < RecursionMaxDepth)
7431       for (auto *Op : Inst->operand_values())
7432         if (VisitedInstrs.insert(Op).second)
7433           if (auto *I = dyn_cast<Instruction>(Op))
7434             if (!isa<PHINode>(I) && !R.isDeleted(I) && I->getParent() == BB)
7435               Stack.emplace_back(I, Level);
7436   }
7437   return Res;
7438 }
7439 
7440 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
7441                                                  BasicBlock *BB, BoUpSLP &R,
7442                                                  TargetTransformInfo *TTI) {
7443   auto *I = dyn_cast_or_null<Instruction>(V);
7444   if (!I)
7445     return false;
7446 
7447   if (!isa<BinaryOperator>(I))
7448     P = nullptr;
7449   // Try to match and vectorize a horizontal reduction.
7450   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
7451     return tryToVectorize(I, R);
7452   };
7453   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
7454                                                   ExtraVectorization);
7455 }
7456 
7457 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
7458                                                  BasicBlock *BB, BoUpSLP &R) {
7459   const DataLayout &DL = BB->getModule()->getDataLayout();
7460   if (!R.canMapToVector(IVI->getType(), DL))
7461     return false;
7462 
7463   SmallVector<Value *, 16> BuildVectorOpds;
7464   SmallVector<Value *, 16> BuildVectorInsts;
7465   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
7466     return false;
7467 
7468   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
7469   // Aggregate value is unlikely to be processed in vector register, we need to
7470   // extract scalars into scalar registers, so NeedExtraction is set true.
7471   return tryToVectorizeList(BuildVectorOpds, R, /*AllowReorder=*/false,
7472                             BuildVectorInsts);
7473 }
7474 
7475 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
7476                                                    BasicBlock *BB, BoUpSLP &R) {
7477   SmallVector<Value *, 16> BuildVectorInsts;
7478   SmallVector<Value *, 16> BuildVectorOpds;
7479   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
7480       (llvm::all_of(BuildVectorOpds,
7481                     [](Value *V) { return isa<ExtractElementInst>(V); }) &&
7482        isShuffle(BuildVectorOpds)))
7483     return false;
7484 
7485   // Vectorize starting with the build vector operands ignoring the BuildVector
7486   // instructions for the purpose of scheduling and user extraction.
7487   return tryToVectorizeList(BuildVectorOpds, R, /*AllowReorder=*/false,
7488                             BuildVectorInsts);
7489 }
7490 
7491 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
7492                                          BoUpSLP &R) {
7493   if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
7494     return true;
7495 
7496   bool OpsChanged = false;
7497   for (int Idx = 0; Idx < 2; ++Idx) {
7498     OpsChanged |=
7499         vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
7500   }
7501   return OpsChanged;
7502 }
7503 
7504 bool SLPVectorizerPass::vectorizeSimpleInstructions(
7505     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R) {
7506   bool OpsChanged = false;
7507   for (auto *I : reverse(Instructions)) {
7508     if (R.isDeleted(I))
7509       continue;
7510     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
7511       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
7512     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
7513       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
7514     else if (auto *CI = dyn_cast<CmpInst>(I))
7515       OpsChanged |= vectorizeCmpInst(CI, BB, R);
7516   }
7517   Instructions.clear();
7518   return OpsChanged;
7519 }
7520 
7521 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
7522   bool Changed = false;
7523   SmallVector<Value *, 4> Incoming;
7524   SmallPtrSet<Value *, 16> VisitedInstrs;
7525 
7526   bool HaveVectorizedPhiNodes = true;
7527   while (HaveVectorizedPhiNodes) {
7528     HaveVectorizedPhiNodes = false;
7529 
7530     // Collect the incoming values from the PHIs.
7531     Incoming.clear();
7532     for (Instruction &I : *BB) {
7533       PHINode *P = dyn_cast<PHINode>(&I);
7534       if (!P)
7535         break;
7536 
7537       if (!VisitedInstrs.count(P) && !R.isDeleted(P))
7538         Incoming.push_back(P);
7539     }
7540 
7541     // Sort by type.
7542     llvm::stable_sort(Incoming, PhiTypeSorterFunc);
7543 
7544     // Try to vectorize elements base on their type.
7545     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
7546                                            E = Incoming.end();
7547          IncIt != E;) {
7548 
7549       // Look for the next elements with the same type.
7550       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
7551       while (SameTypeIt != E &&
7552              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
7553         VisitedInstrs.insert(*SameTypeIt);
7554         ++SameTypeIt;
7555       }
7556 
7557       // Try to vectorize them.
7558       unsigned NumElts = (SameTypeIt - IncIt);
7559       LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("
7560                         << NumElts << ")\n");
7561       // The order in which the phi nodes appear in the program does not matter.
7562       // So allow tryToVectorizeList to reorder them if it is beneficial. This
7563       // is done when there are exactly two elements since tryToVectorizeList
7564       // asserts that there are only two values when AllowReorder is true.
7565       bool AllowReorder = NumElts == 2;
7566       if (NumElts > 1 &&
7567           tryToVectorizeList(makeArrayRef(IncIt, NumElts), R, AllowReorder)) {
7568         // Success start over because instructions might have been changed.
7569         HaveVectorizedPhiNodes = true;
7570         Changed = true;
7571         break;
7572       }
7573 
7574       // Start over at the next instruction of a different type (or the end).
7575       IncIt = SameTypeIt;
7576     }
7577   }
7578 
7579   VisitedInstrs.clear();
7580 
7581   SmallVector<Instruction *, 8> PostProcessInstructions;
7582   SmallDenseSet<Instruction *, 4> KeyNodes;
7583   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
7584     // Skip instructions with scalable type. The num of elements is unknown at
7585     // compile-time for scalable type.
7586     if (isa<ScalableVectorType>(it->getType()))
7587       continue;
7588 
7589     // Skip instructions marked for the deletion.
7590     if (R.isDeleted(&*it))
7591       continue;
7592     // We may go through BB multiple times so skip the one we have checked.
7593     if (!VisitedInstrs.insert(&*it).second) {
7594       if (it->use_empty() && KeyNodes.contains(&*it) &&
7595           vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
7596         // We would like to start over since some instructions are deleted
7597         // and the iterator may become invalid value.
7598         Changed = true;
7599         it = BB->begin();
7600         e = BB->end();
7601       }
7602       continue;
7603     }
7604 
7605     if (isa<DbgInfoIntrinsic>(it))
7606       continue;
7607 
7608     // Try to vectorize reductions that use PHINodes.
7609     if (PHINode *P = dyn_cast<PHINode>(it)) {
7610       // Check that the PHI is a reduction PHI.
7611       if (P->getNumIncomingValues() == 2) {
7612         // Try to match and vectorize a horizontal reduction.
7613         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
7614                                      TTI)) {
7615           Changed = true;
7616           it = BB->begin();
7617           e = BB->end();
7618           continue;
7619         }
7620       }
7621       // Try to vectorize the incoming values of the PHI, to catch reductions
7622       // that feed into PHIs.
7623       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
7624         // Skip if the incoming block is the current BB for now. Also, bypass
7625         // unreachable IR for efficiency and to avoid crashing.
7626         // TODO: Collect the skipped incoming values and try to vectorize them
7627         // after processing BB.
7628         if (BB == P->getIncomingBlock(I) ||
7629             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
7630           continue;
7631 
7632         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
7633                                             P->getIncomingBlock(I), R, TTI);
7634       }
7635       continue;
7636     }
7637 
7638     // Ran into an instruction without users, like terminator, or function call
7639     // with ignored return value, store. Ignore unused instructions (basing on
7640     // instruction type, except for CallInst and InvokeInst).
7641     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
7642                             isa<InvokeInst>(it))) {
7643       KeyNodes.insert(&*it);
7644       bool OpsChanged = false;
7645       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
7646         for (auto *V : it->operand_values()) {
7647           // Try to match and vectorize a horizontal reduction.
7648           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
7649         }
7650       }
7651       // Start vectorization of post-process list of instructions from the
7652       // top-tree instructions to try to vectorize as many instructions as
7653       // possible.
7654       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
7655       if (OpsChanged) {
7656         // We would like to start over since some instructions are deleted
7657         // and the iterator may become invalid value.
7658         Changed = true;
7659         it = BB->begin();
7660         e = BB->end();
7661         continue;
7662       }
7663     }
7664 
7665     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
7666         isa<InsertValueInst>(it))
7667       PostProcessInstructions.push_back(&*it);
7668   }
7669 
7670   return Changed;
7671 }
7672 
7673 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
7674   auto Changed = false;
7675   for (auto &Entry : GEPs) {
7676     // If the getelementptr list has fewer than two elements, there's nothing
7677     // to do.
7678     if (Entry.second.size() < 2)
7679       continue;
7680 
7681     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
7682                       << Entry.second.size() << ".\n");
7683 
7684     // Process the GEP list in chunks suitable for the target's supported
7685     // vector size. If a vector register can't hold 1 element, we are done. We
7686     // are trying to vectorize the index computations, so the maximum number of
7687     // elements is based on the size of the index expression, rather than the
7688     // size of the GEP itself (the target's pointer size).
7689     unsigned MaxVecRegSize = R.getMaxVecRegSize();
7690     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
7691     if (MaxVecRegSize < EltSize)
7692       continue;
7693 
7694     unsigned MaxElts = MaxVecRegSize / EltSize;
7695     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
7696       auto Len = std::min<unsigned>(BE - BI, MaxElts);
7697       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
7698 
7699       // Initialize a set a candidate getelementptrs. Note that we use a
7700       // SetVector here to preserve program order. If the index computations
7701       // are vectorizable and begin with loads, we want to minimize the chance
7702       // of having to reorder them later.
7703       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
7704 
7705       // Some of the candidates may have already been vectorized after we
7706       // initially collected them. If so, they are marked as deleted, so remove
7707       // them from the set of candidates.
7708       Candidates.remove_if(
7709           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
7710 
7711       // Remove from the set of candidates all pairs of getelementptrs with
7712       // constant differences. Such getelementptrs are likely not good
7713       // candidates for vectorization in a bottom-up phase since one can be
7714       // computed from the other. We also ensure all candidate getelementptr
7715       // indices are unique.
7716       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
7717         auto *GEPI = GEPList[I];
7718         if (!Candidates.count(GEPI))
7719           continue;
7720         auto *SCEVI = SE->getSCEV(GEPList[I]);
7721         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
7722           auto *GEPJ = GEPList[J];
7723           auto *SCEVJ = SE->getSCEV(GEPList[J]);
7724           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
7725             Candidates.remove(GEPI);
7726             Candidates.remove(GEPJ);
7727           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
7728             Candidates.remove(GEPJ);
7729           }
7730         }
7731       }
7732 
7733       // We break out of the above computation as soon as we know there are
7734       // fewer than two candidates remaining.
7735       if (Candidates.size() < 2)
7736         continue;
7737 
7738       // Add the single, non-constant index of each candidate to the bundle. We
7739       // ensured the indices met these constraints when we originally collected
7740       // the getelementptrs.
7741       SmallVector<Value *, 16> Bundle(Candidates.size());
7742       auto BundleIndex = 0u;
7743       for (auto *V : Candidates) {
7744         auto *GEP = cast<GetElementPtrInst>(V);
7745         auto *GEPIdx = GEP->idx_begin()->get();
7746         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
7747         Bundle[BundleIndex++] = GEPIdx;
7748       }
7749 
7750       // Try and vectorize the indices. We are currently only interested in
7751       // gather-like cases of the form:
7752       //
7753       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
7754       //
7755       // where the loads of "a", the loads of "b", and the subtractions can be
7756       // performed in parallel. It's likely that detecting this pattern in a
7757       // bottom-up phase will be simpler and less costly than building a
7758       // full-blown top-down phase beginning at the consecutive loads.
7759       Changed |= tryToVectorizeList(Bundle, R);
7760     }
7761   }
7762   return Changed;
7763 }
7764 
7765 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
7766   bool Changed = false;
7767   // Attempt to sort and vectorize each of the store-groups.
7768   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
7769        ++it) {
7770     if (it->second.size() < 2)
7771       continue;
7772 
7773     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
7774                       << it->second.size() << ".\n");
7775 
7776     Changed |= vectorizeStores(it->second, R);
7777   }
7778   return Changed;
7779 }
7780 
7781 char SLPVectorizer::ID = 0;
7782 
7783 static const char lv_name[] = "SLP Vectorizer";
7784 
7785 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
7786 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7787 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7788 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7789 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7790 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
7791 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7792 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7793 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7794 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
7795 
7796 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
7797