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