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