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