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