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