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