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