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