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