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