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