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