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