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