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