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