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