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