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