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) {
1844     auto I = ScalarToTreeEntry.find(V);
1845     if (I != ScalarToTreeEntry.end())
1846       return I->second;
1847     return nullptr;
1848   }
1849 
1850   const TreeEntry *getTreeEntry(Value *V) const {
1851     auto I = ScalarToTreeEntry.find(V);
1852     if (I != ScalarToTreeEntry.end())
1853       return I->second;
1854     return nullptr;
1855   }
1856 
1857   /// Maps a specific scalar to its tree entry.
1858   SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
1859 
1860   /// Maps a value to the proposed vectorizable size.
1861   SmallDenseMap<Value *, unsigned> InstrElementSize;
1862 
1863   /// A list of scalars that we found that we need to keep as scalars.
1864   ValueSet MustGather;
1865 
1866   /// This POD struct describes one external user in the vectorized tree.
1867   struct ExternalUser {
1868     ExternalUser(Value *S, llvm::User *U, int L)
1869         : Scalar(S), User(U), Lane(L) {}
1870 
1871     // Which scalar in our function.
1872     Value *Scalar;
1873 
1874     // Which user that uses the scalar.
1875     llvm::User *User;
1876 
1877     // Which lane does the scalar belong to.
1878     int Lane;
1879   };
1880   using UserList = SmallVector<ExternalUser, 16>;
1881 
1882   /// Checks if two instructions may access the same memory.
1883   ///
1884   /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
1885   /// is invariant in the calling loop.
1886   bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
1887                  Instruction *Inst2) {
1888     // First check if the result is already in the cache.
1889     AliasCacheKey key = std::make_pair(Inst1, Inst2);
1890     Optional<bool> &result = AliasCache[key];
1891     if (result.hasValue()) {
1892       return result.getValue();
1893     }
1894     MemoryLocation Loc2 = getLocation(Inst2, AA);
1895     bool aliased = true;
1896     if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
1897       // Do the alias check.
1898       aliased = AA->alias(Loc1, Loc2);
1899     }
1900     // Store the result in the cache.
1901     result = aliased;
1902     return aliased;
1903   }
1904 
1905   using AliasCacheKey = std::pair<Instruction *, Instruction *>;
1906 
1907   /// Cache for alias results.
1908   /// TODO: consider moving this to the AliasAnalysis itself.
1909   DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
1910 
1911   /// Removes an instruction from its block and eventually deletes it.
1912   /// It's like Instruction::eraseFromParent() except that the actual deletion
1913   /// is delayed until BoUpSLP is destructed.
1914   /// This is required to ensure that there are no incorrect collisions in the
1915   /// AliasCache, which can happen if a new instruction is allocated at the
1916   /// same address as a previously deleted instruction.
1917   void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
1918     auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
1919     It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
1920   }
1921 
1922   /// Temporary store for deleted instructions. Instructions will be deleted
1923   /// eventually when the BoUpSLP is destructed.
1924   DenseMap<Instruction *, bool> DeletedInstructions;
1925 
1926   /// A list of values that need to extracted out of the tree.
1927   /// This list holds pairs of (Internal Scalar : External User). External User
1928   /// can be nullptr, it means that this Internal Scalar will be used later,
1929   /// after vectorization.
1930   UserList ExternalUses;
1931 
1932   /// Values used only by @llvm.assume calls.
1933   SmallPtrSet<const Value *, 32> EphValues;
1934 
1935   /// Holds all of the instructions that we gathered.
1936   SetVector<Instruction *> GatherSeq;
1937 
1938   /// A list of blocks that we are going to CSE.
1939   SetVector<BasicBlock *> CSEBlocks;
1940 
1941   /// Contains all scheduling relevant data for an instruction.
1942   /// A ScheduleData either represents a single instruction or a member of an
1943   /// instruction bundle (= a group of instructions which is combined into a
1944   /// vector instruction).
1945   struct ScheduleData {
1946     // The initial value for the dependency counters. It means that the
1947     // dependencies are not calculated yet.
1948     enum { InvalidDeps = -1 };
1949 
1950     ScheduleData() = default;
1951 
1952     void init(int BlockSchedulingRegionID, Value *OpVal) {
1953       FirstInBundle = this;
1954       NextInBundle = nullptr;
1955       NextLoadStore = nullptr;
1956       IsScheduled = false;
1957       SchedulingRegionID = BlockSchedulingRegionID;
1958       UnscheduledDepsInBundle = UnscheduledDeps;
1959       clearDependencies();
1960       OpValue = OpVal;
1961       TE = nullptr;
1962       Lane = -1;
1963     }
1964 
1965     /// Returns true if the dependency information has been calculated.
1966     bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
1967 
1968     /// Returns true for single instructions and for bundle representatives
1969     /// (= the head of a bundle).
1970     bool isSchedulingEntity() const { return FirstInBundle == this; }
1971 
1972     /// Returns true if it represents an instruction bundle and not only a
1973     /// single instruction.
1974     bool isPartOfBundle() const {
1975       return NextInBundle != nullptr || FirstInBundle != this;
1976     }
1977 
1978     /// Returns true if it is ready for scheduling, i.e. it has no more
1979     /// unscheduled depending instructions/bundles.
1980     bool isReady() const {
1981       assert(isSchedulingEntity() &&
1982              "can't consider non-scheduling entity for ready list");
1983       return UnscheduledDepsInBundle == 0 && !IsScheduled;
1984     }
1985 
1986     /// Modifies the number of unscheduled dependencies, also updating it for
1987     /// the whole bundle.
1988     int incrementUnscheduledDeps(int Incr) {
1989       UnscheduledDeps += Incr;
1990       return FirstInBundle->UnscheduledDepsInBundle += Incr;
1991     }
1992 
1993     /// Sets the number of unscheduled dependencies to the number of
1994     /// dependencies.
1995     void resetUnscheduledDeps() {
1996       incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
1997     }
1998 
1999     /// Clears all dependency information.
2000     void clearDependencies() {
2001       Dependencies = InvalidDeps;
2002       resetUnscheduledDeps();
2003       MemoryDependencies.clear();
2004     }
2005 
2006     void dump(raw_ostream &os) const {
2007       if (!isSchedulingEntity()) {
2008         os << "/ " << *Inst;
2009       } else if (NextInBundle) {
2010         os << '[' << *Inst;
2011         ScheduleData *SD = NextInBundle;
2012         while (SD) {
2013           os << ';' << *SD->Inst;
2014           SD = SD->NextInBundle;
2015         }
2016         os << ']';
2017       } else {
2018         os << *Inst;
2019       }
2020     }
2021 
2022     Instruction *Inst = nullptr;
2023 
2024     /// Points to the head in an instruction bundle (and always to this for
2025     /// single instructions).
2026     ScheduleData *FirstInBundle = nullptr;
2027 
2028     /// Single linked list of all instructions in a bundle. Null if it is a
2029     /// single instruction.
2030     ScheduleData *NextInBundle = nullptr;
2031 
2032     /// Single linked list of all memory instructions (e.g. load, store, call)
2033     /// in the block - until the end of the scheduling region.
2034     ScheduleData *NextLoadStore = nullptr;
2035 
2036     /// The dependent memory instructions.
2037     /// This list is derived on demand in calculateDependencies().
2038     SmallVector<ScheduleData *, 4> MemoryDependencies;
2039 
2040     /// This ScheduleData is in the current scheduling region if this matches
2041     /// the current SchedulingRegionID of BlockScheduling.
2042     int SchedulingRegionID = 0;
2043 
2044     /// Used for getting a "good" final ordering of instructions.
2045     int SchedulingPriority = 0;
2046 
2047     /// The number of dependencies. Constitutes of the number of users of the
2048     /// instruction plus the number of dependent memory instructions (if any).
2049     /// This value is calculated on demand.
2050     /// If InvalidDeps, the number of dependencies is not calculated yet.
2051     int Dependencies = InvalidDeps;
2052 
2053     /// The number of dependencies minus the number of dependencies of scheduled
2054     /// instructions. As soon as this is zero, the instruction/bundle gets ready
2055     /// for scheduling.
2056     /// Note that this is negative as long as Dependencies is not calculated.
2057     int UnscheduledDeps = InvalidDeps;
2058 
2059     /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
2060     /// single instructions.
2061     int UnscheduledDepsInBundle = InvalidDeps;
2062 
2063     /// True if this instruction is scheduled (or considered as scheduled in the
2064     /// dry-run).
2065     bool IsScheduled = false;
2066 
2067     /// Opcode of the current instruction in the schedule data.
2068     Value *OpValue = nullptr;
2069 
2070     /// The TreeEntry that this instruction corresponds to.
2071     TreeEntry *TE = nullptr;
2072 
2073     /// The lane of this node in the TreeEntry.
2074     int Lane = -1;
2075   };
2076 
2077 #ifndef NDEBUG
2078   friend inline raw_ostream &operator<<(raw_ostream &os,
2079                                         const BoUpSLP::ScheduleData &SD) {
2080     SD.dump(os);
2081     return os;
2082   }
2083 #endif
2084 
2085   friend struct GraphTraits<BoUpSLP *>;
2086   friend struct DOTGraphTraits<BoUpSLP *>;
2087 
2088   /// Contains all scheduling data for a basic block.
2089   struct BlockScheduling {
2090     BlockScheduling(BasicBlock *BB)
2091         : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
2092 
2093     void clear() {
2094       ReadyInsts.clear();
2095       ScheduleStart = nullptr;
2096       ScheduleEnd = nullptr;
2097       FirstLoadStoreInRegion = nullptr;
2098       LastLoadStoreInRegion = nullptr;
2099 
2100       // Reduce the maximum schedule region size by the size of the
2101       // previous scheduling run.
2102       ScheduleRegionSizeLimit -= ScheduleRegionSize;
2103       if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
2104         ScheduleRegionSizeLimit = MinScheduleRegionSize;
2105       ScheduleRegionSize = 0;
2106 
2107       // Make a new scheduling region, i.e. all existing ScheduleData is not
2108       // in the new region yet.
2109       ++SchedulingRegionID;
2110     }
2111 
2112     ScheduleData *getScheduleData(Value *V) {
2113       ScheduleData *SD = ScheduleDataMap[V];
2114       if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2115         return SD;
2116       return nullptr;
2117     }
2118 
2119     ScheduleData *getScheduleData(Value *V, Value *Key) {
2120       if (V == Key)
2121         return getScheduleData(V);
2122       auto I = ExtraScheduleDataMap.find(V);
2123       if (I != ExtraScheduleDataMap.end()) {
2124         ScheduleData *SD = I->second[Key];
2125         if (SD && SD->SchedulingRegionID == SchedulingRegionID)
2126           return SD;
2127       }
2128       return nullptr;
2129     }
2130 
2131     bool isInSchedulingRegion(ScheduleData *SD) const {
2132       return SD->SchedulingRegionID == SchedulingRegionID;
2133     }
2134 
2135     /// Marks an instruction as scheduled and puts all dependent ready
2136     /// instructions into the ready-list.
2137     template <typename ReadyListType>
2138     void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
2139       SD->IsScheduled = true;
2140       LLVM_DEBUG(dbgs() << "SLP:   schedule " << *SD << "\n");
2141 
2142       ScheduleData *BundleMember = SD;
2143       while (BundleMember) {
2144         if (BundleMember->Inst != BundleMember->OpValue) {
2145           BundleMember = BundleMember->NextInBundle;
2146           continue;
2147         }
2148         // Handle the def-use chain dependencies.
2149 
2150         // Decrement the unscheduled counter and insert to ready list if ready.
2151         auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
2152           doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
2153             if (OpDef && OpDef->hasValidDependencies() &&
2154                 OpDef->incrementUnscheduledDeps(-1) == 0) {
2155               // There are no more unscheduled dependencies after
2156               // decrementing, so we can put the dependent instruction
2157               // into the ready list.
2158               ScheduleData *DepBundle = OpDef->FirstInBundle;
2159               assert(!DepBundle->IsScheduled &&
2160                      "already scheduled bundle gets ready");
2161               ReadyList.insert(DepBundle);
2162               LLVM_DEBUG(dbgs()
2163                          << "SLP:    gets ready (def): " << *DepBundle << "\n");
2164             }
2165           });
2166         };
2167 
2168         // If BundleMember is a vector bundle, its operands may have been
2169         // reordered duiring buildTree(). We therefore need to get its operands
2170         // through the TreeEntry.
2171         if (TreeEntry *TE = BundleMember->TE) {
2172           int Lane = BundleMember->Lane;
2173           assert(Lane >= 0 && "Lane not set");
2174 
2175           // Since vectorization tree is being built recursively this assertion
2176           // ensures that the tree entry has all operands set before reaching
2177           // this code. Couple of exceptions known at the moment are extracts
2178           // where their second (immediate) operand is not added. Since
2179           // immediates do not affect scheduler behavior this is considered
2180           // okay.
2181           auto *In = TE->getMainOp();
2182           assert(In &&
2183                  (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
2184                   In->getNumOperands() == TE->getNumOperands()) &&
2185                  "Missed TreeEntry operands?");
2186           (void)In; // fake use to avoid build failure when assertions disabled
2187 
2188           for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
2189                OpIdx != NumOperands; ++OpIdx)
2190             if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
2191               DecrUnsched(I);
2192         } else {
2193           // If BundleMember is a stand-alone instruction, no operand reordering
2194           // has taken place, so we directly access its operands.
2195           for (Use &U : BundleMember->Inst->operands())
2196             if (auto *I = dyn_cast<Instruction>(U.get()))
2197               DecrUnsched(I);
2198         }
2199         // Handle the memory dependencies.
2200         for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
2201           if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
2202             // There are no more unscheduled dependencies after decrementing,
2203             // so we can put the dependent instruction into the ready list.
2204             ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
2205             assert(!DepBundle->IsScheduled &&
2206                    "already scheduled bundle gets ready");
2207             ReadyList.insert(DepBundle);
2208             LLVM_DEBUG(dbgs()
2209                        << "SLP:    gets ready (mem): " << *DepBundle << "\n");
2210           }
2211         }
2212         BundleMember = BundleMember->NextInBundle;
2213       }
2214     }
2215 
2216     void doForAllOpcodes(Value *V,
2217                          function_ref<void(ScheduleData *SD)> Action) {
2218       if (ScheduleData *SD = getScheduleData(V))
2219         Action(SD);
2220       auto I = ExtraScheduleDataMap.find(V);
2221       if (I != ExtraScheduleDataMap.end())
2222         for (auto &P : I->second)
2223           if (P.second->SchedulingRegionID == SchedulingRegionID)
2224             Action(P.second);
2225     }
2226 
2227     /// Put all instructions into the ReadyList which are ready for scheduling.
2228     template <typename ReadyListType>
2229     void initialFillReadyList(ReadyListType &ReadyList) {
2230       for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
2231         doForAllOpcodes(I, [&](ScheduleData *SD) {
2232           if (SD->isSchedulingEntity() && SD->isReady()) {
2233             ReadyList.insert(SD);
2234             LLVM_DEBUG(dbgs()
2235                        << "SLP:    initially in ready list: " << *I << "\n");
2236           }
2237         });
2238       }
2239     }
2240 
2241     /// Checks if a bundle of instructions can be scheduled, i.e. has no
2242     /// cyclic dependencies. This is only a dry-run, no instructions are
2243     /// actually moved at this stage.
2244     /// \returns the scheduling bundle. The returned Optional value is non-None
2245     /// if \p VL is allowed to be scheduled.
2246     Optional<ScheduleData *>
2247     tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
2248                       const InstructionsState &S);
2249 
2250     /// Un-bundles a group of instructions.
2251     void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
2252 
2253     /// Allocates schedule data chunk.
2254     ScheduleData *allocateScheduleDataChunks();
2255 
2256     /// Extends the scheduling region so that V is inside the region.
2257     /// \returns true if the region size is within the limit.
2258     bool extendSchedulingRegion(Value *V, const InstructionsState &S);
2259 
2260     /// Initialize the ScheduleData structures for new instructions in the
2261     /// scheduling region.
2262     void initScheduleData(Instruction *FromI, Instruction *ToI,
2263                           ScheduleData *PrevLoadStore,
2264                           ScheduleData *NextLoadStore);
2265 
2266     /// Updates the dependency information of a bundle and of all instructions/
2267     /// bundles which depend on the original bundle.
2268     void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
2269                                BoUpSLP *SLP);
2270 
2271     /// Sets all instruction in the scheduling region to un-scheduled.
2272     void resetSchedule();
2273 
2274     BasicBlock *BB;
2275 
2276     /// Simple memory allocation for ScheduleData.
2277     std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
2278 
2279     /// The size of a ScheduleData array in ScheduleDataChunks.
2280     int ChunkSize;
2281 
2282     /// The allocator position in the current chunk, which is the last entry
2283     /// of ScheduleDataChunks.
2284     int ChunkPos;
2285 
2286     /// Attaches ScheduleData to Instruction.
2287     /// Note that the mapping survives during all vectorization iterations, i.e.
2288     /// ScheduleData structures are recycled.
2289     DenseMap<Value *, ScheduleData *> ScheduleDataMap;
2290 
2291     /// Attaches ScheduleData to Instruction with the leading key.
2292     DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
2293         ExtraScheduleDataMap;
2294 
2295     struct ReadyList : SmallVector<ScheduleData *, 8> {
2296       void insert(ScheduleData *SD) { push_back(SD); }
2297     };
2298 
2299     /// The ready-list for scheduling (only used for the dry-run).
2300     ReadyList ReadyInsts;
2301 
2302     /// The first instruction of the scheduling region.
2303     Instruction *ScheduleStart = nullptr;
2304 
2305     /// The first instruction _after_ the scheduling region.
2306     Instruction *ScheduleEnd = nullptr;
2307 
2308     /// The first memory accessing instruction in the scheduling region
2309     /// (can be null).
2310     ScheduleData *FirstLoadStoreInRegion = nullptr;
2311 
2312     /// The last memory accessing instruction in the scheduling region
2313     /// (can be null).
2314     ScheduleData *LastLoadStoreInRegion = nullptr;
2315 
2316     /// The current size of the scheduling region.
2317     int ScheduleRegionSize = 0;
2318 
2319     /// The maximum size allowed for the scheduling region.
2320     int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
2321 
2322     /// The ID of the scheduling region. For a new vectorization iteration this
2323     /// is incremented which "removes" all ScheduleData from the region.
2324     // Make sure that the initial SchedulingRegionID is greater than the
2325     // initial SchedulingRegionID in ScheduleData (which is 0).
2326     int SchedulingRegionID = 1;
2327   };
2328 
2329   /// Attaches the BlockScheduling structures to basic blocks.
2330   MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
2331 
2332   /// Performs the "real" scheduling. Done before vectorization is actually
2333   /// performed in a basic block.
2334   void scheduleBlock(BlockScheduling *BS);
2335 
2336   /// List of users to ignore during scheduling and that don't need extracting.
2337   ArrayRef<Value *> UserIgnoreList;
2338 
2339   /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
2340   /// sorted SmallVectors of unsigned.
2341   struct OrdersTypeDenseMapInfo {
2342     static OrdersType getEmptyKey() {
2343       OrdersType V;
2344       V.push_back(~1U);
2345       return V;
2346     }
2347 
2348     static OrdersType getTombstoneKey() {
2349       OrdersType V;
2350       V.push_back(~2U);
2351       return V;
2352     }
2353 
2354     static unsigned getHashValue(const OrdersType &V) {
2355       return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
2356     }
2357 
2358     static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
2359       return LHS == RHS;
2360     }
2361   };
2362 
2363   /// Contains orders of operations along with the number of bundles that have
2364   /// operations in this order. It stores only those orders that require
2365   /// reordering, if reordering is not required it is counted using \a
2366   /// NumOpsWantToKeepOriginalOrder.
2367   DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo> NumOpsWantToKeepOrder;
2368   /// Number of bundles that do not require reordering.
2369   unsigned NumOpsWantToKeepOriginalOrder = 0;
2370 
2371   // Analysis and block reference.
2372   Function *F;
2373   ScalarEvolution *SE;
2374   TargetTransformInfo *TTI;
2375   TargetLibraryInfo *TLI;
2376   AAResults *AA;
2377   LoopInfo *LI;
2378   DominatorTree *DT;
2379   AssumptionCache *AC;
2380   DemandedBits *DB;
2381   const DataLayout *DL;
2382   OptimizationRemarkEmitter *ORE;
2383 
2384   unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
2385   unsigned MinVecRegSize; // Set by cl::opt (default: 128).
2386 
2387   /// Instruction builder to construct the vectorized tree.
2388   IRBuilder<> Builder;
2389 
2390   /// A map of scalar integer values to the smallest bit width with which they
2391   /// can legally be represented. The values map to (width, signed) pairs,
2392   /// where "width" indicates the minimum bit width and "signed" is True if the
2393   /// value must be signed-extended, rather than zero-extended, back to its
2394   /// original width.
2395   MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
2396 };
2397 
2398 } // end namespace slpvectorizer
2399 
2400 template <> struct GraphTraits<BoUpSLP *> {
2401   using TreeEntry = BoUpSLP::TreeEntry;
2402 
2403   /// NodeRef has to be a pointer per the GraphWriter.
2404   using NodeRef = TreeEntry *;
2405 
2406   using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
2407 
2408   /// Add the VectorizableTree to the index iterator to be able to return
2409   /// TreeEntry pointers.
2410   struct ChildIteratorType
2411       : public iterator_adaptor_base<
2412             ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
2413     ContainerTy &VectorizableTree;
2414 
2415     ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
2416                       ContainerTy &VT)
2417         : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
2418 
2419     NodeRef operator*() { return I->UserTE; }
2420   };
2421 
2422   static NodeRef getEntryNode(BoUpSLP &R) {
2423     return R.VectorizableTree[0].get();
2424   }
2425 
2426   static ChildIteratorType child_begin(NodeRef N) {
2427     return {N->UserTreeIndices.begin(), N->Container};
2428   }
2429 
2430   static ChildIteratorType child_end(NodeRef N) {
2431     return {N->UserTreeIndices.end(), N->Container};
2432   }
2433 
2434   /// For the node iterator we just need to turn the TreeEntry iterator into a
2435   /// TreeEntry* iterator so that it dereferences to NodeRef.
2436   class nodes_iterator {
2437     using ItTy = ContainerTy::iterator;
2438     ItTy It;
2439 
2440   public:
2441     nodes_iterator(const ItTy &It2) : It(It2) {}
2442     NodeRef operator*() { return It->get(); }
2443     nodes_iterator operator++() {
2444       ++It;
2445       return *this;
2446     }
2447     bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
2448   };
2449 
2450   static nodes_iterator nodes_begin(BoUpSLP *R) {
2451     return nodes_iterator(R->VectorizableTree.begin());
2452   }
2453 
2454   static nodes_iterator nodes_end(BoUpSLP *R) {
2455     return nodes_iterator(R->VectorizableTree.end());
2456   }
2457 
2458   static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
2459 };
2460 
2461 template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
2462   using TreeEntry = BoUpSLP::TreeEntry;
2463 
2464   DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
2465 
2466   std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
2467     std::string Str;
2468     raw_string_ostream OS(Str);
2469     if (isSplat(Entry->Scalars)) {
2470       OS << "<splat> " << *Entry->Scalars[0];
2471       return Str;
2472     }
2473     for (auto V : Entry->Scalars) {
2474       OS << *V;
2475       if (std::any_of(
2476               R->ExternalUses.begin(), R->ExternalUses.end(),
2477               [&](const BoUpSLP::ExternalUser &EU) { return EU.Scalar == V; }))
2478         OS << " <extract>";
2479       OS << "\n";
2480     }
2481     return Str;
2482   }
2483 
2484   static std::string getNodeAttributes(const TreeEntry *Entry,
2485                                        const BoUpSLP *) {
2486     if (Entry->State == TreeEntry::NeedToGather)
2487       return "color=red";
2488     return "";
2489   }
2490 };
2491 
2492 } // end namespace llvm
2493 
2494 BoUpSLP::~BoUpSLP() {
2495   for (const auto &Pair : DeletedInstructions) {
2496     // Replace operands of ignored instructions with Undefs in case if they were
2497     // marked for deletion.
2498     if (Pair.getSecond()) {
2499       Value *Undef = UndefValue::get(Pair.getFirst()->getType());
2500       Pair.getFirst()->replaceAllUsesWith(Undef);
2501     }
2502     Pair.getFirst()->dropAllReferences();
2503   }
2504   for (const auto &Pair : DeletedInstructions) {
2505     assert(Pair.getFirst()->use_empty() &&
2506            "trying to erase instruction with users.");
2507     Pair.getFirst()->eraseFromParent();
2508   }
2509   assert(!verifyFunction(*F, &dbgs()));
2510 }
2511 
2512 void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
2513   for (auto *V : AV) {
2514     if (auto *I = dyn_cast<Instruction>(V))
2515       eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
2516   };
2517 }
2518 
2519 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
2520                         ArrayRef<Value *> UserIgnoreLst) {
2521   ExtraValueToDebugLocsMap ExternallyUsedValues;
2522   buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
2523 }
2524 
2525 void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
2526                         ExtraValueToDebugLocsMap &ExternallyUsedValues,
2527                         ArrayRef<Value *> UserIgnoreLst) {
2528   deleteTree();
2529   UserIgnoreList = UserIgnoreLst;
2530   if (!allSameType(Roots))
2531     return;
2532   buildTree_rec(Roots, 0, EdgeInfo());
2533 
2534   // Collect the values that we need to extract from the tree.
2535   for (auto &TEPtr : VectorizableTree) {
2536     TreeEntry *Entry = TEPtr.get();
2537 
2538     // No need to handle users of gathered values.
2539     if (Entry->State == TreeEntry::NeedToGather)
2540       continue;
2541 
2542     // For each lane:
2543     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
2544       Value *Scalar = Entry->Scalars[Lane];
2545       int FoundLane = Lane;
2546       if (!Entry->ReuseShuffleIndices.empty()) {
2547         FoundLane =
2548             std::distance(Entry->ReuseShuffleIndices.begin(),
2549                           llvm::find(Entry->ReuseShuffleIndices, FoundLane));
2550       }
2551 
2552       // Check if the scalar is externally used as an extra arg.
2553       auto ExtI = ExternallyUsedValues.find(Scalar);
2554       if (ExtI != ExternallyUsedValues.end()) {
2555         LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
2556                           << Lane << " from " << *Scalar << ".\n");
2557         ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
2558       }
2559       for (User *U : Scalar->users()) {
2560         LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
2561 
2562         Instruction *UserInst = dyn_cast<Instruction>(U);
2563         if (!UserInst)
2564           continue;
2565 
2566         // Skip in-tree scalars that become vectors
2567         if (TreeEntry *UseEntry = getTreeEntry(U)) {
2568           Value *UseScalar = UseEntry->Scalars[0];
2569           // Some in-tree scalars will remain as scalar in vectorized
2570           // instructions. If that is the case, the one in Lane 0 will
2571           // be used.
2572           if (UseScalar != U ||
2573               !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
2574             LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
2575                               << ".\n");
2576             assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
2577             continue;
2578           }
2579         }
2580 
2581         // Ignore users in the user ignore list.
2582         if (is_contained(UserIgnoreList, UserInst))
2583           continue;
2584 
2585         LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
2586                           << Lane << " from " << *Scalar << ".\n");
2587         ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
2588       }
2589     }
2590   }
2591 }
2592 
2593 void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
2594                             const EdgeInfo &UserTreeIdx) {
2595   assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
2596 
2597   InstructionsState S = getSameOpcode(VL);
2598   if (Depth == RecursionMaxDepth) {
2599     LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
2600     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2601     return;
2602   }
2603 
2604   // Don't handle vectors.
2605   if (S.OpValue->getType()->isVectorTy()) {
2606     LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
2607     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2608     return;
2609   }
2610 
2611   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
2612     if (SI->getValueOperand()->getType()->isVectorTy()) {
2613       LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
2614       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2615       return;
2616     }
2617 
2618   // If all of the operands are identical or constant we have a simple solution.
2619   if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode()) {
2620     LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
2621     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2622     return;
2623   }
2624 
2625   // We now know that this is a vector of instructions of the same type from
2626   // the same block.
2627 
2628   // Don't vectorize ephemeral values.
2629   for (Value *V : VL) {
2630     if (EphValues.count(V)) {
2631       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
2632                         << ") is ephemeral.\n");
2633       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2634       return;
2635     }
2636   }
2637 
2638   // Check if this is a duplicate of another entry.
2639   if (TreeEntry *E = getTreeEntry(S.OpValue)) {
2640     LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
2641     if (!E->isSame(VL)) {
2642       LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
2643       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2644       return;
2645     }
2646     // Record the reuse of the tree node.  FIXME, currently this is only used to
2647     // properly draw the graph rather than for the actual vectorization.
2648     E->UserTreeIndices.push_back(UserTreeIdx);
2649     LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
2650                       << ".\n");
2651     return;
2652   }
2653 
2654   // Check that none of the instructions in the bundle are already in the tree.
2655   for (Value *V : VL) {
2656     auto *I = dyn_cast<Instruction>(V);
2657     if (!I)
2658       continue;
2659     if (getTreeEntry(I)) {
2660       LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
2661                         << ") is already in tree.\n");
2662       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2663       return;
2664     }
2665   }
2666 
2667   // If any of the scalars is marked as a value that needs to stay scalar, then
2668   // we need to gather the scalars.
2669   // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
2670   for (Value *V : VL) {
2671     if (MustGather.count(V) || is_contained(UserIgnoreList, V)) {
2672       LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
2673       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2674       return;
2675     }
2676   }
2677 
2678   // Check that all of the users of the scalars that we want to vectorize are
2679   // schedulable.
2680   auto *VL0 = cast<Instruction>(S.OpValue);
2681   BasicBlock *BB = VL0->getParent();
2682 
2683   if (!DT->isReachableFromEntry(BB)) {
2684     // Don't go into unreachable blocks. They may contain instructions with
2685     // dependency cycles which confuse the final scheduling.
2686     LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
2687     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2688     return;
2689   }
2690 
2691   // Check that every instruction appears once in this bundle.
2692   SmallVector<unsigned, 4> ReuseShuffleIndicies;
2693   SmallVector<Value *, 4> UniqueValues;
2694   DenseMap<Value *, unsigned> UniquePositions;
2695   for (Value *V : VL) {
2696     auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
2697     ReuseShuffleIndicies.emplace_back(Res.first->second);
2698     if (Res.second)
2699       UniqueValues.emplace_back(V);
2700   }
2701   size_t NumUniqueScalarValues = UniqueValues.size();
2702   if (NumUniqueScalarValues == VL.size()) {
2703     ReuseShuffleIndicies.clear();
2704   } else {
2705     LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
2706     if (NumUniqueScalarValues <= 1 ||
2707         !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
2708       LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
2709       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
2710       return;
2711     }
2712     VL = UniqueValues;
2713   }
2714 
2715   auto &BSRef = BlocksSchedules[BB];
2716   if (!BSRef)
2717     BSRef = std::make_unique<BlockScheduling>(BB);
2718 
2719   BlockScheduling &BS = *BSRef.get();
2720 
2721   Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
2722   if (!Bundle) {
2723     LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
2724     assert((!BS.getScheduleData(VL0) ||
2725             !BS.getScheduleData(VL0)->isPartOfBundle()) &&
2726            "tryScheduleBundle should cancelScheduling on failure");
2727     newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2728                  ReuseShuffleIndicies);
2729     return;
2730   }
2731   LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
2732 
2733   unsigned ShuffleOrOp = S.isAltShuffle() ?
2734                 (unsigned) Instruction::ShuffleVector : S.getOpcode();
2735   switch (ShuffleOrOp) {
2736     case Instruction::PHI: {
2737       auto *PH = cast<PHINode>(VL0);
2738 
2739       // Check for terminator values (e.g. invoke).
2740       for (Value *V : VL)
2741         for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
2742           Instruction *Term = dyn_cast<Instruction>(
2743               cast<PHINode>(V)->getIncomingValueForBlock(
2744                   PH->getIncomingBlock(I)));
2745           if (Term && Term->isTerminator()) {
2746             LLVM_DEBUG(dbgs()
2747                        << "SLP: Need to swizzle PHINodes (terminator use).\n");
2748             BS.cancelScheduling(VL, VL0);
2749             newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2750                          ReuseShuffleIndicies);
2751             return;
2752           }
2753         }
2754 
2755       TreeEntry *TE =
2756           newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
2757       LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
2758 
2759       // Keeps the reordered operands to avoid code duplication.
2760       SmallVector<ValueList, 2> OperandsVec;
2761       for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
2762         ValueList Operands;
2763         // Prepare the operand vector.
2764         for (Value *V : VL)
2765           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
2766               PH->getIncomingBlock(I)));
2767         TE->setOperand(I, Operands);
2768         OperandsVec.push_back(Operands);
2769       }
2770       for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
2771         buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
2772       return;
2773     }
2774     case Instruction::ExtractValue:
2775     case Instruction::ExtractElement: {
2776       OrdersType CurrentOrder;
2777       bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
2778       if (Reuse) {
2779         LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
2780         ++NumOpsWantToKeepOriginalOrder;
2781         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2782                      ReuseShuffleIndicies);
2783         // This is a special case, as it does not gather, but at the same time
2784         // we are not extending buildTree_rec() towards the operands.
2785         ValueList Op0;
2786         Op0.assign(VL.size(), VL0->getOperand(0));
2787         VectorizableTree.back()->setOperand(0, Op0);
2788         return;
2789       }
2790       if (!CurrentOrder.empty()) {
2791         LLVM_DEBUG({
2792           dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
2793                     "with order";
2794           for (unsigned Idx : CurrentOrder)
2795             dbgs() << " " << Idx;
2796           dbgs() << "\n";
2797         });
2798         // Insert new order with initial value 0, if it does not exist,
2799         // otherwise return the iterator to the existing one.
2800         newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2801                      ReuseShuffleIndicies, CurrentOrder);
2802         findRootOrder(CurrentOrder);
2803         ++NumOpsWantToKeepOrder[CurrentOrder];
2804         // This is a special case, as it does not gather, but at the same time
2805         // we are not extending buildTree_rec() towards the operands.
2806         ValueList Op0;
2807         Op0.assign(VL.size(), VL0->getOperand(0));
2808         VectorizableTree.back()->setOperand(0, Op0);
2809         return;
2810       }
2811       LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
2812       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2813                    ReuseShuffleIndicies);
2814       BS.cancelScheduling(VL, VL0);
2815       return;
2816     }
2817     case Instruction::Load: {
2818       // Check that a vectorized load would load the same memory as a scalar
2819       // load. For example, we don't want to vectorize loads that are smaller
2820       // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
2821       // treats loading/storing it as an i8 struct. If we vectorize loads/stores
2822       // from such a struct, we read/write packed bits disagreeing with the
2823       // unvectorized version.
2824       Type *ScalarTy = VL0->getType();
2825 
2826       if (DL->getTypeSizeInBits(ScalarTy) !=
2827           DL->getTypeAllocSizeInBits(ScalarTy)) {
2828         BS.cancelScheduling(VL, VL0);
2829         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2830                      ReuseShuffleIndicies);
2831         LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
2832         return;
2833       }
2834 
2835       // Make sure all loads in the bundle are simple - we can't vectorize
2836       // atomic or volatile loads.
2837       SmallVector<Value *, 4> PointerOps(VL.size());
2838       auto POIter = PointerOps.begin();
2839       for (Value *V : VL) {
2840         auto *L = cast<LoadInst>(V);
2841         if (!L->isSimple()) {
2842           BS.cancelScheduling(VL, VL0);
2843           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2844                        ReuseShuffleIndicies);
2845           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
2846           return;
2847         }
2848         *POIter = L->getPointerOperand();
2849         ++POIter;
2850       }
2851 
2852       OrdersType CurrentOrder;
2853       // Check the order of pointer operands.
2854       if (llvm::sortPtrAccesses(PointerOps, *DL, *SE, CurrentOrder)) {
2855         Value *Ptr0;
2856         Value *PtrN;
2857         if (CurrentOrder.empty()) {
2858           Ptr0 = PointerOps.front();
2859           PtrN = PointerOps.back();
2860         } else {
2861           Ptr0 = PointerOps[CurrentOrder.front()];
2862           PtrN = PointerOps[CurrentOrder.back()];
2863         }
2864         const SCEV *Scev0 = SE->getSCEV(Ptr0);
2865         const SCEV *ScevN = SE->getSCEV(PtrN);
2866         const auto *Diff =
2867             dyn_cast<SCEVConstant>(SE->getMinusSCEV(ScevN, Scev0));
2868         uint64_t Size = DL->getTypeAllocSize(ScalarTy);
2869         // Check that the sorted loads are consecutive.
2870         if (Diff && Diff->getAPInt() == (VL.size() - 1) * Size) {
2871           if (CurrentOrder.empty()) {
2872             // Original loads are consecutive and does not require reordering.
2873             ++NumOpsWantToKeepOriginalOrder;
2874             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
2875                                          UserTreeIdx, ReuseShuffleIndicies);
2876             TE->setOperandsInOrder();
2877             LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
2878           } else {
2879             // Need to reorder.
2880             TreeEntry *TE =
2881                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2882                              ReuseShuffleIndicies, CurrentOrder);
2883             TE->setOperandsInOrder();
2884             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
2885             findRootOrder(CurrentOrder);
2886             ++NumOpsWantToKeepOrder[CurrentOrder];
2887           }
2888           return;
2889         }
2890         // Vectorizing non-consecutive loads with `llvm.masked.gather`.
2891         TreeEntry *TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
2892                                      UserTreeIdx, ReuseShuffleIndicies);
2893         TE->setOperandsInOrder();
2894         buildTree_rec(PointerOps, Depth + 1, {TE, 0});
2895         LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
2896         return;
2897       }
2898 
2899       LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
2900       BS.cancelScheduling(VL, VL0);
2901       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2902                    ReuseShuffleIndicies);
2903       return;
2904     }
2905     case Instruction::ZExt:
2906     case Instruction::SExt:
2907     case Instruction::FPToUI:
2908     case Instruction::FPToSI:
2909     case Instruction::FPExt:
2910     case Instruction::PtrToInt:
2911     case Instruction::IntToPtr:
2912     case Instruction::SIToFP:
2913     case Instruction::UIToFP:
2914     case Instruction::Trunc:
2915     case Instruction::FPTrunc:
2916     case Instruction::BitCast: {
2917       Type *SrcTy = VL0->getOperand(0)->getType();
2918       for (Value *V : VL) {
2919         Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
2920         if (Ty != SrcTy || !isValidElementType(Ty)) {
2921           BS.cancelScheduling(VL, VL0);
2922           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2923                        ReuseShuffleIndicies);
2924           LLVM_DEBUG(dbgs()
2925                      << "SLP: Gathering casts with different src types.\n");
2926           return;
2927         }
2928       }
2929       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2930                                    ReuseShuffleIndicies);
2931       LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
2932 
2933       TE->setOperandsInOrder();
2934       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
2935         ValueList Operands;
2936         // Prepare the operand vector.
2937         for (Value *V : VL)
2938           Operands.push_back(cast<Instruction>(V)->getOperand(i));
2939 
2940         buildTree_rec(Operands, Depth + 1, {TE, i});
2941       }
2942       return;
2943     }
2944     case Instruction::ICmp:
2945     case Instruction::FCmp: {
2946       // Check that all of the compares have the same predicate.
2947       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
2948       CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
2949       Type *ComparedTy = VL0->getOperand(0)->getType();
2950       for (Value *V : VL) {
2951         CmpInst *Cmp = cast<CmpInst>(V);
2952         if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
2953             Cmp->getOperand(0)->getType() != ComparedTy) {
2954           BS.cancelScheduling(VL, VL0);
2955           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
2956                        ReuseShuffleIndicies);
2957           LLVM_DEBUG(dbgs()
2958                      << "SLP: Gathering cmp with different predicate.\n");
2959           return;
2960         }
2961       }
2962 
2963       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
2964                                    ReuseShuffleIndicies);
2965       LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
2966 
2967       ValueList Left, Right;
2968       if (cast<CmpInst>(VL0)->isCommutative()) {
2969         // Commutative predicate - collect + sort operands of the instructions
2970         // so that each side is more likely to have the same opcode.
2971         assert(P0 == SwapP0 && "Commutative Predicate mismatch");
2972         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
2973       } else {
2974         // Collect operands - commute if it uses the swapped predicate.
2975         for (Value *V : VL) {
2976           auto *Cmp = cast<CmpInst>(V);
2977           Value *LHS = Cmp->getOperand(0);
2978           Value *RHS = Cmp->getOperand(1);
2979           if (Cmp->getPredicate() != P0)
2980             std::swap(LHS, RHS);
2981           Left.push_back(LHS);
2982           Right.push_back(RHS);
2983         }
2984       }
2985       TE->setOperand(0, Left);
2986       TE->setOperand(1, Right);
2987       buildTree_rec(Left, Depth + 1, {TE, 0});
2988       buildTree_rec(Right, Depth + 1, {TE, 1});
2989       return;
2990     }
2991     case Instruction::Select:
2992     case Instruction::FNeg:
2993     case Instruction::Add:
2994     case Instruction::FAdd:
2995     case Instruction::Sub:
2996     case Instruction::FSub:
2997     case Instruction::Mul:
2998     case Instruction::FMul:
2999     case Instruction::UDiv:
3000     case Instruction::SDiv:
3001     case Instruction::FDiv:
3002     case Instruction::URem:
3003     case Instruction::SRem:
3004     case Instruction::FRem:
3005     case Instruction::Shl:
3006     case Instruction::LShr:
3007     case Instruction::AShr:
3008     case Instruction::And:
3009     case Instruction::Or:
3010     case Instruction::Xor: {
3011       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3012                                    ReuseShuffleIndicies);
3013       LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
3014 
3015       // Sort operands of the instructions so that each side is more likely to
3016       // have the same opcode.
3017       if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
3018         ValueList Left, Right;
3019         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3020         TE->setOperand(0, Left);
3021         TE->setOperand(1, Right);
3022         buildTree_rec(Left, Depth + 1, {TE, 0});
3023         buildTree_rec(Right, Depth + 1, {TE, 1});
3024         return;
3025       }
3026 
3027       TE->setOperandsInOrder();
3028       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3029         ValueList Operands;
3030         // Prepare the operand vector.
3031         for (Value *V : VL)
3032           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3033 
3034         buildTree_rec(Operands, Depth + 1, {TE, i});
3035       }
3036       return;
3037     }
3038     case Instruction::GetElementPtr: {
3039       // We don't combine GEPs with complicated (nested) indexing.
3040       for (Value *V : VL) {
3041         if (cast<Instruction>(V)->getNumOperands() != 2) {
3042           LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
3043           BS.cancelScheduling(VL, VL0);
3044           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3045                        ReuseShuffleIndicies);
3046           return;
3047         }
3048       }
3049 
3050       // We can't combine several GEPs into one vector if they operate on
3051       // different types.
3052       Type *Ty0 = VL0->getOperand(0)->getType();
3053       for (Value *V : VL) {
3054         Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
3055         if (Ty0 != CurTy) {
3056           LLVM_DEBUG(dbgs()
3057                      << "SLP: not-vectorizable GEP (different types).\n");
3058           BS.cancelScheduling(VL, VL0);
3059           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3060                        ReuseShuffleIndicies);
3061           return;
3062         }
3063       }
3064 
3065       // We don't combine GEPs with non-constant indexes.
3066       Type *Ty1 = VL0->getOperand(1)->getType();
3067       for (Value *V : VL) {
3068         auto Op = cast<Instruction>(V)->getOperand(1);
3069         if (!isa<ConstantInt>(Op) ||
3070             (Op->getType() != Ty1 &&
3071              Op->getType()->getScalarSizeInBits() >
3072                  DL->getIndexSizeInBits(
3073                      V->getType()->getPointerAddressSpace()))) {
3074           LLVM_DEBUG(dbgs()
3075                      << "SLP: not-vectorizable GEP (non-constant indexes).\n");
3076           BS.cancelScheduling(VL, VL0);
3077           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3078                        ReuseShuffleIndicies);
3079           return;
3080         }
3081       }
3082 
3083       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3084                                    ReuseShuffleIndicies);
3085       LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
3086       TE->setOperandsInOrder();
3087       for (unsigned i = 0, e = 2; i < e; ++i) {
3088         ValueList Operands;
3089         // Prepare the operand vector.
3090         for (Value *V : VL)
3091           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3092 
3093         buildTree_rec(Operands, Depth + 1, {TE, i});
3094       }
3095       return;
3096     }
3097     case Instruction::Store: {
3098       // Check if the stores are consecutive or if we need to swizzle them.
3099       llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
3100       // Make sure all stores in the bundle are simple - we can't vectorize
3101       // atomic or volatile stores.
3102       SmallVector<Value *, 4> PointerOps(VL.size());
3103       ValueList Operands(VL.size());
3104       auto POIter = PointerOps.begin();
3105       auto OIter = Operands.begin();
3106       for (Value *V : VL) {
3107         auto *SI = cast<StoreInst>(V);
3108         if (!SI->isSimple()) {
3109           BS.cancelScheduling(VL, VL0);
3110           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3111                        ReuseShuffleIndicies);
3112           LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
3113           return;
3114         }
3115         *POIter = SI->getPointerOperand();
3116         *OIter = SI->getValueOperand();
3117         ++POIter;
3118         ++OIter;
3119       }
3120 
3121       OrdersType CurrentOrder;
3122       // Check the order of pointer operands.
3123       if (llvm::sortPtrAccesses(PointerOps, *DL, *SE, CurrentOrder)) {
3124         Value *Ptr0;
3125         Value *PtrN;
3126         if (CurrentOrder.empty()) {
3127           Ptr0 = PointerOps.front();
3128           PtrN = PointerOps.back();
3129         } else {
3130           Ptr0 = PointerOps[CurrentOrder.front()];
3131           PtrN = PointerOps[CurrentOrder.back()];
3132         }
3133         const SCEV *Scev0 = SE->getSCEV(Ptr0);
3134         const SCEV *ScevN = SE->getSCEV(PtrN);
3135         const auto *Diff =
3136             dyn_cast<SCEVConstant>(SE->getMinusSCEV(ScevN, Scev0));
3137         uint64_t Size = DL->getTypeAllocSize(ScalarTy);
3138         // Check that the sorted pointer operands are consecutive.
3139         if (Diff && Diff->getAPInt() == (VL.size() - 1) * Size) {
3140           if (CurrentOrder.empty()) {
3141             // Original stores are consecutive and does not require reordering.
3142             ++NumOpsWantToKeepOriginalOrder;
3143             TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
3144                                          UserTreeIdx, ReuseShuffleIndicies);
3145             TE->setOperandsInOrder();
3146             buildTree_rec(Operands, Depth + 1, {TE, 0});
3147             LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
3148           } else {
3149             TreeEntry *TE =
3150                 newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3151                              ReuseShuffleIndicies, CurrentOrder);
3152             TE->setOperandsInOrder();
3153             buildTree_rec(Operands, Depth + 1, {TE, 0});
3154             LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
3155             findRootOrder(CurrentOrder);
3156             ++NumOpsWantToKeepOrder[CurrentOrder];
3157           }
3158           return;
3159         }
3160       }
3161 
3162       BS.cancelScheduling(VL, VL0);
3163       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3164                    ReuseShuffleIndicies);
3165       LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
3166       return;
3167     }
3168     case Instruction::Call: {
3169       // Check if the calls are all to the same vectorizable intrinsic or
3170       // library function.
3171       CallInst *CI = cast<CallInst>(VL0);
3172       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3173 
3174       VFShape Shape = VFShape::get(
3175           *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
3176           false /*HasGlobalPred*/);
3177       Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3178 
3179       if (!VecFunc && !isTriviallyVectorizable(ID)) {
3180         BS.cancelScheduling(VL, VL0);
3181         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3182                      ReuseShuffleIndicies);
3183         LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
3184         return;
3185       }
3186       Function *F = CI->getCalledFunction();
3187       unsigned NumArgs = CI->getNumArgOperands();
3188       SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
3189       for (unsigned j = 0; j != NumArgs; ++j)
3190         if (hasVectorInstrinsicScalarOpd(ID, j))
3191           ScalarArgs[j] = CI->getArgOperand(j);
3192       for (Value *V : VL) {
3193         CallInst *CI2 = dyn_cast<CallInst>(V);
3194         if (!CI2 || CI2->getCalledFunction() != F ||
3195             getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
3196             (VecFunc &&
3197              VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
3198             !CI->hasIdenticalOperandBundleSchema(*CI2)) {
3199           BS.cancelScheduling(VL, VL0);
3200           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3201                        ReuseShuffleIndicies);
3202           LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
3203                             << "\n");
3204           return;
3205         }
3206         // Some intrinsics have scalar arguments and should be same in order for
3207         // them to be vectorized.
3208         for (unsigned j = 0; j != NumArgs; ++j) {
3209           if (hasVectorInstrinsicScalarOpd(ID, j)) {
3210             Value *A1J = CI2->getArgOperand(j);
3211             if (ScalarArgs[j] != A1J) {
3212               BS.cancelScheduling(VL, VL0);
3213               newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3214                            ReuseShuffleIndicies);
3215               LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
3216                                 << " argument " << ScalarArgs[j] << "!=" << A1J
3217                                 << "\n");
3218               return;
3219             }
3220           }
3221         }
3222         // Verify that the bundle operands are identical between the two calls.
3223         if (CI->hasOperandBundles() &&
3224             !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
3225                         CI->op_begin() + CI->getBundleOperandsEndIndex(),
3226                         CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
3227           BS.cancelScheduling(VL, VL0);
3228           newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3229                        ReuseShuffleIndicies);
3230           LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
3231                             << *CI << "!=" << *V << '\n');
3232           return;
3233         }
3234       }
3235 
3236       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3237                                    ReuseShuffleIndicies);
3238       TE->setOperandsInOrder();
3239       for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
3240         ValueList Operands;
3241         // Prepare the operand vector.
3242         for (Value *V : VL) {
3243           auto *CI2 = cast<CallInst>(V);
3244           Operands.push_back(CI2->getArgOperand(i));
3245         }
3246         buildTree_rec(Operands, Depth + 1, {TE, i});
3247       }
3248       return;
3249     }
3250     case Instruction::ShuffleVector: {
3251       // If this is not an alternate sequence of opcode like add-sub
3252       // then do not vectorize this instruction.
3253       if (!S.isAltShuffle()) {
3254         BS.cancelScheduling(VL, VL0);
3255         newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3256                      ReuseShuffleIndicies);
3257         LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
3258         return;
3259       }
3260       TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
3261                                    ReuseShuffleIndicies);
3262       LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
3263 
3264       // Reorder operands if reordering would enable vectorization.
3265       if (isa<BinaryOperator>(VL0)) {
3266         ValueList Left, Right;
3267         reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
3268         TE->setOperand(0, Left);
3269         TE->setOperand(1, Right);
3270         buildTree_rec(Left, Depth + 1, {TE, 0});
3271         buildTree_rec(Right, Depth + 1, {TE, 1});
3272         return;
3273       }
3274 
3275       TE->setOperandsInOrder();
3276       for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
3277         ValueList Operands;
3278         // Prepare the operand vector.
3279         for (Value *V : VL)
3280           Operands.push_back(cast<Instruction>(V)->getOperand(i));
3281 
3282         buildTree_rec(Operands, Depth + 1, {TE, i});
3283       }
3284       return;
3285     }
3286     default:
3287       BS.cancelScheduling(VL, VL0);
3288       newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
3289                    ReuseShuffleIndicies);
3290       LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
3291       return;
3292   }
3293 }
3294 
3295 unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
3296   unsigned N = 1;
3297   Type *EltTy = T;
3298 
3299   while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
3300          isa<VectorType>(EltTy)) {
3301     if (auto *ST = dyn_cast<StructType>(EltTy)) {
3302       // Check that struct is homogeneous.
3303       for (const auto *Ty : ST->elements())
3304         if (Ty != *ST->element_begin())
3305           return 0;
3306       N *= ST->getNumElements();
3307       EltTy = *ST->element_begin();
3308     } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
3309       N *= AT->getNumElements();
3310       EltTy = AT->getElementType();
3311     } else {
3312       auto *VT = cast<FixedVectorType>(EltTy);
3313       N *= VT->getNumElements();
3314       EltTy = VT->getElementType();
3315     }
3316   }
3317 
3318   if (!isValidElementType(EltTy))
3319     return 0;
3320   uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
3321   if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
3322     return 0;
3323   return N;
3324 }
3325 
3326 bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
3327                               SmallVectorImpl<unsigned> &CurrentOrder) const {
3328   Instruction *E0 = cast<Instruction>(OpValue);
3329   assert(E0->getOpcode() == Instruction::ExtractElement ||
3330          E0->getOpcode() == Instruction::ExtractValue);
3331   assert(E0->getOpcode() == getSameOpcode(VL).getOpcode() && "Invalid opcode");
3332   // Check if all of the extracts come from the same vector and from the
3333   // correct offset.
3334   Value *Vec = E0->getOperand(0);
3335 
3336   CurrentOrder.clear();
3337 
3338   // We have to extract from a vector/aggregate with the same number of elements.
3339   unsigned NElts;
3340   if (E0->getOpcode() == Instruction::ExtractValue) {
3341     const DataLayout &DL = E0->getModule()->getDataLayout();
3342     NElts = canMapToVector(Vec->getType(), DL);
3343     if (!NElts)
3344       return false;
3345     // Check if load can be rewritten as load of vector.
3346     LoadInst *LI = dyn_cast<LoadInst>(Vec);
3347     if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
3348       return false;
3349   } else {
3350     NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
3351   }
3352 
3353   if (NElts != VL.size())
3354     return false;
3355 
3356   // Check that all of the indices extract from the correct offset.
3357   bool ShouldKeepOrder = true;
3358   unsigned E = VL.size();
3359   // Assign to all items the initial value E + 1 so we can check if the extract
3360   // instruction index was used already.
3361   // Also, later we can check that all the indices are used and we have a
3362   // consecutive access in the extract instructions, by checking that no
3363   // element of CurrentOrder still has value E + 1.
3364   CurrentOrder.assign(E, E + 1);
3365   unsigned I = 0;
3366   for (; I < E; ++I) {
3367     auto *Inst = cast<Instruction>(VL[I]);
3368     if (Inst->getOperand(0) != Vec)
3369       break;
3370     Optional<unsigned> Idx = getExtractIndex(Inst);
3371     if (!Idx)
3372       break;
3373     const unsigned ExtIdx = *Idx;
3374     if (ExtIdx != I) {
3375       if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1)
3376         break;
3377       ShouldKeepOrder = false;
3378       CurrentOrder[ExtIdx] = I;
3379     } else {
3380       if (CurrentOrder[I] != E + 1)
3381         break;
3382       CurrentOrder[I] = I;
3383     }
3384   }
3385   if (I < E) {
3386     CurrentOrder.clear();
3387     return false;
3388   }
3389 
3390   return ShouldKeepOrder;
3391 }
3392 
3393 bool BoUpSLP::areAllUsersVectorized(Instruction *I) const {
3394   return I->hasOneUse() ||
3395          std::all_of(I->user_begin(), I->user_end(), [this](User *U) {
3396            return ScalarToTreeEntry.count(U) > 0;
3397          });
3398 }
3399 
3400 static std::pair<unsigned, unsigned>
3401 getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
3402                    TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
3403   Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3404 
3405   // Calculate the cost of the scalar and vector calls.
3406   IntrinsicCostAttributes CostAttrs(ID, *CI, VecTy->getElementCount());
3407   int IntrinsicCost =
3408     TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
3409 
3410   auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
3411                                      VecTy->getNumElements())),
3412                             false /*HasGlobalPred*/);
3413   Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
3414   int LibCost = IntrinsicCost;
3415   if (!CI->isNoBuiltin() && VecFunc) {
3416     // Calculate the cost of the vector library call.
3417     SmallVector<Type *, 4> VecTys;
3418     for (Use &Arg : CI->args())
3419       VecTys.push_back(
3420           FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
3421 
3422     // If the corresponding vector call is cheaper, return its cost.
3423     LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
3424                                     TTI::TCK_RecipThroughput);
3425   }
3426   return {IntrinsicCost, LibCost};
3427 }
3428 
3429 InstructionCost BoUpSLP::getEntryCost(TreeEntry *E) {
3430   ArrayRef<Value*> VL = E->Scalars;
3431 
3432   Type *ScalarTy = VL[0]->getType();
3433   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
3434     ScalarTy = SI->getValueOperand()->getType();
3435   else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
3436     ScalarTy = CI->getOperand(0)->getType();
3437   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
3438   TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
3439 
3440   // If we have computed a smaller type for the expression, update VecTy so
3441   // that the costs will be accurate.
3442   if (MinBWs.count(VL[0]))
3443     VecTy = FixedVectorType::get(
3444         IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
3445 
3446   unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size();
3447   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
3448   InstructionCost ReuseShuffleCost = 0;
3449   if (NeedToShuffleReuses) {
3450     ReuseShuffleCost =
3451         TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
3452   }
3453   if (E->State == TreeEntry::NeedToGather) {
3454     if (allConstant(VL))
3455       return 0;
3456     if (isSplat(VL)) {
3457       return ReuseShuffleCost +
3458              TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
3459     }
3460     if (E->getOpcode() == Instruction::ExtractElement &&
3461         allSameType(VL) && allSameBlock(VL)) {
3462       Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = isShuffle(VL);
3463       if (ShuffleKind.hasValue()) {
3464         InstructionCost Cost =
3465             TTI->getShuffleCost(ShuffleKind.getValue(), VecTy);
3466         for (auto *V : VL) {
3467           // If all users of instruction are going to be vectorized and this
3468           // instruction itself is not going to be vectorized, consider this
3469           // instruction as dead and remove its cost from the final cost of the
3470           // vectorized tree.
3471           if (areAllUsersVectorized(cast<Instruction>(V)) &&
3472               !ScalarToTreeEntry.count(V)) {
3473             auto *IO = cast<ConstantInt>(
3474                 cast<ExtractElementInst>(V)->getIndexOperand());
3475             Cost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
3476                                             IO->getZExtValue());
3477           }
3478         }
3479         return ReuseShuffleCost + Cost;
3480       }
3481     }
3482     return ReuseShuffleCost + getGatherCost(VL);
3483   }
3484   assert((E->State == TreeEntry::Vectorize ||
3485           E->State == TreeEntry::ScatterVectorize) &&
3486          "Unhandled state");
3487   assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
3488   Instruction *VL0 = E->getMainOp();
3489   unsigned ShuffleOrOp =
3490       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
3491   switch (ShuffleOrOp) {
3492     case Instruction::PHI:
3493       return 0;
3494 
3495     case Instruction::ExtractValue:
3496     case Instruction::ExtractElement: {
3497       InstructionCost DeadCost = 0;
3498       if (NeedToShuffleReuses) {
3499         unsigned Idx = 0;
3500         for (unsigned I : E->ReuseShuffleIndices) {
3501           if (ShuffleOrOp == Instruction::ExtractElement) {
3502             auto *IO = cast<ConstantInt>(
3503                 cast<ExtractElementInst>(VL[I])->getIndexOperand());
3504             Idx = IO->getZExtValue();
3505             ReuseShuffleCost -= TTI->getVectorInstrCost(
3506                 Instruction::ExtractElement, VecTy, Idx);
3507           } else {
3508             ReuseShuffleCost -= TTI->getVectorInstrCost(
3509                 Instruction::ExtractElement, VecTy, Idx);
3510             ++Idx;
3511           }
3512         }
3513         Idx = ReuseShuffleNumbers;
3514         for (Value *V : VL) {
3515           if (ShuffleOrOp == Instruction::ExtractElement) {
3516             auto *IO = cast<ConstantInt>(
3517                 cast<ExtractElementInst>(V)->getIndexOperand());
3518             Idx = IO->getZExtValue();
3519           } else {
3520             --Idx;
3521           }
3522           ReuseShuffleCost +=
3523               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, Idx);
3524         }
3525         DeadCost = ReuseShuffleCost;
3526       } else if (!E->ReorderIndices.empty()) {
3527         DeadCost = TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
3528                                        VecTy);
3529       }
3530       for (unsigned I = 0, E = VL.size(); I < E; ++I) {
3531         Instruction *EI = cast<Instruction>(VL[I]);
3532         // If all users are going to be vectorized, instruction can be
3533         // considered as dead.
3534         // The same, if have only one user, it will be vectorized for sure.
3535         if (areAllUsersVectorized(EI)) {
3536           // Take credit for instruction that will become dead.
3537           if (EI->hasOneUse()) {
3538             Instruction *Ext = EI->user_back();
3539             if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
3540                 all_of(Ext->users(),
3541                        [](User *U) { return isa<GetElementPtrInst>(U); })) {
3542               // Use getExtractWithExtendCost() to calculate the cost of
3543               // extractelement/ext pair.
3544               DeadCost -= TTI->getExtractWithExtendCost(
3545                   Ext->getOpcode(), Ext->getType(), VecTy, I);
3546               // Add back the cost of s|zext which is subtracted separately.
3547               DeadCost += TTI->getCastInstrCost(
3548                   Ext->getOpcode(), Ext->getType(), EI->getType(),
3549                   TTI::getCastContextHint(Ext), CostKind, Ext);
3550               continue;
3551             }
3552           }
3553           DeadCost -=
3554               TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
3555         }
3556       }
3557       return DeadCost;
3558     }
3559     case Instruction::ZExt:
3560     case Instruction::SExt:
3561     case Instruction::FPToUI:
3562     case Instruction::FPToSI:
3563     case Instruction::FPExt:
3564     case Instruction::PtrToInt:
3565     case Instruction::IntToPtr:
3566     case Instruction::SIToFP:
3567     case Instruction::UIToFP:
3568     case Instruction::Trunc:
3569     case Instruction::FPTrunc:
3570     case Instruction::BitCast: {
3571       Type *SrcTy = VL0->getOperand(0)->getType();
3572       InstructionCost ScalarEltCost =
3573           TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
3574                                 TTI::getCastContextHint(VL0), CostKind, VL0);
3575       if (NeedToShuffleReuses) {
3576         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3577       }
3578 
3579       // Calculate the cost of this instruction.
3580       InstructionCost ScalarCost = VL.size() * ScalarEltCost;
3581 
3582       auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
3583       InstructionCost VecCost = 0;
3584       // Check if the values are candidates to demote.
3585       if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
3586         VecCost =
3587             ReuseShuffleCost +
3588             TTI->getCastInstrCost(E->getOpcode(), VecTy, SrcVecTy,
3589                                   TTI::getCastContextHint(VL0), CostKind, VL0);
3590       }
3591       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecCost, ScalarCost));
3592       return VecCost - ScalarCost;
3593     }
3594     case Instruction::FCmp:
3595     case Instruction::ICmp:
3596     case Instruction::Select: {
3597       // Calculate the cost of this instruction.
3598       InstructionCost ScalarEltCost =
3599           TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
3600                                   CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
3601       if (NeedToShuffleReuses) {
3602         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3603       }
3604       auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
3605       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
3606 
3607       // Check if all entries in VL are either compares or selects with compares
3608       // as condition that have the same predicates.
3609       CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
3610       bool First = true;
3611       for (auto *V : VL) {
3612         CmpInst::Predicate CurrentPred;
3613         auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
3614         if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
3615              !match(V, MatchCmp)) ||
3616             (!First && VecPred != CurrentPred)) {
3617           VecPred = CmpInst::BAD_ICMP_PREDICATE;
3618           break;
3619         }
3620         First = false;
3621         VecPred = CurrentPred;
3622       }
3623 
3624       InstructionCost VecCost = TTI->getCmpSelInstrCost(
3625           E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
3626       // Check if it is possible and profitable to use min/max for selects in
3627       // VL.
3628       //
3629       auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
3630       if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
3631         IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
3632                                           {VecTy, VecTy});
3633         InstructionCost IntrinsicCost =
3634             TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
3635         // If the selects are the only uses of the compares, they will be dead
3636         // and we can adjust the cost by removing their cost.
3637         if (IntrinsicAndUse.second)
3638           IntrinsicCost -=
3639               TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
3640                                       CmpInst::BAD_ICMP_PREDICATE, CostKind);
3641         VecCost = std::min(VecCost, IntrinsicCost);
3642       }
3643       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecCost, ScalarCost));
3644       return ReuseShuffleCost + VecCost - ScalarCost;
3645     }
3646     case Instruction::FNeg:
3647     case Instruction::Add:
3648     case Instruction::FAdd:
3649     case Instruction::Sub:
3650     case Instruction::FSub:
3651     case Instruction::Mul:
3652     case Instruction::FMul:
3653     case Instruction::UDiv:
3654     case Instruction::SDiv:
3655     case Instruction::FDiv:
3656     case Instruction::URem:
3657     case Instruction::SRem:
3658     case Instruction::FRem:
3659     case Instruction::Shl:
3660     case Instruction::LShr:
3661     case Instruction::AShr:
3662     case Instruction::And:
3663     case Instruction::Or:
3664     case Instruction::Xor: {
3665       // Certain instructions can be cheaper to vectorize if they have a
3666       // constant second vector operand.
3667       TargetTransformInfo::OperandValueKind Op1VK =
3668           TargetTransformInfo::OK_AnyValue;
3669       TargetTransformInfo::OperandValueKind Op2VK =
3670           TargetTransformInfo::OK_UniformConstantValue;
3671       TargetTransformInfo::OperandValueProperties Op1VP =
3672           TargetTransformInfo::OP_None;
3673       TargetTransformInfo::OperandValueProperties Op2VP =
3674           TargetTransformInfo::OP_PowerOf2;
3675 
3676       // If all operands are exactly the same ConstantInt then set the
3677       // operand kind to OK_UniformConstantValue.
3678       // If instead not all operands are constants, then set the operand kind
3679       // to OK_AnyValue. If all operands are constants but not the same,
3680       // then set the operand kind to OK_NonUniformConstantValue.
3681       ConstantInt *CInt0 = nullptr;
3682       for (unsigned i = 0, e = VL.size(); i < e; ++i) {
3683         const Instruction *I = cast<Instruction>(VL[i]);
3684         unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
3685         ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
3686         if (!CInt) {
3687           Op2VK = TargetTransformInfo::OK_AnyValue;
3688           Op2VP = TargetTransformInfo::OP_None;
3689           break;
3690         }
3691         if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
3692             !CInt->getValue().isPowerOf2())
3693           Op2VP = TargetTransformInfo::OP_None;
3694         if (i == 0) {
3695           CInt0 = CInt;
3696           continue;
3697         }
3698         if (CInt0 != CInt)
3699           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
3700       }
3701 
3702       SmallVector<const Value *, 4> Operands(VL0->operand_values());
3703       InstructionCost ScalarEltCost =
3704           TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
3705                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
3706       if (NeedToShuffleReuses) {
3707         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3708       }
3709       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
3710       InstructionCost VecCost =
3711           TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
3712                                       Op2VK, Op1VP, Op2VP, Operands, VL0);
3713       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecCost, ScalarCost));
3714       return ReuseShuffleCost + VecCost - ScalarCost;
3715     }
3716     case Instruction::GetElementPtr: {
3717       TargetTransformInfo::OperandValueKind Op1VK =
3718           TargetTransformInfo::OK_AnyValue;
3719       TargetTransformInfo::OperandValueKind Op2VK =
3720           TargetTransformInfo::OK_UniformConstantValue;
3721 
3722       InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
3723           Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
3724       if (NeedToShuffleReuses) {
3725         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3726       }
3727       InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
3728       InstructionCost VecCost = TTI->getArithmeticInstrCost(
3729           Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
3730       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecCost, ScalarCost));
3731       return ReuseShuffleCost + VecCost - ScalarCost;
3732     }
3733     case Instruction::Load: {
3734       // Cost of wide load - cost of scalar loads.
3735       Align alignment = cast<LoadInst>(VL0)->getAlign();
3736       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
3737           Instruction::Load, ScalarTy, alignment, 0, CostKind, VL0);
3738       if (NeedToShuffleReuses) {
3739         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3740       }
3741       InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
3742       InstructionCost VecLdCost;
3743       if (E->State == TreeEntry::Vectorize) {
3744         VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, alignment, 0,
3745                                          CostKind, VL0);
3746       } else {
3747         assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
3748         VecLdCost = TTI->getGatherScatterOpCost(
3749             Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
3750             /*VariableMask=*/false, alignment, CostKind, VL0);
3751       }
3752       if (!NeedToShuffleReuses && !E->ReorderIndices.empty())
3753         VecLdCost += TTI->getShuffleCost(
3754             TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
3755       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecLdCost, ScalarLdCost));
3756       return ReuseShuffleCost + VecLdCost - ScalarLdCost;
3757     }
3758     case Instruction::Store: {
3759       // We know that we can merge the stores. Calculate the cost.
3760       bool IsReorder = !E->ReorderIndices.empty();
3761       auto *SI =
3762           cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
3763       Align Alignment = SI->getAlign();
3764       InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
3765           Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
3766       InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
3767       InstructionCost VecStCost = TTI->getMemoryOpCost(
3768           Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
3769       if (IsReorder)
3770         VecStCost += TTI->getShuffleCost(
3771             TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
3772       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecStCost, ScalarStCost));
3773       return VecStCost - ScalarStCost;
3774     }
3775     case Instruction::Call: {
3776       CallInst *CI = cast<CallInst>(VL0);
3777       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3778 
3779       // Calculate the cost of the scalar and vector calls.
3780       IntrinsicCostAttributes CostAttrs(ID, *CI, ElementCount::getFixed(1), 1);
3781       InstructionCost ScalarEltCost =
3782           TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
3783       if (NeedToShuffleReuses) {
3784         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
3785       }
3786       InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
3787 
3788       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
3789       InstructionCost VecCallCost =
3790           std::min(VecCallCosts.first, VecCallCosts.second);
3791 
3792       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
3793                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
3794                         << " for " << *CI << "\n");
3795 
3796       return ReuseShuffleCost + VecCallCost - ScalarCallCost;
3797     }
3798     case Instruction::ShuffleVector: {
3799       assert(E->isAltShuffle() &&
3800              ((Instruction::isBinaryOp(E->getOpcode()) &&
3801                Instruction::isBinaryOp(E->getAltOpcode())) ||
3802               (Instruction::isCast(E->getOpcode()) &&
3803                Instruction::isCast(E->getAltOpcode()))) &&
3804              "Invalid Shuffle Vector Operand");
3805       InstructionCost ScalarCost = 0;
3806       if (NeedToShuffleReuses) {
3807         for (unsigned Idx : E->ReuseShuffleIndices) {
3808           Instruction *I = cast<Instruction>(VL[Idx]);
3809           InstructionCost Cost = TTI->getInstructionCost(I, CostKind);
3810           assert(Cost.isValid() && "Invalid instruction cost");
3811           ReuseShuffleCost -= *(Cost.getValue());
3812         }
3813         for (Value *V : VL) {
3814           Instruction *I = cast<Instruction>(V);
3815           InstructionCost Cost = TTI->getInstructionCost(I, CostKind);
3816           assert(Cost.isValid() && "Invalid instruction cost");
3817           ReuseShuffleCost += *(Cost.getValue());
3818         }
3819       }
3820       for (Value *V : VL) {
3821         Instruction *I = cast<Instruction>(V);
3822         assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
3823         InstructionCost Cost = TTI->getInstructionCost(I, CostKind);
3824         assert(Cost.isValid() && "Invalid instruction cost");
3825         ScalarCost += *(Cost.getValue());
3826       }
3827       // VecCost is equal to sum of the cost of creating 2 vectors
3828       // and the cost of creating shuffle.
3829       InstructionCost VecCost = 0;
3830       if (Instruction::isBinaryOp(E->getOpcode())) {
3831         VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
3832         VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
3833                                                CostKind);
3834       } else {
3835         Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
3836         Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
3837         auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
3838         auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
3839         VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
3840                                         TTI::CastContextHint::None, CostKind);
3841         VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
3842                                          TTI::CastContextHint::None, CostKind);
3843       }
3844       VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_Select, VecTy, 0);
3845       LLVM_DEBUG(dumpTreeCosts(E, ReuseShuffleCost, VecCost, ScalarCost));
3846       return ReuseShuffleCost + VecCost - ScalarCost;
3847     }
3848     default:
3849       llvm_unreachable("Unknown instruction");
3850   }
3851 }
3852 
3853 bool BoUpSLP::isFullyVectorizableTinyTree() const {
3854   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
3855                     << VectorizableTree.size() << " is fully vectorizable .\n");
3856 
3857   // We only handle trees of heights 1 and 2.
3858   if (VectorizableTree.size() == 1 &&
3859       VectorizableTree[0]->State == TreeEntry::Vectorize)
3860     return true;
3861 
3862   if (VectorizableTree.size() != 2)
3863     return false;
3864 
3865   // Handle splat and all-constants stores.
3866   if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
3867       (allConstant(VectorizableTree[1]->Scalars) ||
3868        isSplat(VectorizableTree[1]->Scalars)))
3869     return true;
3870 
3871   // Gathering cost would be too much for tiny trees.
3872   if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
3873       VectorizableTree[1]->State == TreeEntry::NeedToGather)
3874     return false;
3875 
3876   return true;
3877 }
3878 
3879 static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
3880                                        TargetTransformInfo *TTI) {
3881   // Look past the root to find a source value. Arbitrarily follow the
3882   // path through operand 0 of any 'or'. Also, peek through optional
3883   // shift-left-by-multiple-of-8-bits.
3884   Value *ZextLoad = Root;
3885   const APInt *ShAmtC;
3886   while (!isa<ConstantExpr>(ZextLoad) &&
3887          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
3888           (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
3889            ShAmtC->urem(8) == 0)))
3890     ZextLoad = cast<BinaryOperator>(ZextLoad)->getOperand(0);
3891 
3892   // Check if the input is an extended load of the required or/shift expression.
3893   Value *LoadPtr;
3894   if (ZextLoad == Root || !match(ZextLoad, m_ZExt(m_Load(m_Value(LoadPtr)))))
3895     return false;
3896 
3897   // Require that the total load bit width is a legal integer type.
3898   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
3899   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
3900   Type *SrcTy = LoadPtr->getType()->getPointerElementType();
3901   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
3902   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
3903     return false;
3904 
3905   // Everything matched - assume that we can fold the whole sequence using
3906   // load combining.
3907   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
3908              << *(cast<Instruction>(Root)) << "\n");
3909 
3910   return true;
3911 }
3912 
3913 bool BoUpSLP::isLoadCombineReductionCandidate(unsigned RdxOpcode) const {
3914   if (RdxOpcode != Instruction::Or)
3915     return false;
3916 
3917   unsigned NumElts = VectorizableTree[0]->Scalars.size();
3918   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
3919   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI);
3920 }
3921 
3922 bool BoUpSLP::isLoadCombineCandidate() const {
3923   // Peek through a final sequence of stores and check if all operations are
3924   // likely to be load-combined.
3925   unsigned NumElts = VectorizableTree[0]->Scalars.size();
3926   for (Value *Scalar : VectorizableTree[0]->Scalars) {
3927     Value *X;
3928     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
3929         !isLoadCombineCandidateImpl(X, NumElts, TTI))
3930       return false;
3931   }
3932   return true;
3933 }
3934 
3935 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() const {
3936   // We can vectorize the tree if its size is greater than or equal to the
3937   // minimum size specified by the MinTreeSize command line option.
3938   if (VectorizableTree.size() >= MinTreeSize)
3939     return false;
3940 
3941   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
3942   // can vectorize it if we can prove it fully vectorizable.
3943   if (isFullyVectorizableTinyTree())
3944     return false;
3945 
3946   assert(VectorizableTree.empty()
3947              ? ExternalUses.empty()
3948              : true && "We shouldn't have any external users");
3949 
3950   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
3951   // vectorizable.
3952   return true;
3953 }
3954 
3955 InstructionCost BoUpSLP::getSpillCost() const {
3956   // Walk from the bottom of the tree to the top, tracking which values are
3957   // live. When we see a call instruction that is not part of our tree,
3958   // query TTI to see if there is a cost to keeping values live over it
3959   // (for example, if spills and fills are required).
3960   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
3961   InstructionCost Cost = 0;
3962 
3963   SmallPtrSet<Instruction*, 4> LiveValues;
3964   Instruction *PrevInst = nullptr;
3965 
3966   // The entries in VectorizableTree are not necessarily ordered by their
3967   // position in basic blocks. Collect them and order them by dominance so later
3968   // instructions are guaranteed to be visited first. For instructions in
3969   // different basic blocks, we only scan to the beginning of the block, so
3970   // their order does not matter, as long as all instructions in a basic block
3971   // are grouped together. Using dominance ensures a deterministic order.
3972   SmallVector<Instruction *, 16> OrderedScalars;
3973   for (const auto &TEPtr : VectorizableTree) {
3974     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
3975     if (!Inst)
3976       continue;
3977     OrderedScalars.push_back(Inst);
3978   }
3979   llvm::stable_sort(OrderedScalars, [this](Instruction *A, Instruction *B) {
3980     return DT->dominates(B, A);
3981   });
3982 
3983   for (Instruction *Inst : OrderedScalars) {
3984     if (!PrevInst) {
3985       PrevInst = Inst;
3986       continue;
3987     }
3988 
3989     // Update LiveValues.
3990     LiveValues.erase(PrevInst);
3991     for (auto &J : PrevInst->operands()) {
3992       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
3993         LiveValues.insert(cast<Instruction>(&*J));
3994     }
3995 
3996     LLVM_DEBUG({
3997       dbgs() << "SLP: #LV: " << LiveValues.size();
3998       for (auto *X : LiveValues)
3999         dbgs() << " " << X->getName();
4000       dbgs() << ", Looking at ";
4001       Inst->dump();
4002     });
4003 
4004     // Now find the sequence of instructions between PrevInst and Inst.
4005     unsigned NumCalls = 0;
4006     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
4007                                  PrevInstIt =
4008                                      PrevInst->getIterator().getReverse();
4009     while (InstIt != PrevInstIt) {
4010       if (PrevInstIt == PrevInst->getParent()->rend()) {
4011         PrevInstIt = Inst->getParent()->rbegin();
4012         continue;
4013       }
4014 
4015       // Debug information does not impact spill cost.
4016       if ((isa<CallInst>(&*PrevInstIt) &&
4017            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
4018           &*PrevInstIt != PrevInst)
4019         NumCalls++;
4020 
4021       ++PrevInstIt;
4022     }
4023 
4024     if (NumCalls) {
4025       SmallVector<Type*, 4> V;
4026       for (auto *II : LiveValues)
4027         V.push_back(FixedVectorType::get(II->getType(), BundleWidth));
4028       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
4029     }
4030 
4031     PrevInst = Inst;
4032   }
4033 
4034   return Cost;
4035 }
4036 
4037 InstructionCost BoUpSLP::getTreeCost() {
4038   InstructionCost Cost = 0;
4039   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
4040                     << VectorizableTree.size() << ".\n");
4041 
4042   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
4043 
4044   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
4045     TreeEntry &TE = *VectorizableTree[I].get();
4046 
4047     // We create duplicate tree entries for gather sequences that have multiple
4048     // uses. However, we should not compute the cost of duplicate sequences.
4049     // For example, if we have a build vector (i.e., insertelement sequence)
4050     // that is used by more than one vector instruction, we only need to
4051     // compute the cost of the insertelement instructions once. The redundant
4052     // instructions will be eliminated by CSE.
4053     //
4054     // We should consider not creating duplicate tree entries for gather
4055     // sequences, and instead add additional edges to the tree representing
4056     // their uses. Since such an approach results in fewer total entries,
4057     // existing heuristics based on tree size may yield different results.
4058     //
4059     if (TE.State == TreeEntry::NeedToGather &&
4060         std::any_of(std::next(VectorizableTree.begin(), I + 1),
4061                     VectorizableTree.end(),
4062                     [TE](const std::unique_ptr<TreeEntry> &EntryPtr) {
4063                       return EntryPtr->State == TreeEntry::NeedToGather &&
4064                              EntryPtr->isSame(TE.Scalars);
4065                     }))
4066       continue;
4067 
4068     InstructionCost C = getEntryCost(&TE);
4069     Cost += C;
4070     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
4071                       << " for bundle that starts with " << *TE.Scalars[0]
4072                       << ".\n"
4073                       << "SLP: Current total cost = " << Cost << "\n");
4074   }
4075 
4076   SmallPtrSet<Value *, 16> ExtractCostCalculated;
4077   InstructionCost ExtractCost = 0;
4078   for (ExternalUser &EU : ExternalUses) {
4079     // We only add extract cost once for the same scalar.
4080     if (!ExtractCostCalculated.insert(EU.Scalar).second)
4081       continue;
4082 
4083     // Uses by ephemeral values are free (because the ephemeral value will be
4084     // removed prior to code generation, and so the extraction will be
4085     // removed as well).
4086     if (EphValues.count(EU.User))
4087       continue;
4088 
4089     // If we plan to rewrite the tree in a smaller type, we will need to sign
4090     // extend the extracted value back to the original type. Here, we account
4091     // for the extract and the added cost of the sign extend if needed.
4092     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
4093     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
4094     if (MinBWs.count(ScalarRoot)) {
4095       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
4096       auto Extend =
4097           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
4098       VecTy = FixedVectorType::get(MinTy, BundleWidth);
4099       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
4100                                                    VecTy, EU.Lane);
4101     } else {
4102       ExtractCost +=
4103           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
4104     }
4105   }
4106 
4107   InstructionCost SpillCost = getSpillCost();
4108   Cost += SpillCost + ExtractCost;
4109 
4110 #ifndef NDEBUG
4111   SmallString<256> Str;
4112   {
4113     raw_svector_ostream OS(Str);
4114     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
4115        << "SLP: Extract Cost = " << ExtractCost << ".\n"
4116        << "SLP: Total Cost = " << Cost << ".\n";
4117   }
4118   LLVM_DEBUG(dbgs() << Str);
4119   if (ViewSLPTree)
4120     ViewGraph(this, "SLP" + F->getName(), false, Str);
4121 #endif
4122 
4123   return Cost;
4124 }
4125 
4126 InstructionCost
4127 BoUpSLP::getGatherCost(FixedVectorType *Ty,
4128                        const DenseSet<unsigned> &ShuffledIndices) const {
4129   unsigned NumElts = Ty->getNumElements();
4130   APInt DemandedElts = APInt::getNullValue(NumElts);
4131   for (unsigned I = 0; I < NumElts; ++I)
4132     if (!ShuffledIndices.count(I))
4133       DemandedElts.setBit(I);
4134   InstructionCost Cost =
4135       TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
4136                                     /*Extract*/ false);
4137   if (!ShuffledIndices.empty())
4138     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
4139   return Cost;
4140 }
4141 
4142 InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
4143   // Find the type of the operands in VL.
4144   Type *ScalarTy = VL[0]->getType();
4145   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
4146     ScalarTy = SI->getValueOperand()->getType();
4147   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4148   // Find the cost of inserting/extracting values from the vector.
4149   // Check if the same elements are inserted several times and count them as
4150   // shuffle candidates.
4151   DenseSet<unsigned> ShuffledElements;
4152   DenseSet<Value *> UniqueElements;
4153   // Iterate in reverse order to consider insert elements with the high cost.
4154   for (unsigned I = VL.size(); I > 0; --I) {
4155     unsigned Idx = I - 1;
4156     if (!UniqueElements.insert(VL[Idx]).second)
4157       ShuffledElements.insert(Idx);
4158   }
4159   return getGatherCost(VecTy, ShuffledElements);
4160 }
4161 
4162 // Perform operand reordering on the instructions in VL and return the reordered
4163 // operands in Left and Right.
4164 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
4165                                              SmallVectorImpl<Value *> &Left,
4166                                              SmallVectorImpl<Value *> &Right,
4167                                              const DataLayout &DL,
4168                                              ScalarEvolution &SE,
4169                                              const BoUpSLP &R) {
4170   if (VL.empty())
4171     return;
4172   VLOperands Ops(VL, DL, SE, R);
4173   // Reorder the operands in place.
4174   Ops.reorder();
4175   Left = Ops.getVL(0);
4176   Right = Ops.getVL(1);
4177 }
4178 
4179 void BoUpSLP::setInsertPointAfterBundle(TreeEntry *E) {
4180   // Get the basic block this bundle is in. All instructions in the bundle
4181   // should be in this block.
4182   auto *Front = E->getMainOp();
4183   auto *BB = Front->getParent();
4184   assert(llvm::all_of(make_range(E->Scalars.begin(), E->Scalars.end()),
4185                       [=](Value *V) -> bool {
4186                         auto *I = cast<Instruction>(V);
4187                         return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
4188                       }));
4189 
4190   // The last instruction in the bundle in program order.
4191   Instruction *LastInst = nullptr;
4192 
4193   // Find the last instruction. The common case should be that BB has been
4194   // scheduled, and the last instruction is VL.back(). So we start with
4195   // VL.back() and iterate over schedule data until we reach the end of the
4196   // bundle. The end of the bundle is marked by null ScheduleData.
4197   if (BlocksSchedules.count(BB)) {
4198     auto *Bundle =
4199         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
4200     if (Bundle && Bundle->isPartOfBundle())
4201       for (; Bundle; Bundle = Bundle->NextInBundle)
4202         if (Bundle->OpValue == Bundle->Inst)
4203           LastInst = Bundle->Inst;
4204   }
4205 
4206   // LastInst can still be null at this point if there's either not an entry
4207   // for BB in BlocksSchedules or there's no ScheduleData available for
4208   // VL.back(). This can be the case if buildTree_rec aborts for various
4209   // reasons (e.g., the maximum recursion depth is reached, the maximum region
4210   // size is reached, etc.). ScheduleData is initialized in the scheduling
4211   // "dry-run".
4212   //
4213   // If this happens, we can still find the last instruction by brute force. We
4214   // iterate forwards from Front (inclusive) until we either see all
4215   // instructions in the bundle or reach the end of the block. If Front is the
4216   // last instruction in program order, LastInst will be set to Front, and we
4217   // will visit all the remaining instructions in the block.
4218   //
4219   // One of the reasons we exit early from buildTree_rec is to place an upper
4220   // bound on compile-time. Thus, taking an additional compile-time hit here is
4221   // not ideal. However, this should be exceedingly rare since it requires that
4222   // we both exit early from buildTree_rec and that the bundle be out-of-order
4223   // (causing us to iterate all the way to the end of the block).
4224   if (!LastInst) {
4225     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
4226     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
4227       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
4228         LastInst = &I;
4229       if (Bundle.empty())
4230         break;
4231     }
4232   }
4233   assert(LastInst && "Failed to find last instruction in bundle");
4234 
4235   // Set the insertion point after the last instruction in the bundle. Set the
4236   // debug location to Front.
4237   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
4238   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
4239 }
4240 
4241 Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
4242   Value *Val0 =
4243       isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
4244   FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
4245   Value *Vec = UndefValue::get(VecTy);
4246   unsigned InsIndex = 0;
4247   for (Value *Val : VL) {
4248     Vec = Builder.CreateInsertElement(Vec, Val, Builder.getInt32(InsIndex++));
4249     auto *InsElt = dyn_cast<InsertElementInst>(Vec);
4250     if (!InsElt)
4251       continue;
4252     GatherSeq.insert(InsElt);
4253     CSEBlocks.insert(InsElt->getParent());
4254     // Add to our 'need-to-extract' list.
4255     if (TreeEntry *Entry = getTreeEntry(Val)) {
4256       // Find which lane we need to extract.
4257       unsigned FoundLane = std::distance(Entry->Scalars.begin(),
4258                                          find(Entry->Scalars, Val));
4259       assert(FoundLane < Entry->Scalars.size() && "Couldn't find extract lane");
4260       if (!Entry->ReuseShuffleIndices.empty()) {
4261         FoundLane = std::distance(Entry->ReuseShuffleIndices.begin(),
4262                                   find(Entry->ReuseShuffleIndices, FoundLane));
4263       }
4264       ExternalUses.push_back(ExternalUser(Val, InsElt, FoundLane));
4265     }
4266   }
4267 
4268   return Vec;
4269 }
4270 
4271 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
4272   InstructionsState S = getSameOpcode(VL);
4273   if (S.getOpcode()) {
4274     if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4275       if (E->isSame(VL)) {
4276         Value *V = vectorizeTree(E);
4277         if (VL.size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) {
4278           // We need to get the vectorized value but without shuffle.
4279           if (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
4280             V = SV->getOperand(0);
4281           } else {
4282             // Reshuffle to get only unique values.
4283             SmallVector<int, 4> UniqueIdxs;
4284             SmallSet<int, 4> UsedIdxs;
4285             for (int Idx : E->ReuseShuffleIndices)
4286               if (UsedIdxs.insert(Idx).second)
4287                 UniqueIdxs.emplace_back(Idx);
4288             V = Builder.CreateShuffleVector(V, UniqueIdxs);
4289           }
4290         }
4291         return V;
4292       }
4293     }
4294   }
4295 
4296   // Check that every instruction appears once in this bundle.
4297   SmallVector<int, 4> ReuseShuffleIndicies;
4298   SmallVector<Value *, 4> UniqueValues;
4299   if (VL.size() > 2) {
4300     DenseMap<Value *, unsigned> UniquePositions;
4301     for (Value *V : VL) {
4302       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4303       ReuseShuffleIndicies.emplace_back(Res.first->second);
4304       if (Res.second || isa<Constant>(V))
4305         UniqueValues.emplace_back(V);
4306     }
4307     // Do not shuffle single element or if number of unique values is not power
4308     // of 2.
4309     if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 ||
4310         !llvm::isPowerOf2_32(UniqueValues.size()))
4311       ReuseShuffleIndicies.clear();
4312     else
4313       VL = UniqueValues;
4314   }
4315 
4316   Value *Vec = gather(VL);
4317   if (!ReuseShuffleIndicies.empty()) {
4318     Vec = Builder.CreateShuffleVector(Vec, ReuseShuffleIndicies, "shuffle");
4319     if (auto *I = dyn_cast<Instruction>(Vec)) {
4320       GatherSeq.insert(I);
4321       CSEBlocks.insert(I->getParent());
4322     }
4323   }
4324   return Vec;
4325 }
4326 
4327 namespace {
4328 /// Merges shuffle masks and emits final shuffle instruction, if required.
4329 class ShuffleInstructionBuilder {
4330   IRBuilderBase &Builder;
4331   bool IsFinalized = false;
4332   SmallVector<int, 4> Mask;
4333 
4334 public:
4335   ShuffleInstructionBuilder(IRBuilderBase &Builder) : Builder(Builder) {}
4336 
4337   /// Adds a mask, inverting it before applying.
4338   void addInversedMask(ArrayRef<unsigned> SubMask) {
4339     if (SubMask.empty())
4340       return;
4341     SmallVector<int, 4> NewMask;
4342     inversePermutation(SubMask, NewMask);
4343     addMask(NewMask);
4344   }
4345 
4346   /// Functions adds masks, merging them into  single one.
4347   void addMask(ArrayRef<unsigned> SubMask) {
4348     SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
4349     addMask(NewMask);
4350   }
4351 
4352   void addMask(ArrayRef<int> SubMask) {
4353     if (SubMask.empty())
4354       return;
4355     if (Mask.empty()) {
4356       Mask.append(SubMask.begin(), SubMask.end());
4357       return;
4358     }
4359     SmallVector<int, 4> NewMask(SubMask.size(), SubMask.size());
4360     int TermValue = std::min(Mask.size(), SubMask.size());
4361     for (int I = 0, E = SubMask.size(); I < E; ++I) {
4362       if (SubMask[I] >= TermValue || Mask[SubMask[I]] >= TermValue) {
4363         NewMask[I] = E;
4364         continue;
4365       }
4366       NewMask[I] = Mask[SubMask[I]];
4367     }
4368     Mask.swap(NewMask);
4369   }
4370 
4371   Value *finalize(Value *V) {
4372     IsFinalized = true;
4373     if (Mask.empty())
4374       return V;
4375     return Builder.CreateShuffleVector(V, Mask, "shuffle");
4376   }
4377 
4378   ~ShuffleInstructionBuilder() {
4379     assert((IsFinalized || Mask.empty()) &&
4380            "Must be finalized construction of the shuffles.");
4381   }
4382 };
4383 } // namespace
4384 
4385 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
4386   IRBuilder<>::InsertPointGuard Guard(Builder);
4387 
4388   if (E->VectorizedValue) {
4389     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
4390     return E->VectorizedValue;
4391   }
4392 
4393   ShuffleInstructionBuilder ShuffleBuilder(Builder);
4394   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4395   if (E->State == TreeEntry::NeedToGather) {
4396     setInsertPointAfterBundle(E);
4397     Value *Vec = gather(E->Scalars);
4398     if (NeedToShuffleReuses) {
4399       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4400       Vec = ShuffleBuilder.finalize(Vec);
4401       if (auto *I = dyn_cast<Instruction>(Vec)) {
4402         GatherSeq.insert(I);
4403         CSEBlocks.insert(I->getParent());
4404       }
4405     }
4406     E->VectorizedValue = Vec;
4407     return Vec;
4408   }
4409 
4410   assert((E->State == TreeEntry::Vectorize ||
4411           E->State == TreeEntry::ScatterVectorize) &&
4412          "Unhandled state");
4413   unsigned ShuffleOrOp =
4414       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
4415   Instruction *VL0 = E->getMainOp();
4416   Type *ScalarTy = VL0->getType();
4417   if (auto *Store = dyn_cast<StoreInst>(VL0))
4418     ScalarTy = Store->getValueOperand()->getType();
4419   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
4420   switch (ShuffleOrOp) {
4421     case Instruction::PHI: {
4422       auto *PH = cast<PHINode>(VL0);
4423       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
4424       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
4425       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
4426       Value *V = NewPhi;
4427       if (NeedToShuffleReuses)
4428         V = Builder.CreateShuffleVector(V, E->ReuseShuffleIndices, "shuffle");
4429 
4430       E->VectorizedValue = V;
4431 
4432       // PHINodes may have multiple entries from the same block. We want to
4433       // visit every block once.
4434       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
4435 
4436       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
4437         ValueList Operands;
4438         BasicBlock *IBB = PH->getIncomingBlock(i);
4439 
4440         if (!VisitedBBs.insert(IBB).second) {
4441           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
4442           continue;
4443         }
4444 
4445         Builder.SetInsertPoint(IBB->getTerminator());
4446         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
4447         Value *Vec = vectorizeTree(E->getOperand(i));
4448         NewPhi->addIncoming(Vec, IBB);
4449       }
4450 
4451       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
4452              "Invalid number of incoming values");
4453       return V;
4454     }
4455 
4456     case Instruction::ExtractElement: {
4457       Value *V = E->getSingleOperand(0);
4458       Builder.SetInsertPoint(VL0);
4459       ShuffleBuilder.addInversedMask(E->ReorderIndices);
4460       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4461       V = ShuffleBuilder.finalize(V);
4462       E->VectorizedValue = V;
4463       return V;
4464     }
4465     case Instruction::ExtractValue: {
4466       auto *LI = cast<LoadInst>(E->getSingleOperand(0));
4467       Builder.SetInsertPoint(LI);
4468       auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
4469       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
4470       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
4471       Value *NewV = propagateMetadata(V, E->Scalars);
4472       ShuffleBuilder.addInversedMask(E->ReorderIndices);
4473       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4474       NewV = ShuffleBuilder.finalize(NewV);
4475       E->VectorizedValue = NewV;
4476       return NewV;
4477     }
4478     case Instruction::ZExt:
4479     case Instruction::SExt:
4480     case Instruction::FPToUI:
4481     case Instruction::FPToSI:
4482     case Instruction::FPExt:
4483     case Instruction::PtrToInt:
4484     case Instruction::IntToPtr:
4485     case Instruction::SIToFP:
4486     case Instruction::UIToFP:
4487     case Instruction::Trunc:
4488     case Instruction::FPTrunc:
4489     case Instruction::BitCast: {
4490       setInsertPointAfterBundle(E);
4491 
4492       Value *InVec = vectorizeTree(E->getOperand(0));
4493 
4494       if (E->VectorizedValue) {
4495         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4496         return E->VectorizedValue;
4497       }
4498 
4499       auto *CI = cast<CastInst>(VL0);
4500       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
4501       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4502       V = ShuffleBuilder.finalize(V);
4503 
4504       E->VectorizedValue = V;
4505       ++NumVectorInstructions;
4506       return V;
4507     }
4508     case Instruction::FCmp:
4509     case Instruction::ICmp: {
4510       setInsertPointAfterBundle(E);
4511 
4512       Value *L = vectorizeTree(E->getOperand(0));
4513       Value *R = vectorizeTree(E->getOperand(1));
4514 
4515       if (E->VectorizedValue) {
4516         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4517         return E->VectorizedValue;
4518       }
4519 
4520       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4521       Value *V = Builder.CreateCmp(P0, L, R);
4522       propagateIRFlags(V, E->Scalars, VL0);
4523       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4524       V = ShuffleBuilder.finalize(V);
4525 
4526       E->VectorizedValue = V;
4527       ++NumVectorInstructions;
4528       return V;
4529     }
4530     case Instruction::Select: {
4531       setInsertPointAfterBundle(E);
4532 
4533       Value *Cond = vectorizeTree(E->getOperand(0));
4534       Value *True = vectorizeTree(E->getOperand(1));
4535       Value *False = vectorizeTree(E->getOperand(2));
4536 
4537       if (E->VectorizedValue) {
4538         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4539         return E->VectorizedValue;
4540       }
4541 
4542       Value *V = Builder.CreateSelect(Cond, True, False);
4543       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4544       V = ShuffleBuilder.finalize(V);
4545 
4546       E->VectorizedValue = V;
4547       ++NumVectorInstructions;
4548       return V;
4549     }
4550     case Instruction::FNeg: {
4551       setInsertPointAfterBundle(E);
4552 
4553       Value *Op = vectorizeTree(E->getOperand(0));
4554 
4555       if (E->VectorizedValue) {
4556         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4557         return E->VectorizedValue;
4558       }
4559 
4560       Value *V = Builder.CreateUnOp(
4561           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
4562       propagateIRFlags(V, E->Scalars, VL0);
4563       if (auto *I = dyn_cast<Instruction>(V))
4564         V = propagateMetadata(I, E->Scalars);
4565 
4566       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4567       V = ShuffleBuilder.finalize(V);
4568 
4569       E->VectorizedValue = V;
4570       ++NumVectorInstructions;
4571 
4572       return V;
4573     }
4574     case Instruction::Add:
4575     case Instruction::FAdd:
4576     case Instruction::Sub:
4577     case Instruction::FSub:
4578     case Instruction::Mul:
4579     case Instruction::FMul:
4580     case Instruction::UDiv:
4581     case Instruction::SDiv:
4582     case Instruction::FDiv:
4583     case Instruction::URem:
4584     case Instruction::SRem:
4585     case Instruction::FRem:
4586     case Instruction::Shl:
4587     case Instruction::LShr:
4588     case Instruction::AShr:
4589     case Instruction::And:
4590     case Instruction::Or:
4591     case Instruction::Xor: {
4592       setInsertPointAfterBundle(E);
4593 
4594       Value *LHS = vectorizeTree(E->getOperand(0));
4595       Value *RHS = vectorizeTree(E->getOperand(1));
4596 
4597       if (E->VectorizedValue) {
4598         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4599         return E->VectorizedValue;
4600       }
4601 
4602       Value *V = Builder.CreateBinOp(
4603           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
4604           RHS);
4605       propagateIRFlags(V, E->Scalars, VL0);
4606       if (auto *I = dyn_cast<Instruction>(V))
4607         V = propagateMetadata(I, E->Scalars);
4608 
4609       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4610       V = ShuffleBuilder.finalize(V);
4611 
4612       E->VectorizedValue = V;
4613       ++NumVectorInstructions;
4614 
4615       return V;
4616     }
4617     case Instruction::Load: {
4618       // Loads are inserted at the head of the tree because we don't want to
4619       // sink them all the way down past store instructions.
4620       bool IsReorder = E->updateStateIfReorder();
4621       if (IsReorder)
4622         VL0 = E->getMainOp();
4623       setInsertPointAfterBundle(E);
4624 
4625       LoadInst *LI = cast<LoadInst>(VL0);
4626       Instruction *NewLI;
4627       unsigned AS = LI->getPointerAddressSpace();
4628       Value *PO = LI->getPointerOperand();
4629       if (E->State == TreeEntry::Vectorize) {
4630 
4631         Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
4632 
4633         // The pointer operand uses an in-tree scalar so we add the new BitCast
4634         // to ExternalUses list to make sure that an extract will be generated
4635         // in the future.
4636         if (getTreeEntry(PO))
4637           ExternalUses.emplace_back(PO, cast<User>(VecPtr), 0);
4638 
4639         NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
4640       } else {
4641         assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
4642         Value *VecPtr = vectorizeTree(E->getOperand(0));
4643         // Use the minimum alignment of the gathered loads.
4644         Align CommonAlignment = LI->getAlign();
4645         for (Value *V : E->Scalars)
4646           CommonAlignment =
4647               commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
4648         NewLI = Builder.CreateMaskedGather(VecPtr, CommonAlignment);
4649       }
4650       Value *V = propagateMetadata(NewLI, E->Scalars);
4651 
4652       ShuffleBuilder.addInversedMask(E->ReorderIndices);
4653       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4654       V = ShuffleBuilder.finalize(V);
4655       E->VectorizedValue = V;
4656       ++NumVectorInstructions;
4657       return V;
4658     }
4659     case Instruction::Store: {
4660       bool IsReorder = !E->ReorderIndices.empty();
4661       auto *SI = cast<StoreInst>(
4662           IsReorder ? E->Scalars[E->ReorderIndices.front()] : VL0);
4663       unsigned AS = SI->getPointerAddressSpace();
4664 
4665       setInsertPointAfterBundle(E);
4666 
4667       Value *VecValue = vectorizeTree(E->getOperand(0));
4668       ShuffleBuilder.addMask(E->ReorderIndices);
4669       VecValue = ShuffleBuilder.finalize(VecValue);
4670 
4671       Value *ScalarPtr = SI->getPointerOperand();
4672       Value *VecPtr = Builder.CreateBitCast(
4673           ScalarPtr, VecValue->getType()->getPointerTo(AS));
4674       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
4675                                                  SI->getAlign());
4676 
4677       // The pointer operand uses an in-tree scalar, so add the new BitCast to
4678       // ExternalUses to make sure that an extract will be generated in the
4679       // future.
4680       if (getTreeEntry(ScalarPtr))
4681         ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
4682 
4683       Value *V = propagateMetadata(ST, E->Scalars);
4684 
4685       E->VectorizedValue = V;
4686       ++NumVectorInstructions;
4687       return V;
4688     }
4689     case Instruction::GetElementPtr: {
4690       setInsertPointAfterBundle(E);
4691 
4692       Value *Op0 = vectorizeTree(E->getOperand(0));
4693 
4694       std::vector<Value *> OpVecs;
4695       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
4696            ++j) {
4697         ValueList &VL = E->getOperand(j);
4698         // Need to cast all elements to the same type before vectorization to
4699         // avoid crash.
4700         Type *VL0Ty = VL0->getOperand(j)->getType();
4701         Type *Ty = llvm::all_of(
4702                        VL, [VL0Ty](Value *V) { return VL0Ty == V->getType(); })
4703                        ? VL0Ty
4704                        : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4705                                               ->getPointerOperandType()
4706                                               ->getScalarType());
4707         for (Value *&V : VL) {
4708           auto *CI = cast<ConstantInt>(V);
4709           V = ConstantExpr::getIntegerCast(CI, Ty,
4710                                            CI->getValue().isSignBitSet());
4711         }
4712         Value *OpVec = vectorizeTree(VL);
4713         OpVecs.push_back(OpVec);
4714       }
4715 
4716       Value *V = Builder.CreateGEP(
4717           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
4718       if (Instruction *I = dyn_cast<Instruction>(V))
4719         V = propagateMetadata(I, E->Scalars);
4720 
4721       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4722       V = ShuffleBuilder.finalize(V);
4723 
4724       E->VectorizedValue = V;
4725       ++NumVectorInstructions;
4726 
4727       return V;
4728     }
4729     case Instruction::Call: {
4730       CallInst *CI = cast<CallInst>(VL0);
4731       setInsertPointAfterBundle(E);
4732 
4733       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
4734       if (Function *FI = CI->getCalledFunction())
4735         IID = FI->getIntrinsicID();
4736 
4737       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4738 
4739       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
4740       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
4741                           VecCallCosts.first <= VecCallCosts.second;
4742 
4743       Value *ScalarArg = nullptr;
4744       std::vector<Value *> OpVecs;
4745       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
4746         ValueList OpVL;
4747         // Some intrinsics have scalar arguments. This argument should not be
4748         // vectorized.
4749         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
4750           CallInst *CEI = cast<CallInst>(VL0);
4751           ScalarArg = CEI->getArgOperand(j);
4752           OpVecs.push_back(CEI->getArgOperand(j));
4753           continue;
4754         }
4755 
4756         Value *OpVec = vectorizeTree(E->getOperand(j));
4757         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
4758         OpVecs.push_back(OpVec);
4759       }
4760 
4761       Function *CF;
4762       if (!UseIntrinsic) {
4763         VFShape Shape =
4764             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4765                                   VecTy->getNumElements())),
4766                          false /*HasGlobalPred*/);
4767         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
4768       } else {
4769         Type *Tys[] = {FixedVectorType::get(CI->getType(), E->Scalars.size())};
4770         CF = Intrinsic::getDeclaration(F->getParent(), ID, Tys);
4771       }
4772 
4773       SmallVector<OperandBundleDef, 1> OpBundles;
4774       CI->getOperandBundlesAsDefs(OpBundles);
4775       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
4776 
4777       // The scalar argument uses an in-tree scalar so we add the new vectorized
4778       // call to ExternalUses list to make sure that an extract will be
4779       // generated in the future.
4780       if (ScalarArg && getTreeEntry(ScalarArg))
4781         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
4782 
4783       propagateIRFlags(V, E->Scalars, VL0);
4784       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4785       V = ShuffleBuilder.finalize(V);
4786 
4787       E->VectorizedValue = V;
4788       ++NumVectorInstructions;
4789       return V;
4790     }
4791     case Instruction::ShuffleVector: {
4792       assert(E->isAltShuffle() &&
4793              ((Instruction::isBinaryOp(E->getOpcode()) &&
4794                Instruction::isBinaryOp(E->getAltOpcode())) ||
4795               (Instruction::isCast(E->getOpcode()) &&
4796                Instruction::isCast(E->getAltOpcode()))) &&
4797              "Invalid Shuffle Vector Operand");
4798 
4799       Value *LHS = nullptr, *RHS = nullptr;
4800       if (Instruction::isBinaryOp(E->getOpcode())) {
4801         setInsertPointAfterBundle(E);
4802         LHS = vectorizeTree(E->getOperand(0));
4803         RHS = vectorizeTree(E->getOperand(1));
4804       } else {
4805         setInsertPointAfterBundle(E);
4806         LHS = vectorizeTree(E->getOperand(0));
4807       }
4808 
4809       if (E->VectorizedValue) {
4810         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4811         return E->VectorizedValue;
4812       }
4813 
4814       Value *V0, *V1;
4815       if (Instruction::isBinaryOp(E->getOpcode())) {
4816         V0 = Builder.CreateBinOp(
4817             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
4818         V1 = Builder.CreateBinOp(
4819             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
4820       } else {
4821         V0 = Builder.CreateCast(
4822             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
4823         V1 = Builder.CreateCast(
4824             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
4825       }
4826 
4827       // Create shuffle to take alternate operations from the vector.
4828       // Also, gather up main and alt scalar ops to propagate IR flags to
4829       // each vector operation.
4830       ValueList OpScalars, AltScalars;
4831       unsigned e = E->Scalars.size();
4832       SmallVector<int, 8> Mask(e);
4833       for (unsigned i = 0; i < e; ++i) {
4834         auto *OpInst = cast<Instruction>(E->Scalars[i]);
4835         assert(E->isOpcodeOrAlt(OpInst) && "Unexpected main/alternate opcode");
4836         if (OpInst->getOpcode() == E->getAltOpcode()) {
4837           Mask[i] = e + i;
4838           AltScalars.push_back(E->Scalars[i]);
4839         } else {
4840           Mask[i] = i;
4841           OpScalars.push_back(E->Scalars[i]);
4842         }
4843       }
4844 
4845       propagateIRFlags(V0, OpScalars);
4846       propagateIRFlags(V1, AltScalars);
4847 
4848       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
4849       if (Instruction *I = dyn_cast<Instruction>(V))
4850         V = propagateMetadata(I, E->Scalars);
4851       ShuffleBuilder.addMask(E->ReuseShuffleIndices);
4852       V = ShuffleBuilder.finalize(V);
4853 
4854       E->VectorizedValue = V;
4855       ++NumVectorInstructions;
4856 
4857       return V;
4858     }
4859     default:
4860     llvm_unreachable("unknown inst");
4861   }
4862   return nullptr;
4863 }
4864 
4865 Value *BoUpSLP::vectorizeTree() {
4866   ExtraValueToDebugLocsMap ExternallyUsedValues;
4867   return vectorizeTree(ExternallyUsedValues);
4868 }
4869 
4870 Value *
4871 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4872   // All blocks must be scheduled before any instructions are inserted.
4873   for (auto &BSIter : BlocksSchedules) {
4874     scheduleBlock(BSIter.second.get());
4875   }
4876 
4877   Builder.SetInsertPoint(&F->getEntryBlock().front());
4878   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
4879 
4880   // If the vectorized tree can be rewritten in a smaller type, we truncate the
4881   // vectorized root. InstCombine will then rewrite the entire expression. We
4882   // sign extend the extracted values below.
4883   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
4884   if (MinBWs.count(ScalarRoot)) {
4885     if (auto *I = dyn_cast<Instruction>(VectorRoot))
4886       Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
4887     auto BundleWidth = VectorizableTree[0]->Scalars.size();
4888     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
4889     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
4890     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
4891     VectorizableTree[0]->VectorizedValue = Trunc;
4892   }
4893 
4894   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
4895                     << " values .\n");
4896 
4897   // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
4898   // specified by ScalarType.
4899   auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
4900     if (!MinBWs.count(ScalarRoot))
4901       return Ex;
4902     if (MinBWs[ScalarRoot].second)
4903       return Builder.CreateSExt(Ex, ScalarType);
4904     return Builder.CreateZExt(Ex, ScalarType);
4905   };
4906 
4907   // Extract all of the elements with the external uses.
4908   for (const auto &ExternalUse : ExternalUses) {
4909     Value *Scalar = ExternalUse.Scalar;
4910     llvm::User *User = ExternalUse.User;
4911 
4912     // Skip users that we already RAUW. This happens when one instruction
4913     // has multiple uses of the same value.
4914     if (User && !is_contained(Scalar->users(), User))
4915       continue;
4916     TreeEntry *E = getTreeEntry(Scalar);
4917     assert(E && "Invalid scalar");
4918     assert(E->State != TreeEntry::NeedToGather &&
4919            "Extracting from a gather list");
4920 
4921     Value *Vec = E->VectorizedValue;
4922     assert(Vec && "Can't find vectorizable value");
4923 
4924     Value *Lane = Builder.getInt32(ExternalUse.Lane);
4925     // If User == nullptr, the Scalar is used as extra arg. Generate
4926     // ExtractElement instruction and update the record for this scalar in
4927     // ExternallyUsedValues.
4928     if (!User) {
4929       assert(ExternallyUsedValues.count(Scalar) &&
4930              "Scalar with nullptr as an external user must be registered in "
4931              "ExternallyUsedValues map");
4932       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
4933         Builder.SetInsertPoint(VecI->getParent(),
4934                                std::next(VecI->getIterator()));
4935       } else {
4936         Builder.SetInsertPoint(&F->getEntryBlock().front());
4937       }
4938       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4939       Ex = extend(ScalarRoot, Ex, Scalar->getType());
4940       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
4941       auto &Locs = ExternallyUsedValues[Scalar];
4942       ExternallyUsedValues.insert({Ex, Locs});
4943       ExternallyUsedValues.erase(Scalar);
4944       // Required to update internally referenced instructions.
4945       Scalar->replaceAllUsesWith(Ex);
4946       continue;
4947     }
4948 
4949     // Generate extracts for out-of-tree users.
4950     // Find the insertion point for the extractelement lane.
4951     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
4952       if (PHINode *PH = dyn_cast<PHINode>(User)) {
4953         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
4954           if (PH->getIncomingValue(i) == Scalar) {
4955             Instruction *IncomingTerminator =
4956                 PH->getIncomingBlock(i)->getTerminator();
4957             if (isa<CatchSwitchInst>(IncomingTerminator)) {
4958               Builder.SetInsertPoint(VecI->getParent(),
4959                                      std::next(VecI->getIterator()));
4960             } else {
4961               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
4962             }
4963             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4964             Ex = extend(ScalarRoot, Ex, Scalar->getType());
4965             CSEBlocks.insert(PH->getIncomingBlock(i));
4966             PH->setOperand(i, Ex);
4967           }
4968         }
4969       } else {
4970         Builder.SetInsertPoint(cast<Instruction>(User));
4971         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4972         Ex = extend(ScalarRoot, Ex, Scalar->getType());
4973         CSEBlocks.insert(cast<Instruction>(User)->getParent());
4974         User->replaceUsesOfWith(Scalar, Ex);
4975       }
4976     } else {
4977       Builder.SetInsertPoint(&F->getEntryBlock().front());
4978       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4979       Ex = extend(ScalarRoot, Ex, Scalar->getType());
4980       CSEBlocks.insert(&F->getEntryBlock());
4981       User->replaceUsesOfWith(Scalar, Ex);
4982     }
4983 
4984     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
4985   }
4986 
4987   // For each vectorized value:
4988   for (auto &TEPtr : VectorizableTree) {
4989     TreeEntry *Entry = TEPtr.get();
4990 
4991     // No need to handle users of gathered values.
4992     if (Entry->State == TreeEntry::NeedToGather)
4993       continue;
4994 
4995     assert(Entry->VectorizedValue && "Can't find vectorizable value");
4996 
4997     // For each lane:
4998     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4999       Value *Scalar = Entry->Scalars[Lane];
5000 
5001 #ifndef NDEBUG
5002       Type *Ty = Scalar->getType();
5003       if (!Ty->isVoidTy()) {
5004         for (User *U : Scalar->users()) {
5005           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
5006 
5007           // It is legal to delete users in the ignorelist.
5008           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
5009                  "Deleting out-of-tree value");
5010         }
5011       }
5012 #endif
5013       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
5014       eraseInstruction(cast<Instruction>(Scalar));
5015     }
5016   }
5017 
5018   Builder.ClearInsertionPoint();
5019   InstrElementSize.clear();
5020 
5021   return VectorizableTree[0]->VectorizedValue;
5022 }
5023 
5024 void BoUpSLP::optimizeGatherSequence() {
5025   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
5026                     << " gather sequences instructions.\n");
5027   // LICM InsertElementInst sequences.
5028   for (Instruction *I : GatherSeq) {
5029     if (isDeleted(I))
5030       continue;
5031 
5032     // Check if this block is inside a loop.
5033     Loop *L = LI->getLoopFor(I->getParent());
5034     if (!L)
5035       continue;
5036 
5037     // Check if it has a preheader.
5038     BasicBlock *PreHeader = L->getLoopPreheader();
5039     if (!PreHeader)
5040       continue;
5041 
5042     // If the vector or the element that we insert into it are
5043     // instructions that are defined in this basic block then we can't
5044     // hoist this instruction.
5045     auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
5046     auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
5047     if (Op0 && L->contains(Op0))
5048       continue;
5049     if (Op1 && L->contains(Op1))
5050       continue;
5051 
5052     // We can hoist this instruction. Move it to the pre-header.
5053     I->moveBefore(PreHeader->getTerminator());
5054   }
5055 
5056   // Make a list of all reachable blocks in our CSE queue.
5057   SmallVector<const DomTreeNode *, 8> CSEWorkList;
5058   CSEWorkList.reserve(CSEBlocks.size());
5059   for (BasicBlock *BB : CSEBlocks)
5060     if (DomTreeNode *N = DT->getNode(BB)) {
5061       assert(DT->isReachableFromEntry(N));
5062       CSEWorkList.push_back(N);
5063     }
5064 
5065   // Sort blocks by domination. This ensures we visit a block after all blocks
5066   // dominating it are visited.
5067   llvm::stable_sort(CSEWorkList,
5068                     [this](const DomTreeNode *A, const DomTreeNode *B) {
5069                       return DT->properlyDominates(A, B);
5070                     });
5071 
5072   // Perform O(N^2) search over the gather sequences and merge identical
5073   // instructions. TODO: We can further optimize this scan if we split the
5074   // instructions into different buckets based on the insert lane.
5075   SmallVector<Instruction *, 16> Visited;
5076   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
5077     assert(*I &&
5078            (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
5079            "Worklist not sorted properly!");
5080     BasicBlock *BB = (*I)->getBlock();
5081     // For all instructions in blocks containing gather sequences:
5082     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
5083       Instruction *In = &*it++;
5084       if (isDeleted(In))
5085         continue;
5086       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
5087         continue;
5088 
5089       // Check if we can replace this instruction with any of the
5090       // visited instructions.
5091       for (Instruction *v : Visited) {
5092         if (In->isIdenticalTo(v) &&
5093             DT->dominates(v->getParent(), In->getParent())) {
5094           In->replaceAllUsesWith(v);
5095           eraseInstruction(In);
5096           In = nullptr;
5097           break;
5098         }
5099       }
5100       if (In) {
5101         assert(!is_contained(Visited, In));
5102         Visited.push_back(In);
5103       }
5104     }
5105   }
5106   CSEBlocks.clear();
5107   GatherSeq.clear();
5108 }
5109 
5110 // Groups the instructions to a bundle (which is then a single scheduling entity)
5111 // and schedules instructions until the bundle gets ready.
5112 Optional<BoUpSLP::ScheduleData *>
5113 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
5114                                             const InstructionsState &S) {
5115   if (isa<PHINode>(S.OpValue))
5116     return nullptr;
5117 
5118   // Initialize the instruction bundle.
5119   Instruction *OldScheduleEnd = ScheduleEnd;
5120   ScheduleData *PrevInBundle = nullptr;
5121   ScheduleData *Bundle = nullptr;
5122   bool ReSchedule = false;
5123   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
5124 
5125   // Make sure that the scheduling region contains all
5126   // instructions of the bundle.
5127   for (Value *V : VL) {
5128     if (!extendSchedulingRegion(V, S))
5129       return None;
5130   }
5131 
5132   for (Value *V : VL) {
5133     ScheduleData *BundleMember = getScheduleData(V);
5134     assert(BundleMember &&
5135            "no ScheduleData for bundle member (maybe not in same basic block)");
5136     if (BundleMember->IsScheduled) {
5137       // A bundle member was scheduled as single instruction before and now
5138       // needs to be scheduled as part of the bundle. We just get rid of the
5139       // existing schedule.
5140       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
5141                         << " was already scheduled\n");
5142       ReSchedule = true;
5143     }
5144     assert(BundleMember->isSchedulingEntity() &&
5145            "bundle member already part of other bundle");
5146     if (PrevInBundle) {
5147       PrevInBundle->NextInBundle = BundleMember;
5148     } else {
5149       Bundle = BundleMember;
5150     }
5151     BundleMember->UnscheduledDepsInBundle = 0;
5152     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
5153 
5154     // Group the instructions to a bundle.
5155     BundleMember->FirstInBundle = Bundle;
5156     PrevInBundle = BundleMember;
5157   }
5158   if (ScheduleEnd != OldScheduleEnd) {
5159     // The scheduling region got new instructions at the lower end (or it is a
5160     // new region for the first bundle). This makes it necessary to
5161     // recalculate all dependencies.
5162     // It is seldom that this needs to be done a second time after adding the
5163     // initial bundle to the region.
5164     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
5165       doForAllOpcodes(I, [](ScheduleData *SD) {
5166         SD->clearDependencies();
5167       });
5168     }
5169     ReSchedule = true;
5170   }
5171   if (ReSchedule) {
5172     resetSchedule();
5173     initialFillReadyList(ReadyInsts);
5174   }
5175   assert(Bundle && "Failed to find schedule bundle");
5176 
5177   LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
5178                     << BB->getName() << "\n");
5179 
5180   calculateDependencies(Bundle, true, SLP);
5181 
5182   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
5183   // means that there are no cyclic dependencies and we can schedule it.
5184   // Note that's important that we don't "schedule" the bundle yet (see
5185   // cancelScheduling).
5186   while (!Bundle->isReady() && !ReadyInsts.empty()) {
5187 
5188     ScheduleData *pickedSD = ReadyInsts.back();
5189     ReadyInsts.pop_back();
5190 
5191     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
5192       schedule(pickedSD, ReadyInsts);
5193     }
5194   }
5195   if (!Bundle->isReady()) {
5196     cancelScheduling(VL, S.OpValue);
5197     return None;
5198   }
5199   return Bundle;
5200 }
5201 
5202 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
5203                                                 Value *OpValue) {
5204   if (isa<PHINode>(OpValue))
5205     return;
5206 
5207   ScheduleData *Bundle = getScheduleData(OpValue);
5208   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
5209   assert(!Bundle->IsScheduled &&
5210          "Can't cancel bundle which is already scheduled");
5211   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
5212          "tried to unbundle something which is not a bundle");
5213 
5214   // Un-bundle: make single instructions out of the bundle.
5215   ScheduleData *BundleMember = Bundle;
5216   while (BundleMember) {
5217     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
5218     BundleMember->FirstInBundle = BundleMember;
5219     ScheduleData *Next = BundleMember->NextInBundle;
5220     BundleMember->NextInBundle = nullptr;
5221     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
5222     if (BundleMember->UnscheduledDepsInBundle == 0) {
5223       ReadyInsts.insert(BundleMember);
5224     }
5225     BundleMember = Next;
5226   }
5227 }
5228 
5229 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
5230   // Allocate a new ScheduleData for the instruction.
5231   if (ChunkPos >= ChunkSize) {
5232     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
5233     ChunkPos = 0;
5234   }
5235   return &(ScheduleDataChunks.back()[ChunkPos++]);
5236 }
5237 
5238 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
5239                                                       const InstructionsState &S) {
5240   if (getScheduleData(V, isOneOf(S, V)))
5241     return true;
5242   Instruction *I = dyn_cast<Instruction>(V);
5243   assert(I && "bundle member must be an instruction");
5244   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
5245   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
5246     ScheduleData *ISD = getScheduleData(I);
5247     if (!ISD)
5248       return false;
5249     assert(isInSchedulingRegion(ISD) &&
5250            "ScheduleData not in scheduling region");
5251     ScheduleData *SD = allocateScheduleDataChunks();
5252     SD->Inst = I;
5253     SD->init(SchedulingRegionID, S.OpValue);
5254     ExtraScheduleDataMap[I][S.OpValue] = SD;
5255     return true;
5256   };
5257   if (CheckSheduleForI(I))
5258     return true;
5259   if (!ScheduleStart) {
5260     // It's the first instruction in the new region.
5261     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
5262     ScheduleStart = I;
5263     ScheduleEnd = I->getNextNode();
5264     if (isOneOf(S, I) != I)
5265       CheckSheduleForI(I);
5266     assert(ScheduleEnd && "tried to vectorize a terminator?");
5267     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
5268     return true;
5269   }
5270   // Search up and down at the same time, because we don't know if the new
5271   // instruction is above or below the existing scheduling region.
5272   BasicBlock::reverse_iterator UpIter =
5273       ++ScheduleStart->getIterator().getReverse();
5274   BasicBlock::reverse_iterator UpperEnd = BB->rend();
5275   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
5276   BasicBlock::iterator LowerEnd = BB->end();
5277   while (true) {
5278     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
5279       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
5280       return false;
5281     }
5282 
5283     if (UpIter != UpperEnd) {
5284       if (&*UpIter == I) {
5285         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
5286         ScheduleStart = I;
5287         if (isOneOf(S, I) != I)
5288           CheckSheduleForI(I);
5289         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
5290                           << "\n");
5291         return true;
5292       }
5293       ++UpIter;
5294     }
5295     if (DownIter != LowerEnd) {
5296       if (&*DownIter == I) {
5297         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
5298                          nullptr);
5299         ScheduleEnd = I->getNextNode();
5300         if (isOneOf(S, I) != I)
5301           CheckSheduleForI(I);
5302         assert(ScheduleEnd && "tried to vectorize a terminator?");
5303         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I
5304                           << "\n");
5305         return true;
5306       }
5307       ++DownIter;
5308     }
5309     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
5310            "instruction not found in block");
5311   }
5312   return true;
5313 }
5314 
5315 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
5316                                                 Instruction *ToI,
5317                                                 ScheduleData *PrevLoadStore,
5318                                                 ScheduleData *NextLoadStore) {
5319   ScheduleData *CurrentLoadStore = PrevLoadStore;
5320   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
5321     ScheduleData *SD = ScheduleDataMap[I];
5322     if (!SD) {
5323       SD = allocateScheduleDataChunks();
5324       ScheduleDataMap[I] = SD;
5325       SD->Inst = I;
5326     }
5327     assert(!isInSchedulingRegion(SD) &&
5328            "new ScheduleData already in scheduling region");
5329     SD->init(SchedulingRegionID, I);
5330 
5331     if (I->mayReadOrWriteMemory() &&
5332         (!isa<IntrinsicInst>(I) ||
5333          (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
5334           cast<IntrinsicInst>(I)->getIntrinsicID() !=
5335               Intrinsic::pseudoprobe))) {
5336       // Update the linked list of memory accessing instructions.
5337       if (CurrentLoadStore) {
5338         CurrentLoadStore->NextLoadStore = SD;
5339       } else {
5340         FirstLoadStoreInRegion = SD;
5341       }
5342       CurrentLoadStore = SD;
5343     }
5344   }
5345   if (NextLoadStore) {
5346     if (CurrentLoadStore)
5347       CurrentLoadStore->NextLoadStore = NextLoadStore;
5348   } else {
5349     LastLoadStoreInRegion = CurrentLoadStore;
5350   }
5351 }
5352 
5353 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
5354                                                      bool InsertInReadyList,
5355                                                      BoUpSLP *SLP) {
5356   assert(SD->isSchedulingEntity());
5357 
5358   SmallVector<ScheduleData *, 10> WorkList;
5359   WorkList.push_back(SD);
5360 
5361   while (!WorkList.empty()) {
5362     ScheduleData *SD = WorkList.back();
5363     WorkList.pop_back();
5364 
5365     ScheduleData *BundleMember = SD;
5366     while (BundleMember) {
5367       assert(isInSchedulingRegion(BundleMember));
5368       if (!BundleMember->hasValidDependencies()) {
5369 
5370         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
5371                           << "\n");
5372         BundleMember->Dependencies = 0;
5373         BundleMember->resetUnscheduledDeps();
5374 
5375         // Handle def-use chain dependencies.
5376         if (BundleMember->OpValue != BundleMember->Inst) {
5377           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
5378           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
5379             BundleMember->Dependencies++;
5380             ScheduleData *DestBundle = UseSD->FirstInBundle;
5381             if (!DestBundle->IsScheduled)
5382               BundleMember->incrementUnscheduledDeps(1);
5383             if (!DestBundle->hasValidDependencies())
5384               WorkList.push_back(DestBundle);
5385           }
5386         } else {
5387           for (User *U : BundleMember->Inst->users()) {
5388             if (isa<Instruction>(U)) {
5389               ScheduleData *UseSD = getScheduleData(U);
5390               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
5391                 BundleMember->Dependencies++;
5392                 ScheduleData *DestBundle = UseSD->FirstInBundle;
5393                 if (!DestBundle->IsScheduled)
5394                   BundleMember->incrementUnscheduledDeps(1);
5395                 if (!DestBundle->hasValidDependencies())
5396                   WorkList.push_back(DestBundle);
5397               }
5398             } else {
5399               // I'm not sure if this can ever happen. But we need to be safe.
5400               // This lets the instruction/bundle never be scheduled and
5401               // eventually disable vectorization.
5402               BundleMember->Dependencies++;
5403               BundleMember->incrementUnscheduledDeps(1);
5404             }
5405           }
5406         }
5407 
5408         // Handle the memory dependencies.
5409         ScheduleData *DepDest = BundleMember->NextLoadStore;
5410         if (DepDest) {
5411           Instruction *SrcInst = BundleMember->Inst;
5412           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
5413           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
5414           unsigned numAliased = 0;
5415           unsigned DistToSrc = 1;
5416 
5417           while (DepDest) {
5418             assert(isInSchedulingRegion(DepDest));
5419 
5420             // We have two limits to reduce the complexity:
5421             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
5422             //    SLP->isAliased (which is the expensive part in this loop).
5423             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
5424             //    the whole loop (even if the loop is fast, it's quadratic).
5425             //    It's important for the loop break condition (see below) to
5426             //    check this limit even between two read-only instructions.
5427             if (DistToSrc >= MaxMemDepDistance ||
5428                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
5429                      (numAliased >= AliasedCheckLimit ||
5430                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
5431 
5432               // We increment the counter only if the locations are aliased
5433               // (instead of counting all alias checks). This gives a better
5434               // balance between reduced runtime and accurate dependencies.
5435               numAliased++;
5436 
5437               DepDest->MemoryDependencies.push_back(BundleMember);
5438               BundleMember->Dependencies++;
5439               ScheduleData *DestBundle = DepDest->FirstInBundle;
5440               if (!DestBundle->IsScheduled) {
5441                 BundleMember->incrementUnscheduledDeps(1);
5442               }
5443               if (!DestBundle->hasValidDependencies()) {
5444                 WorkList.push_back(DestBundle);
5445               }
5446             }
5447             DepDest = DepDest->NextLoadStore;
5448 
5449             // Example, explaining the loop break condition: Let's assume our
5450             // starting instruction is i0 and MaxMemDepDistance = 3.
5451             //
5452             //                      +--------v--v--v
5453             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
5454             //             +--------^--^--^
5455             //
5456             // MaxMemDepDistance let us stop alias-checking at i3 and we add
5457             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
5458             // Previously we already added dependencies from i3 to i6,i7,i8
5459             // (because of MaxMemDepDistance). As we added a dependency from
5460             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
5461             // and we can abort this loop at i6.
5462             if (DistToSrc >= 2 * MaxMemDepDistance)
5463               break;
5464             DistToSrc++;
5465           }
5466         }
5467       }
5468       BundleMember = BundleMember->NextInBundle;
5469     }
5470     if (InsertInReadyList && SD->isReady()) {
5471       ReadyInsts.push_back(SD);
5472       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
5473                         << "\n");
5474     }
5475   }
5476 }
5477 
5478 void BoUpSLP::BlockScheduling::resetSchedule() {
5479   assert(ScheduleStart &&
5480          "tried to reset schedule on block which has not been scheduled");
5481   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
5482     doForAllOpcodes(I, [&](ScheduleData *SD) {
5483       assert(isInSchedulingRegion(SD) &&
5484              "ScheduleData not in scheduling region");
5485       SD->IsScheduled = false;
5486       SD->resetUnscheduledDeps();
5487     });
5488   }
5489   ReadyInsts.clear();
5490 }
5491 
5492 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
5493   if (!BS->ScheduleStart)
5494     return;
5495 
5496   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
5497 
5498   BS->resetSchedule();
5499 
5500   // For the real scheduling we use a more sophisticated ready-list: it is
5501   // sorted by the original instruction location. This lets the final schedule
5502   // be as  close as possible to the original instruction order.
5503   struct ScheduleDataCompare {
5504     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
5505       return SD2->SchedulingPriority < SD1->SchedulingPriority;
5506     }
5507   };
5508   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
5509 
5510   // Ensure that all dependency data is updated and fill the ready-list with
5511   // initial instructions.
5512   int Idx = 0;
5513   int NumToSchedule = 0;
5514   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
5515        I = I->getNextNode()) {
5516     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
5517       assert(SD->isPartOfBundle() ==
5518                  (getTreeEntry(SD->Inst) != nullptr) &&
5519              "scheduler and vectorizer bundle mismatch");
5520       SD->FirstInBundle->SchedulingPriority = Idx++;
5521       if (SD->isSchedulingEntity()) {
5522         BS->calculateDependencies(SD, false, this);
5523         NumToSchedule++;
5524       }
5525     });
5526   }
5527   BS->initialFillReadyList(ReadyInsts);
5528 
5529   Instruction *LastScheduledInst = BS->ScheduleEnd;
5530 
5531   // Do the "real" scheduling.
5532   while (!ReadyInsts.empty()) {
5533     ScheduleData *picked = *ReadyInsts.begin();
5534     ReadyInsts.erase(ReadyInsts.begin());
5535 
5536     // Move the scheduled instruction(s) to their dedicated places, if not
5537     // there yet.
5538     ScheduleData *BundleMember = picked;
5539     while (BundleMember) {
5540       Instruction *pickedInst = BundleMember->Inst;
5541       if (LastScheduledInst->getNextNode() != pickedInst) {
5542         BS->BB->getInstList().remove(pickedInst);
5543         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
5544                                      pickedInst);
5545       }
5546       LastScheduledInst = pickedInst;
5547       BundleMember = BundleMember->NextInBundle;
5548     }
5549 
5550     BS->schedule(picked, ReadyInsts);
5551     NumToSchedule--;
5552   }
5553   assert(NumToSchedule == 0 && "could not schedule all instructions");
5554 
5555   // Avoid duplicate scheduling of the block.
5556   BS->ScheduleStart = nullptr;
5557 }
5558 
5559 unsigned BoUpSLP::getVectorElementSize(Value *V) {
5560   // If V is a store, just return the width of the stored value (or value
5561   // truncated just before storing) without traversing the expression tree.
5562   // This is the common case.
5563   if (auto *Store = dyn_cast<StoreInst>(V)) {
5564     if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
5565       return DL->getTypeSizeInBits(Trunc->getSrcTy());
5566     else
5567       return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
5568   }
5569 
5570   auto E = InstrElementSize.find(V);
5571   if (E != InstrElementSize.end())
5572     return E->second;
5573 
5574   // If V is not a store, we can traverse the expression tree to find loads
5575   // that feed it. The type of the loaded value may indicate a more suitable
5576   // width than V's type. We want to base the vector element size on the width
5577   // of memory operations where possible.
5578   SmallVector<Instruction *, 16> Worklist;
5579   SmallPtrSet<Instruction *, 16> Visited;
5580   if (auto *I = dyn_cast<Instruction>(V)) {
5581     Worklist.push_back(I);
5582     Visited.insert(I);
5583   }
5584 
5585   // Traverse the expression tree in bottom-up order looking for loads. If we
5586   // encounter an instruction we don't yet handle, we give up.
5587   auto MaxWidth = 0u;
5588   auto FoundUnknownInst = false;
5589   while (!Worklist.empty() && !FoundUnknownInst) {
5590     auto *I = Worklist.pop_back_val();
5591 
5592     // We should only be looking at scalar instructions here. If the current
5593     // instruction has a vector type, give up.
5594     auto *Ty = I->getType();
5595     if (isa<VectorType>(Ty))
5596       FoundUnknownInst = true;
5597 
5598     // If the current instruction is a load, update MaxWidth to reflect the
5599     // width of the loaded value.
5600     else if (isa<LoadInst>(I))
5601       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
5602 
5603     // Otherwise, we need to visit the operands of the instruction. We only
5604     // handle the interesting cases from buildTree here. If an operand is an
5605     // instruction we haven't yet visited, we add it to the worklist.
5606     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5607              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
5608       for (Use &U : I->operands())
5609         if (auto *J = dyn_cast<Instruction>(U.get()))
5610           if (Visited.insert(J).second)
5611             Worklist.push_back(J);
5612     }
5613 
5614     // If we don't yet handle the instruction, give up.
5615     else
5616       FoundUnknownInst = true;
5617   }
5618 
5619   int Width = MaxWidth;
5620   // If we didn't encounter a memory access in the expression tree, or if we
5621   // gave up for some reason, just return the width of V. Otherwise, return the
5622   // maximum width we found.
5623   if (!MaxWidth || FoundUnknownInst)
5624     Width = DL->getTypeSizeInBits(V->getType());
5625 
5626   for (Instruction *I : Visited)
5627     InstrElementSize[I] = Width;
5628 
5629   return Width;
5630 }
5631 
5632 // Determine if a value V in a vectorizable expression Expr can be demoted to a
5633 // smaller type with a truncation. We collect the values that will be demoted
5634 // in ToDemote and additional roots that require investigating in Roots.
5635 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
5636                                   SmallVectorImpl<Value *> &ToDemote,
5637                                   SmallVectorImpl<Value *> &Roots) {
5638   // We can always demote constants.
5639   if (isa<Constant>(V)) {
5640     ToDemote.push_back(V);
5641     return true;
5642   }
5643 
5644   // If the value is not an instruction in the expression with only one use, it
5645   // cannot be demoted.
5646   auto *I = dyn_cast<Instruction>(V);
5647   if (!I || !I->hasOneUse() || !Expr.count(I))
5648     return false;
5649 
5650   switch (I->getOpcode()) {
5651 
5652   // We can always demote truncations and extensions. Since truncations can
5653   // seed additional demotion, we save the truncated value.
5654   case Instruction::Trunc:
5655     Roots.push_back(I->getOperand(0));
5656     break;
5657   case Instruction::ZExt:
5658   case Instruction::SExt:
5659     break;
5660 
5661   // We can demote certain binary operations if we can demote both of their
5662   // operands.
5663   case Instruction::Add:
5664   case Instruction::Sub:
5665   case Instruction::Mul:
5666   case Instruction::And:
5667   case Instruction::Or:
5668   case Instruction::Xor:
5669     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
5670         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
5671       return false;
5672     break;
5673 
5674   // We can demote selects if we can demote their true and false values.
5675   case Instruction::Select: {
5676     SelectInst *SI = cast<SelectInst>(I);
5677     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
5678         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
5679       return false;
5680     break;
5681   }
5682 
5683   // We can demote phis if we can demote all their incoming operands. Note that
5684   // we don't need to worry about cycles since we ensure single use above.
5685   case Instruction::PHI: {
5686     PHINode *PN = cast<PHINode>(I);
5687     for (Value *IncValue : PN->incoming_values())
5688       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
5689         return false;
5690     break;
5691   }
5692 
5693   // Otherwise, conservatively give up.
5694   default:
5695     return false;
5696   }
5697 
5698   // Record the value that we can demote.
5699   ToDemote.push_back(V);
5700   return true;
5701 }
5702 
5703 void BoUpSLP::computeMinimumValueSizes() {
5704   // If there are no external uses, the expression tree must be rooted by a
5705   // store. We can't demote in-memory values, so there is nothing to do here.
5706   if (ExternalUses.empty())
5707     return;
5708 
5709   // We only attempt to truncate integer expressions.
5710   auto &TreeRoot = VectorizableTree[0]->Scalars;
5711   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
5712   if (!TreeRootIT)
5713     return;
5714 
5715   // If the expression is not rooted by a store, these roots should have
5716   // external uses. We will rely on InstCombine to rewrite the expression in
5717   // the narrower type. However, InstCombine only rewrites single-use values.
5718   // This means that if a tree entry other than a root is used externally, it
5719   // must have multiple uses and InstCombine will not rewrite it. The code
5720   // below ensures that only the roots are used externally.
5721   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
5722   for (auto &EU : ExternalUses)
5723     if (!Expr.erase(EU.Scalar))
5724       return;
5725   if (!Expr.empty())
5726     return;
5727 
5728   // Collect the scalar values of the vectorizable expression. We will use this
5729   // context to determine which values can be demoted. If we see a truncation,
5730   // we mark it as seeding another demotion.
5731   for (auto &EntryPtr : VectorizableTree)
5732     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
5733 
5734   // Ensure the roots of the vectorizable tree don't form a cycle. They must
5735   // have a single external user that is not in the vectorizable tree.
5736   for (auto *Root : TreeRoot)
5737     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
5738       return;
5739 
5740   // Conservatively determine if we can actually truncate the roots of the
5741   // expression. Collect the values that can be demoted in ToDemote and
5742   // additional roots that require investigating in Roots.
5743   SmallVector<Value *, 32> ToDemote;
5744   SmallVector<Value *, 4> Roots;
5745   for (auto *Root : TreeRoot)
5746     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
5747       return;
5748 
5749   // The maximum bit width required to represent all the values that can be
5750   // demoted without loss of precision. It would be safe to truncate the roots
5751   // of the expression to this width.
5752   auto MaxBitWidth = 8u;
5753 
5754   // We first check if all the bits of the roots are demanded. If they're not,
5755   // we can truncate the roots to this narrower type.
5756   for (auto *Root : TreeRoot) {
5757     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
5758     MaxBitWidth = std::max<unsigned>(
5759         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
5760   }
5761 
5762   // True if the roots can be zero-extended back to their original type, rather
5763   // than sign-extended. We know that if the leading bits are not demanded, we
5764   // can safely zero-extend. So we initialize IsKnownPositive to True.
5765   bool IsKnownPositive = true;
5766 
5767   // If all the bits of the roots are demanded, we can try a little harder to
5768   // compute a narrower type. This can happen, for example, if the roots are
5769   // getelementptr indices. InstCombine promotes these indices to the pointer
5770   // width. Thus, all their bits are technically demanded even though the
5771   // address computation might be vectorized in a smaller type.
5772   //
5773   // We start by looking at each entry that can be demoted. We compute the
5774   // maximum bit width required to store the scalar by using ValueTracking to
5775   // compute the number of high-order bits we can truncate.
5776   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
5777       llvm::all_of(TreeRoot, [](Value *R) {
5778         assert(R->hasOneUse() && "Root should have only one use!");
5779         return isa<GetElementPtrInst>(R->user_back());
5780       })) {
5781     MaxBitWidth = 8u;
5782 
5783     // Determine if the sign bit of all the roots is known to be zero. If not,
5784     // IsKnownPositive is set to False.
5785     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
5786       KnownBits Known = computeKnownBits(R, *DL);
5787       return Known.isNonNegative();
5788     });
5789 
5790     // Determine the maximum number of bits required to store the scalar
5791     // values.
5792     for (auto *Scalar : ToDemote) {
5793       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
5794       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
5795       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
5796     }
5797 
5798     // If we can't prove that the sign bit is zero, we must add one to the
5799     // maximum bit width to account for the unknown sign bit. This preserves
5800     // the existing sign bit so we can safely sign-extend the root back to the
5801     // original type. Otherwise, if we know the sign bit is zero, we will
5802     // zero-extend the root instead.
5803     //
5804     // FIXME: This is somewhat suboptimal, as there will be cases where adding
5805     //        one to the maximum bit width will yield a larger-than-necessary
5806     //        type. In general, we need to add an extra bit only if we can't
5807     //        prove that the upper bit of the original type is equal to the
5808     //        upper bit of the proposed smaller type. If these two bits are the
5809     //        same (either zero or one) we know that sign-extending from the
5810     //        smaller type will result in the same value. Here, since we can't
5811     //        yet prove this, we are just making the proposed smaller type
5812     //        larger to ensure correctness.
5813     if (!IsKnownPositive)
5814       ++MaxBitWidth;
5815   }
5816 
5817   // Round MaxBitWidth up to the next power-of-two.
5818   if (!isPowerOf2_64(MaxBitWidth))
5819     MaxBitWidth = NextPowerOf2(MaxBitWidth);
5820 
5821   // If the maximum bit width we compute is less than the with of the roots'
5822   // type, we can proceed with the narrowing. Otherwise, do nothing.
5823   if (MaxBitWidth >= TreeRootIT->getBitWidth())
5824     return;
5825 
5826   // If we can truncate the root, we must collect additional values that might
5827   // be demoted as a result. That is, those seeded by truncations we will
5828   // modify.
5829   while (!Roots.empty())
5830     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
5831 
5832   // Finally, map the values we can demote to the maximum bit with we computed.
5833   for (auto *Scalar : ToDemote)
5834     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
5835 }
5836 
5837 namespace {
5838 
5839 /// The SLPVectorizer Pass.
5840 struct SLPVectorizer : public FunctionPass {
5841   SLPVectorizerPass Impl;
5842 
5843   /// Pass identification, replacement for typeid
5844   static char ID;
5845 
5846   explicit SLPVectorizer() : FunctionPass(ID) {
5847     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
5848   }
5849 
5850   bool doInitialization(Module &M) override {
5851     return false;
5852   }
5853 
5854   bool runOnFunction(Function &F) override {
5855     if (skipFunction(F))
5856       return false;
5857 
5858     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5859     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
5860     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5861     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
5862     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
5863     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5864     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5865     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
5866     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
5867     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
5868 
5869     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5870   }
5871 
5872   void getAnalysisUsage(AnalysisUsage &AU) const override {
5873     FunctionPass::getAnalysisUsage(AU);
5874     AU.addRequired<AssumptionCacheTracker>();
5875     AU.addRequired<ScalarEvolutionWrapperPass>();
5876     AU.addRequired<AAResultsWrapperPass>();
5877     AU.addRequired<TargetTransformInfoWrapperPass>();
5878     AU.addRequired<LoopInfoWrapperPass>();
5879     AU.addRequired<DominatorTreeWrapperPass>();
5880     AU.addRequired<DemandedBitsWrapperPass>();
5881     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
5882     AU.addRequired<InjectTLIMappingsLegacy>();
5883     AU.addPreserved<LoopInfoWrapperPass>();
5884     AU.addPreserved<DominatorTreeWrapperPass>();
5885     AU.addPreserved<AAResultsWrapperPass>();
5886     AU.addPreserved<GlobalsAAWrapperPass>();
5887     AU.setPreservesCFG();
5888   }
5889 };
5890 
5891 } // end anonymous namespace
5892 
5893 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
5894   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
5895   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
5896   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
5897   auto *AA = &AM.getResult<AAManager>(F);
5898   auto *LI = &AM.getResult<LoopAnalysis>(F);
5899   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
5900   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
5901   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
5902   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5903 
5904   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5905   if (!Changed)
5906     return PreservedAnalyses::all();
5907 
5908   PreservedAnalyses PA;
5909   PA.preserveSet<CFGAnalyses>();
5910   PA.preserve<AAManager>();
5911   PA.preserve<GlobalsAA>();
5912   return PA;
5913 }
5914 
5915 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
5916                                 TargetTransformInfo *TTI_,
5917                                 TargetLibraryInfo *TLI_, AAResults *AA_,
5918                                 LoopInfo *LI_, DominatorTree *DT_,
5919                                 AssumptionCache *AC_, DemandedBits *DB_,
5920                                 OptimizationRemarkEmitter *ORE_) {
5921   if (!RunSLPVectorization)
5922     return false;
5923   SE = SE_;
5924   TTI = TTI_;
5925   TLI = TLI_;
5926   AA = AA_;
5927   LI = LI_;
5928   DT = DT_;
5929   AC = AC_;
5930   DB = DB_;
5931   DL = &F.getParent()->getDataLayout();
5932 
5933   Stores.clear();
5934   GEPs.clear();
5935   bool Changed = false;
5936 
5937   // If the target claims to have no vector registers don't attempt
5938   // vectorization.
5939   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)))
5940     return false;
5941 
5942   // Don't vectorize when the attribute NoImplicitFloat is used.
5943   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
5944     return false;
5945 
5946   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
5947 
5948   // Use the bottom up slp vectorizer to construct chains that start with
5949   // store instructions.
5950   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
5951 
5952   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
5953   // delete instructions.
5954 
5955   // Scan the blocks in the function in post order.
5956   for (auto BB : post_order(&F.getEntryBlock())) {
5957     collectSeedInstructions(BB);
5958 
5959     // Vectorize trees that end at stores.
5960     if (!Stores.empty()) {
5961       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
5962                         << " underlying objects.\n");
5963       Changed |= vectorizeStoreChains(R);
5964     }
5965 
5966     // Vectorize trees that end at reductions.
5967     Changed |= vectorizeChainsInBlock(BB, R);
5968 
5969     // Vectorize the index computations of getelementptr instructions. This
5970     // is primarily intended to catch gather-like idioms ending at
5971     // non-consecutive loads.
5972     if (!GEPs.empty()) {
5973       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
5974                         << " underlying objects.\n");
5975       Changed |= vectorizeGEPIndices(BB, R);
5976     }
5977   }
5978 
5979   if (Changed) {
5980     R.optimizeGatherSequence();
5981     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
5982   }
5983   return Changed;
5984 }
5985 
5986 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
5987                                             unsigned Idx) {
5988   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
5989                     << "\n");
5990   const unsigned Sz = R.getVectorElementSize(Chain[0]);
5991   const unsigned MinVF = R.getMinVecRegSize() / Sz;
5992   unsigned VF = Chain.size();
5993 
5994   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
5995     return false;
5996 
5997   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
5998                     << "\n");
5999 
6000   R.buildTree(Chain);
6001   Optional<ArrayRef<unsigned>> Order = R.bestOrder();
6002   // TODO: Handle orders of size less than number of elements in the vector.
6003   if (Order && Order->size() == Chain.size()) {
6004     // TODO: reorder tree nodes without tree rebuilding.
6005     SmallVector<Value *, 4> ReorderedOps(Chain.rbegin(), Chain.rend());
6006     llvm::transform(*Order, ReorderedOps.begin(),
6007                     [Chain](const unsigned Idx) { return Chain[Idx]; });
6008     R.buildTree(ReorderedOps);
6009   }
6010   if (R.isTreeTinyAndNotFullyVectorizable())
6011     return false;
6012   if (R.isLoadCombineCandidate())
6013     return false;
6014 
6015   R.computeMinimumValueSizes();
6016 
6017   InstructionCost Cost = R.getTreeCost();
6018 
6019   LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
6020   if (Cost.isValid() && Cost < -SLPCostThreshold) {
6021     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
6022 
6023     using namespace ore;
6024 
6025     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
6026                                         cast<StoreInst>(Chain[0]))
6027                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
6028                      << " and with tree size "
6029                      << NV("TreeSize", R.getTreeSize()));
6030 
6031     R.vectorizeTree();
6032     return true;
6033   }
6034 
6035   return false;
6036 }
6037 
6038 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
6039                                         BoUpSLP &R) {
6040   // We may run into multiple chains that merge into a single chain. We mark the
6041   // stores that we vectorized so that we don't visit the same store twice.
6042   BoUpSLP::ValueSet VectorizedStores;
6043   bool Changed = false;
6044 
6045   int E = Stores.size();
6046   SmallBitVector Tails(E, false);
6047   SmallVector<int, 16> ConsecutiveChain(E, E + 1);
6048   int MaxIter = MaxStoreLookup.getValue();
6049   int IterCnt;
6050   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
6051                                   &ConsecutiveChain](int K, int Idx) {
6052     if (IterCnt >= MaxIter)
6053       return true;
6054     ++IterCnt;
6055     if (!isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE))
6056       return false;
6057 
6058     Tails.set(Idx);
6059     ConsecutiveChain[K] = Idx;
6060     return true;
6061   };
6062   // Do a quadratic search on all of the given stores in reverse order and find
6063   // all of the pairs of stores that follow each other.
6064   for (int Idx = E - 1; Idx >= 0; --Idx) {
6065     // If a store has multiple consecutive store candidates, search according
6066     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
6067     // This is because usually pairing with immediate succeeding or preceding
6068     // candidate create the best chance to find slp vectorization opportunity.
6069     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
6070     IterCnt = 0;
6071     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
6072       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
6073           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
6074         break;
6075   }
6076 
6077   // For stores that start but don't end a link in the chain:
6078   for (int Cnt = E; Cnt > 0; --Cnt) {
6079     int I = Cnt - 1;
6080     if (ConsecutiveChain[I] == E + 1 || Tails.test(I))
6081       continue;
6082     // We found a store instr that starts a chain. Now follow the chain and try
6083     // to vectorize it.
6084     BoUpSLP::ValueList Operands;
6085     // Collect the chain into a list.
6086     while (I != E + 1 && !VectorizedStores.count(Stores[I])) {
6087       Operands.push_back(Stores[I]);
6088       // Move to the next value in the chain.
6089       I = ConsecutiveChain[I];
6090     }
6091 
6092     // If a vector register can't hold 1 element, we are done.
6093     unsigned MaxVecRegSize = R.getMaxVecRegSize();
6094     unsigned EltSize = R.getVectorElementSize(Operands[0]);
6095     if (MaxVecRegSize % EltSize != 0)
6096       continue;
6097 
6098     unsigned MaxElts = MaxVecRegSize / EltSize;
6099     // FIXME: Is division-by-2 the correct step? Should we assert that the
6100     // register size is a power-of-2?
6101     unsigned StartIdx = 0;
6102     for (unsigned Size = llvm::PowerOf2Ceil(MaxElts); Size >= 2; Size /= 2) {
6103       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
6104         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
6105         if (!VectorizedStores.count(Slice.front()) &&
6106             !VectorizedStores.count(Slice.back()) &&
6107             vectorizeStoreChain(Slice, R, Cnt)) {
6108           // Mark the vectorized stores so that we don't vectorize them again.
6109           VectorizedStores.insert(Slice.begin(), Slice.end());
6110           Changed = true;
6111           // If we vectorized initial block, no need to try to vectorize it
6112           // again.
6113           if (Cnt == StartIdx)
6114             StartIdx += Size;
6115           Cnt += Size;
6116           continue;
6117         }
6118         ++Cnt;
6119       }
6120       // Check if the whole array was vectorized already - exit.
6121       if (StartIdx >= Operands.size())
6122         break;
6123     }
6124   }
6125 
6126   return Changed;
6127 }
6128 
6129 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
6130   // Initialize the collections. We will make a single pass over the block.
6131   Stores.clear();
6132   GEPs.clear();
6133 
6134   // Visit the store and getelementptr instructions in BB and organize them in
6135   // Stores and GEPs according to the underlying objects of their pointer
6136   // operands.
6137   for (Instruction &I : *BB) {
6138     // Ignore store instructions that are volatile or have a pointer operand
6139     // that doesn't point to a scalar type.
6140     if (auto *SI = dyn_cast<StoreInst>(&I)) {
6141       if (!SI->isSimple())
6142         continue;
6143       if (!isValidElementType(SI->getValueOperand()->getType()))
6144         continue;
6145       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
6146     }
6147 
6148     // Ignore getelementptr instructions that have more than one index, a
6149     // constant index, or a pointer operand that doesn't point to a scalar
6150     // type.
6151     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
6152       auto Idx = GEP->idx_begin()->get();
6153       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
6154         continue;
6155       if (!isValidElementType(Idx->getType()))
6156         continue;
6157       if (GEP->getType()->isVectorTy())
6158         continue;
6159       GEPs[GEP->getPointerOperand()].push_back(GEP);
6160     }
6161   }
6162 }
6163 
6164 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
6165   if (!A || !B)
6166     return false;
6167   Value *VL[] = {A, B};
6168   return tryToVectorizeList(VL, R, /*AllowReorder=*/true);
6169 }
6170 
6171 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
6172                                            bool AllowReorder,
6173                                            ArrayRef<Value *> InsertUses) {
6174   if (VL.size() < 2)
6175     return false;
6176 
6177   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
6178                     << VL.size() << ".\n");
6179 
6180   // Check that all of the parts are instructions of the same type,
6181   // we permit an alternate opcode via InstructionsState.
6182   InstructionsState S = getSameOpcode(VL);
6183   if (!S.getOpcode())
6184     return false;
6185 
6186   Instruction *I0 = cast<Instruction>(S.OpValue);
6187   // Make sure invalid types (including vector type) are rejected before
6188   // determining vectorization factor for scalar instructions.
6189   for (Value *V : VL) {
6190     Type *Ty = V->getType();
6191     if (!isValidElementType(Ty)) {
6192       // NOTE: the following will give user internal llvm type name, which may
6193       // not be useful.
6194       R.getORE()->emit([&]() {
6195         std::string type_str;
6196         llvm::raw_string_ostream rso(type_str);
6197         Ty->print(rso);
6198         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
6199                << "Cannot SLP vectorize list: type "
6200                << rso.str() + " is unsupported by vectorizer";
6201       });
6202       return false;
6203     }
6204   }
6205 
6206   unsigned Sz = R.getVectorElementSize(I0);
6207   unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
6208   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
6209   MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
6210   if (MaxVF < 2) {
6211     R.getORE()->emit([&]() {
6212       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
6213              << "Cannot SLP vectorize list: vectorization factor "
6214              << "less than 2 is not supported";
6215     });
6216     return false;
6217   }
6218 
6219   bool Changed = false;
6220   bool CandidateFound = false;
6221   InstructionCost MinCost = SLPCostThreshold.getValue();
6222 
6223   bool CompensateUseCost =
6224       !InsertUses.empty() && llvm::all_of(InsertUses, [](const Value *V) {
6225         return V && isa<InsertElementInst>(V);
6226       });
6227   assert((!CompensateUseCost || InsertUses.size() == VL.size()) &&
6228          "Each scalar expected to have an associated InsertElement user.");
6229 
6230   unsigned NextInst = 0, MaxInst = VL.size();
6231   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
6232     // No actual vectorization should happen, if number of parts is the same as
6233     // provided vectorization factor (i.e. the scalar type is used for vector
6234     // code during codegen).
6235     auto *VecTy = FixedVectorType::get(VL[0]->getType(), VF);
6236     if (TTI->getNumberOfParts(VecTy) == VF)
6237       continue;
6238     for (unsigned I = NextInst; I < MaxInst; ++I) {
6239       unsigned OpsWidth = 0;
6240 
6241       if (I + VF > MaxInst)
6242         OpsWidth = MaxInst - I;
6243       else
6244         OpsWidth = VF;
6245 
6246       if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
6247         break;
6248 
6249       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
6250       // Check that a previous iteration of this loop did not delete the Value.
6251       if (llvm::any_of(Ops, [&R](Value *V) {
6252             auto *I = dyn_cast<Instruction>(V);
6253             return I && R.isDeleted(I);
6254           }))
6255         continue;
6256 
6257       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
6258                         << "\n");
6259 
6260       R.buildTree(Ops);
6261       Optional<ArrayRef<unsigned>> Order = R.bestOrder();
6262       // TODO: check if we can allow reordering for more cases.
6263       if (AllowReorder && Order) {
6264         // TODO: reorder tree nodes without tree rebuilding.
6265         // Conceptually, there is nothing actually preventing us from trying to
6266         // reorder a larger list. In fact, we do exactly this when vectorizing
6267         // reductions. However, at this point, we only expect to get here when
6268         // there are exactly two operations.
6269         assert(Ops.size() == 2);
6270         Value *ReorderedOps[] = {Ops[1], Ops[0]};
6271         R.buildTree(ReorderedOps, None);
6272       }
6273       if (R.isTreeTinyAndNotFullyVectorizable())
6274         continue;
6275 
6276       R.computeMinimumValueSizes();
6277       InstructionCost Cost = R.getTreeCost();
6278       CandidateFound = true;
6279       if (CompensateUseCost) {
6280         // TODO: Use TTI's getScalarizationOverhead for sequence of inserts
6281         // rather than sum of single inserts as the latter may overestimate
6282         // cost. This work should imply improving cost estimation for extracts
6283         // that added in for external (for vectorization tree) users,i.e. that
6284         // part should also switch to same interface.
6285         // For example, the following case is projected code after SLP:
6286         //  %4 = extractelement <4 x i64> %3, i32 0
6287         //  %v0 = insertelement <4 x i64> undef, i64 %4, i32 0
6288         //  %5 = extractelement <4 x i64> %3, i32 1
6289         //  %v1 = insertelement <4 x i64> %v0, i64 %5, i32 1
6290         //  %6 = extractelement <4 x i64> %3, i32 2
6291         //  %v2 = insertelement <4 x i64> %v1, i64 %6, i32 2
6292         //  %7 = extractelement <4 x i64> %3, i32 3
6293         //  %v3 = insertelement <4 x i64> %v2, i64 %7, i32 3
6294         //
6295         // Extracts here added by SLP in order to feed users (the inserts) of
6296         // original scalars and contribute to "ExtractCost" at cost evaluation.
6297         // The inserts in turn form sequence to build an aggregate that
6298         // detected by findBuildAggregate routine.
6299         // SLP makes an assumption that such sequence will be optimized away
6300         // later (instcombine) so it tries to compensate ExctractCost with
6301         // cost of insert sequence.
6302         // Current per element cost calculation approach is not quite accurate
6303         // and tends to create bias toward favoring vectorization.
6304         // Switching to the TTI interface might help a bit.
6305         // Alternative solution could be pattern-match to detect a no-op or
6306         // shuffle.
6307         InstructionCost UserCost = 0;
6308         for (unsigned Lane = 0; Lane < OpsWidth; Lane++) {
6309           auto *IE = cast<InsertElementInst>(InsertUses[I + Lane]);
6310           if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2)))
6311             UserCost += TTI->getVectorInstrCost(
6312                 Instruction::InsertElement, IE->getType(), CI->getZExtValue());
6313         }
6314         LLVM_DEBUG(dbgs() << "SLP: Compensate cost of users by: " << UserCost
6315                           << ".\n");
6316         Cost -= UserCost;
6317       }
6318 
6319       MinCost = InstructionCost::min(MinCost, Cost);
6320 
6321       if (Cost.isValid() && Cost < -SLPCostThreshold) {
6322         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
6323         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
6324                                                     cast<Instruction>(Ops[0]))
6325                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
6326                                  << " and with tree size "
6327                                  << ore::NV("TreeSize", R.getTreeSize()));
6328 
6329         R.vectorizeTree();
6330         // Move to the next bundle.
6331         I += VF - 1;
6332         NextInst = I + 1;
6333         Changed = true;
6334       }
6335     }
6336   }
6337 
6338   if (!Changed && CandidateFound) {
6339     R.getORE()->emit([&]() {
6340       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
6341              << "List vectorization was possible but not beneficial with cost "
6342              << ore::NV("Cost", MinCost) << " >= "
6343              << ore::NV("Treshold", -SLPCostThreshold);
6344     });
6345   } else if (!Changed) {
6346     R.getORE()->emit([&]() {
6347       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
6348              << "Cannot SLP vectorize list: vectorization was impossible"
6349              << " with available vectorization factors";
6350     });
6351   }
6352   return Changed;
6353 }
6354 
6355 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
6356   if (!I)
6357     return false;
6358 
6359   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
6360     return false;
6361 
6362   Value *P = I->getParent();
6363 
6364   // Vectorize in current basic block only.
6365   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
6366   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
6367   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
6368     return false;
6369 
6370   // Try to vectorize V.
6371   if (tryToVectorizePair(Op0, Op1, R))
6372     return true;
6373 
6374   auto *A = dyn_cast<BinaryOperator>(Op0);
6375   auto *B = dyn_cast<BinaryOperator>(Op1);
6376   // Try to skip B.
6377   if (B && B->hasOneUse()) {
6378     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
6379     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
6380     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
6381       return true;
6382     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
6383       return true;
6384   }
6385 
6386   // Try to skip A.
6387   if (A && A->hasOneUse()) {
6388     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
6389     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
6390     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
6391       return true;
6392     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
6393       return true;
6394   }
6395   return false;
6396 }
6397 
6398 /// Generate a shuffle mask to be used in a reduction tree.
6399 ///
6400 /// \param VecLen The length of the vector to be reduced.
6401 /// \param NumEltsToRdx The number of elements that should be reduced in the
6402 ///        vector.
6403 /// \param IsPairwise Whether the reduction is a pairwise or splitting
6404 ///        reduction. A pairwise reduction will generate a mask of
6405 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
6406 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
6407 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
6408 static SmallVector<int, 32> createRdxShuffleMask(unsigned VecLen,
6409                                                  unsigned NumEltsToRdx,
6410                                                  bool IsPairwise, bool IsLeft) {
6411   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
6412 
6413   SmallVector<int, 32> ShuffleMask(VecLen, -1);
6414 
6415   if (IsPairwise)
6416     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
6417     for (unsigned i = 0; i != NumEltsToRdx; ++i)
6418       ShuffleMask[i] = 2 * i + !IsLeft;
6419   else
6420     // Move the upper half of the vector to the lower half.
6421     for (unsigned i = 0; i != NumEltsToRdx; ++i)
6422       ShuffleMask[i] = NumEltsToRdx + i;
6423 
6424   return ShuffleMask;
6425 }
6426 
6427 namespace {
6428 
6429 /// Model horizontal reductions.
6430 ///
6431 /// A horizontal reduction is a tree of reduction operations (currently add and
6432 /// fadd) that has operations that can be put into a vector as its leaf.
6433 /// For example, this tree:
6434 ///
6435 /// mul mul mul mul
6436 ///  \  /    \  /
6437 ///   +       +
6438 ///    \     /
6439 ///       +
6440 /// This tree has "mul" as its reduced values and "+" as its reduction
6441 /// operations. A reduction might be feeding into a store or a binary operation
6442 /// feeding a phi.
6443 ///    ...
6444 ///    \  /
6445 ///     +
6446 ///     |
6447 ///  phi +=
6448 ///
6449 ///  Or:
6450 ///    ...
6451 ///    \  /
6452 ///     +
6453 ///     |
6454 ///   *p =
6455 ///
6456 class HorizontalReduction {
6457   using ReductionOpsType = SmallVector<Value *, 16>;
6458   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
6459   ReductionOpsListType  ReductionOps;
6460   SmallVector<Value *, 32> ReducedVals;
6461   // Use map vector to make stable output.
6462   MapVector<Instruction *, Value *> ExtraArgs;
6463 
6464   /// Kind of the reduction data.
6465   enum ReductionKind {
6466     RK_None,       /// Not a reduction.
6467     RK_Arithmetic, /// Binary reduction data.
6468     RK_SMin,       /// Signed minimum reduction data.
6469     RK_UMin,       /// Unsigned minimum reduction data.
6470     RK_SMax,       /// Signed maximum reduction data.
6471     RK_UMax,       /// Unsigned maximum reduction data.
6472   };
6473 
6474   /// Contains info about operation, like its opcode, left and right operands.
6475   class OperationData {
6476     /// Opcode of the instruction.
6477     unsigned Opcode = 0;
6478 
6479     /// Kind of the reduction operation.
6480     ReductionKind Kind = RK_None;
6481 
6482     /// Checks if the reduction operation can be vectorized.
6483     bool isVectorizable() const {
6484       // We currently only support add/mul/logical && min/max reductions.
6485       return ((Kind == RK_Arithmetic &&
6486                (Opcode == Instruction::Add || Opcode == Instruction::FAdd ||
6487                 Opcode == Instruction::Mul || Opcode == Instruction::FMul ||
6488                 Opcode == Instruction::And || Opcode == Instruction::Or ||
6489                 Opcode == Instruction::Xor)) ||
6490               (Opcode == Instruction::ICmp &&
6491                (Kind == RK_SMin || Kind == RK_SMax ||
6492                 Kind == RK_UMin || Kind == RK_UMax)));
6493     }
6494 
6495     /// Creates reduction operation with the current opcode.
6496     Value *createOp(IRBuilder<> &Builder, Value *LHS, Value *RHS,
6497                     const Twine &Name) const {
6498       assert(isVectorizable() &&
6499              "Expected add|fadd or min/max reduction operation.");
6500       Value *Cmp = nullptr;
6501       switch (Kind) {
6502       case RK_Arithmetic:
6503         return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
6504                                    Name);
6505       case RK_SMin:
6506         assert(Opcode == Instruction::ICmp && "Expected integer types.");
6507         Cmp = Builder.CreateICmpSLT(LHS, RHS);
6508         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6509       case RK_SMax:
6510         assert(Opcode == Instruction::ICmp && "Expected integer types.");
6511         Cmp = Builder.CreateICmpSGT(LHS, RHS);
6512         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6513       case RK_UMin:
6514         assert(Opcode == Instruction::ICmp && "Expected integer types.");
6515         Cmp = Builder.CreateICmpULT(LHS, RHS);
6516         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6517       case RK_UMax:
6518         assert(Opcode == Instruction::ICmp && "Expected integer types.");
6519         Cmp = Builder.CreateICmpUGT(LHS, RHS);
6520         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6521       case RK_None:
6522         break;
6523       }
6524       llvm_unreachable("Unknown reduction operation.");
6525     }
6526 
6527   public:
6528     explicit OperationData() = default;
6529 
6530     /// Construction for reduced values. They are identified by opcode only and
6531     /// don't have associated LHS/RHS values.
6532     explicit OperationData(Instruction &I) {
6533       Opcode = I.getOpcode();
6534     }
6535 
6536     /// Constructor for reduction operations with opcode and its left and
6537     /// right operands.
6538     OperationData(unsigned Opcode, ReductionKind Kind)
6539         : Opcode(Opcode), Kind(Kind) {
6540       assert(Kind != RK_None && "One of the reduction operations is expected.");
6541     }
6542 
6543     explicit operator bool() const { return Opcode; }
6544 
6545     /// Return true if this operation is any kind of minimum or maximum.
6546     bool isMinMax() const {
6547       switch (Kind) {
6548       case RK_Arithmetic:
6549         return false;
6550       case RK_SMin:
6551       case RK_SMax:
6552       case RK_UMin:
6553       case RK_UMax:
6554         return true;
6555       case RK_None:
6556         break;
6557       }
6558       llvm_unreachable("Reduction kind is not set");
6559     }
6560 
6561     /// Get the index of the first operand.
6562     unsigned getFirstOperandIndex() const {
6563       assert(!!*this && "The opcode is not set.");
6564       // We allow calling this before 'Kind' is set, so handle that specially.
6565       if (Kind == RK_None)
6566         return 0;
6567       return isMinMax() ? 1 : 0;
6568     }
6569 
6570     /// Total number of operands in the reduction operation.
6571     unsigned getNumberOfOperands() const {
6572       assert(Kind != RK_None && !!*this && "Expected reduction operation.");
6573       return isMinMax() ? 3 : 2;
6574     }
6575 
6576     /// Checks if the instruction is in basic block \p BB.
6577     /// For a min/max reduction check that both compare and select are in \p BB.
6578     bool hasSameParent(Instruction *I, BasicBlock *BB, bool IsRedOp) const {
6579       assert(Kind != RK_None && !!*this && "Expected reduction operation.");
6580       if (IsRedOp && isMinMax()) {
6581         auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition());
6582         return I->getParent() == BB && Cmp && Cmp->getParent() == BB;
6583       }
6584       return I->getParent() == BB;
6585     }
6586 
6587     /// Expected number of uses for reduction operations/reduced values.
6588     bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const {
6589       assert(Kind != RK_None && !!*this && "Expected reduction operation.");
6590       // SelectInst must be used twice while the condition op must have single
6591       // use only.
6592       if (isMinMax())
6593         return I->hasNUses(2) &&
6594                (!IsReductionOp ||
6595                 cast<SelectInst>(I)->getCondition()->hasOneUse());
6596 
6597       // Arithmetic reduction operation must be used once only.
6598       return I->hasOneUse();
6599     }
6600 
6601     /// Initializes the list of reduction operations.
6602     void initReductionOps(ReductionOpsListType &ReductionOps) {
6603       assert(Kind != RK_None && !!*this && "Expected reduction operation.");
6604       if (isMinMax())
6605         ReductionOps.assign(2, ReductionOpsType());
6606       else
6607         ReductionOps.assign(1, ReductionOpsType());
6608     }
6609 
6610     /// Add all reduction operations for the reduction instruction \p I.
6611     void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) {
6612       assert(Kind != RK_None && !!*this && "Expected reduction operation.");
6613       if (isMinMax()) {
6614         ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
6615         ReductionOps[1].emplace_back(I);
6616       } else {
6617         ReductionOps[0].emplace_back(I);
6618       }
6619     }
6620 
6621     /// Checks if instruction is associative and can be vectorized.
6622     bool isAssociative(Instruction *I) const {
6623       assert(Kind != RK_None && *this && "Expected reduction operation.");
6624       switch (Kind) {
6625       case RK_Arithmetic:
6626         return I->isAssociative();
6627       case RK_SMin:
6628       case RK_SMax:
6629       case RK_UMin:
6630       case RK_UMax:
6631         assert(Opcode == Instruction::ICmp &&
6632                "Only integer compare operation is expected.");
6633         return true;
6634       case RK_None:
6635         break;
6636       }
6637       llvm_unreachable("Reduction kind is not set");
6638     }
6639 
6640     /// Checks if the reduction operation can be vectorized.
6641     bool isVectorizable(Instruction *I) const {
6642       return isVectorizable() && isAssociative(I);
6643     }
6644 
6645     /// Checks if two operation data are both a reduction op or both a reduced
6646     /// value.
6647     bool operator==(const OperationData &OD) const {
6648       assert(((Kind != OD.Kind) || (Opcode != 0 && OD.Opcode != 0)) &&
6649              "One of the comparing operations is incorrect.");
6650       return Kind == OD.Kind && Opcode == OD.Opcode;
6651     }
6652     bool operator!=(const OperationData &OD) const { return !(*this == OD); }
6653     void clear() {
6654       Opcode = 0;
6655       Kind = RK_None;
6656     }
6657 
6658     /// Get the opcode of the reduction operation.
6659     unsigned getOpcode() const {
6660       assert(isVectorizable() && "Expected vectorizable operation.");
6661       return Opcode;
6662     }
6663 
6664     /// Get kind of reduction data.
6665     ReductionKind getKind() const { return Kind; }
6666     Value *getLHS(Instruction *I) const {
6667       if (Kind == RK_None)
6668         return nullptr;
6669       return I->getOperand(getFirstOperandIndex());
6670     }
6671     Value *getRHS(Instruction *I) const {
6672       if (Kind == RK_None)
6673         return nullptr;
6674       return I->getOperand(getFirstOperandIndex() + 1);
6675     }
6676 
6677     /// Creates reduction operation with the current opcode with the IR flags
6678     /// from \p ReductionOps.
6679     Value *createOp(IRBuilder<> &Builder, Value *LHS, Value *RHS,
6680                     const Twine &Name,
6681                     const ReductionOpsListType &ReductionOps) const {
6682       assert(isVectorizable() &&
6683              "Expected add|fadd or min/max reduction operation.");
6684       auto *Op = createOp(Builder, LHS, RHS, Name);
6685       switch (Kind) {
6686       case RK_Arithmetic:
6687         propagateIRFlags(Op, ReductionOps[0]);
6688         return Op;
6689       case RK_SMin:
6690       case RK_SMax:
6691       case RK_UMin:
6692       case RK_UMax:
6693         if (auto *SI = dyn_cast<SelectInst>(Op))
6694           propagateIRFlags(SI->getCondition(), ReductionOps[0]);
6695         propagateIRFlags(Op, ReductionOps[1]);
6696         return Op;
6697       case RK_None:
6698         break;
6699       }
6700       llvm_unreachable("Unknown reduction operation.");
6701     }
6702     /// Creates reduction operation with the current opcode with the IR flags
6703     /// from \p I.
6704     Value *createOp(IRBuilder<> &Builder, Value *LHS, Value *RHS,
6705                     const Twine &Name, Instruction *I) const {
6706       assert(isVectorizable() &&
6707              "Expected add|fadd or min/max reduction operation.");
6708       auto *Op = createOp(Builder, LHS, RHS, Name);
6709       switch (Kind) {
6710       case RK_Arithmetic:
6711         propagateIRFlags(Op, I);
6712         return Op;
6713       case RK_SMin:
6714       case RK_SMax:
6715       case RK_UMin:
6716       case RK_UMax:
6717         if (auto *SI = dyn_cast<SelectInst>(Op)) {
6718           propagateIRFlags(SI->getCondition(),
6719                            cast<SelectInst>(I)->getCondition());
6720         }
6721         propagateIRFlags(Op, I);
6722         return Op;
6723       case RK_None:
6724         break;
6725       }
6726       llvm_unreachable("Unknown reduction operation.");
6727     }
6728 
6729     TargetTransformInfo::ReductionFlags getFlags() const {
6730       TargetTransformInfo::ReductionFlags Flags;
6731       switch (Kind) {
6732       case RK_Arithmetic:
6733         break;
6734       case RK_SMin:
6735         Flags.IsSigned = true;
6736         Flags.IsMaxOp = false;
6737         break;
6738       case RK_SMax:
6739         Flags.IsSigned = true;
6740         Flags.IsMaxOp = true;
6741         break;
6742       case RK_UMin:
6743         Flags.IsSigned = false;
6744         Flags.IsMaxOp = false;
6745         break;
6746       case RK_UMax:
6747         Flags.IsSigned = false;
6748         Flags.IsMaxOp = true;
6749         break;
6750       case RK_None:
6751         llvm_unreachable("Reduction kind is not set");
6752       }
6753       return Flags;
6754     }
6755   };
6756 
6757   WeakTrackingVH ReductionRoot;
6758 
6759   /// The operation data of the reduction operation.
6760   OperationData ReductionData;
6761 
6762   /// The operation data of the values we perform a reduction on.
6763   OperationData ReducedValueData;
6764 
6765   /// Should we model this reduction as a pairwise reduction tree or a tree that
6766   /// splits the vector in halves and adds those halves.
6767   bool IsPairwiseReduction = false;
6768 
6769   /// Checks if the ParentStackElem.first should be marked as a reduction
6770   /// operation with an extra argument or as extra argument itself.
6771   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
6772                     Value *ExtraArg) {
6773     if (ExtraArgs.count(ParentStackElem.first)) {
6774       ExtraArgs[ParentStackElem.first] = nullptr;
6775       // We ran into something like:
6776       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
6777       // The whole ParentStackElem.first should be considered as an extra value
6778       // in this case.
6779       // Do not perform analysis of remaining operands of ParentStackElem.first
6780       // instruction, this whole instruction is an extra argument.
6781       ParentStackElem.second = ParentStackElem.first->getNumOperands();
6782     } else {
6783       // We ran into something like:
6784       // ParentStackElem.first += ... + ExtraArg + ...
6785       ExtraArgs[ParentStackElem.first] = ExtraArg;
6786     }
6787   }
6788 
6789   static OperationData getOperationData(Instruction *I) {
6790     if (!I)
6791       return OperationData();
6792 
6793     Value *LHS;
6794     Value *RHS;
6795     if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(I)) {
6796       return OperationData(cast<BinaryOperator>(I)->getOpcode(), RK_Arithmetic);
6797     }
6798     if (auto *Select = dyn_cast<SelectInst>(I)) {
6799       // Look for a min/max pattern.
6800       if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6801         return OperationData(Instruction::ICmp, RK_UMin);
6802       } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6803         return OperationData(Instruction::ICmp, RK_SMin);
6804       } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6805         return OperationData(Instruction::ICmp, RK_UMax);
6806       } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6807         return OperationData(Instruction::ICmp, RK_SMax);
6808       } else {
6809         // Try harder: look for min/max pattern based on instructions producing
6810         // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
6811         // During the intermediate stages of SLP, it's very common to have
6812         // pattern like this (since optimizeGatherSequence is run only once
6813         // at the end):
6814         // %1 = extractelement <2 x i32> %a, i32 0
6815         // %2 = extractelement <2 x i32> %a, i32 1
6816         // %cond = icmp sgt i32 %1, %2
6817         // %3 = extractelement <2 x i32> %a, i32 0
6818         // %4 = extractelement <2 x i32> %a, i32 1
6819         // %select = select i1 %cond, i32 %3, i32 %4
6820         CmpInst::Predicate Pred;
6821         Instruction *L1;
6822         Instruction *L2;
6823 
6824         LHS = Select->getTrueValue();
6825         RHS = Select->getFalseValue();
6826         Value *Cond = Select->getCondition();
6827 
6828         // TODO: Support inverse predicates.
6829         if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
6830           if (!isa<ExtractElementInst>(RHS) ||
6831               !L2->isIdenticalTo(cast<Instruction>(RHS)))
6832             return OperationData(*I);
6833         } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
6834           if (!isa<ExtractElementInst>(LHS) ||
6835               !L1->isIdenticalTo(cast<Instruction>(LHS)))
6836             return OperationData(*I);
6837         } else {
6838           if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
6839             return OperationData(*I);
6840           if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
6841               !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
6842               !L2->isIdenticalTo(cast<Instruction>(RHS)))
6843             return OperationData(*I);
6844         }
6845         switch (Pred) {
6846         default:
6847           return OperationData(*I);
6848 
6849         case CmpInst::ICMP_ULT:
6850         case CmpInst::ICMP_ULE:
6851           return OperationData(Instruction::ICmp, RK_UMin);
6852 
6853         case CmpInst::ICMP_SLT:
6854         case CmpInst::ICMP_SLE:
6855           return OperationData(Instruction::ICmp, RK_SMin);
6856 
6857         case CmpInst::ICMP_UGT:
6858         case CmpInst::ICMP_UGE:
6859           return OperationData(Instruction::ICmp, RK_UMax);
6860 
6861         case CmpInst::ICMP_SGT:
6862         case CmpInst::ICMP_SGE:
6863           return OperationData(Instruction::ICmp, RK_SMax);
6864         }
6865       }
6866     }
6867     return OperationData(*I);
6868   }
6869 
6870 public:
6871   HorizontalReduction() = default;
6872 
6873   /// Try to find a reduction tree.
6874   bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
6875     assert((!Phi || is_contained(Phi->operands(), B)) &&
6876            "Thi phi needs to use the binary operator");
6877 
6878     ReductionData = getOperationData(B);
6879 
6880     // We could have a initial reductions that is not an add.
6881     //  r *= v1 + v2 + v3 + v4
6882     // In such a case start looking for a tree rooted in the first '+'.
6883     if (Phi) {
6884       if (ReductionData.getLHS(B) == Phi) {
6885         Phi = nullptr;
6886         B = dyn_cast<Instruction>(ReductionData.getRHS(B));
6887         ReductionData = getOperationData(B);
6888       } else if (ReductionData.getRHS(B) == Phi) {
6889         Phi = nullptr;
6890         B = dyn_cast<Instruction>(ReductionData.getLHS(B));
6891         ReductionData = getOperationData(B);
6892       }
6893     }
6894 
6895     if (!ReductionData.isVectorizable(B))
6896       return false;
6897 
6898     Type *Ty = B->getType();
6899     if (!isValidElementType(Ty))
6900       return false;
6901     if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy())
6902       return false;
6903 
6904     ReducedValueData.clear();
6905     ReductionRoot = B;
6906 
6907     // Post order traverse the reduction tree starting at B. We only handle true
6908     // trees containing only binary operators.
6909     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
6910     Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
6911     ReductionData.initReductionOps(ReductionOps);
6912     while (!Stack.empty()) {
6913       Instruction *TreeN = Stack.back().first;
6914       unsigned EdgeToVist = Stack.back().second++;
6915       OperationData OpData = getOperationData(TreeN);
6916       bool IsReducedValue = OpData != ReductionData;
6917 
6918       // Postorder vist.
6919       if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
6920         if (IsReducedValue)
6921           ReducedVals.push_back(TreeN);
6922         else {
6923           auto I = ExtraArgs.find(TreeN);
6924           if (I != ExtraArgs.end() && !I->second) {
6925             // Check if TreeN is an extra argument of its parent operation.
6926             if (Stack.size() <= 1) {
6927               // TreeN can't be an extra argument as it is a root reduction
6928               // operation.
6929               return false;
6930             }
6931             // Yes, TreeN is an extra argument, do not add it to a list of
6932             // reduction operations.
6933             // Stack[Stack.size() - 2] always points to the parent operation.
6934             markExtraArg(Stack[Stack.size() - 2], TreeN);
6935             ExtraArgs.erase(TreeN);
6936           } else
6937             ReductionData.addReductionOps(TreeN, ReductionOps);
6938         }
6939         // Retract.
6940         Stack.pop_back();
6941         continue;
6942       }
6943 
6944       // Visit left or right.
6945       Value *NextV = TreeN->getOperand(EdgeToVist);
6946       if (NextV != Phi) {
6947         auto *I = dyn_cast<Instruction>(NextV);
6948         OpData = getOperationData(I);
6949         // Continue analysis if the next operand is a reduction operation or
6950         // (possibly) a reduced value. If the reduced value opcode is not set,
6951         // the first met operation != reduction operation is considered as the
6952         // reduced value class.
6953         if (I && (!ReducedValueData || OpData == ReducedValueData ||
6954                   OpData == ReductionData)) {
6955           const bool IsReductionOperation = OpData == ReductionData;
6956           // Only handle trees in the current basic block.
6957           if (!ReductionData.hasSameParent(I, B->getParent(),
6958                                            IsReductionOperation)) {
6959             // I is an extra argument for TreeN (its parent operation).
6960             markExtraArg(Stack.back(), I);
6961             continue;
6962           }
6963 
6964           // Each tree node needs to have minimal number of users except for the
6965           // ultimate reduction.
6966           if (!ReductionData.hasRequiredNumberOfUses(I,
6967                                                      OpData == ReductionData) &&
6968               I != B) {
6969             // I is an extra argument for TreeN (its parent operation).
6970             markExtraArg(Stack.back(), I);
6971             continue;
6972           }
6973 
6974           if (IsReductionOperation) {
6975             // We need to be able to reassociate the reduction operations.
6976             if (!OpData.isAssociative(I)) {
6977               // I is an extra argument for TreeN (its parent operation).
6978               markExtraArg(Stack.back(), I);
6979               continue;
6980             }
6981           } else if (ReducedValueData &&
6982                      ReducedValueData != OpData) {
6983             // Make sure that the opcodes of the operations that we are going to
6984             // reduce match.
6985             // I is an extra argument for TreeN (its parent operation).
6986             markExtraArg(Stack.back(), I);
6987             continue;
6988           } else if (!ReducedValueData)
6989             ReducedValueData = OpData;
6990 
6991           Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
6992           continue;
6993         }
6994       }
6995       // NextV is an extra argument for TreeN (its parent operation).
6996       markExtraArg(Stack.back(), NextV);
6997     }
6998     return true;
6999   }
7000 
7001   /// Attempt to vectorize the tree found by matchAssociativeReduction.
7002   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
7003     // If there are a sufficient number of reduction values, reduce
7004     // to a nearby power-of-2. We can safely generate oversized
7005     // vectors and rely on the backend to split them to legal sizes.
7006     unsigned NumReducedVals = ReducedVals.size();
7007     if (NumReducedVals < 4)
7008       return false;
7009 
7010     // FIXME: Fast-math-flags should be set based on the instructions in the
7011     //        reduction (not all of 'fast' are required).
7012     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
7013     FastMathFlags Unsafe;
7014     Unsafe.setFast();
7015     Builder.setFastMathFlags(Unsafe);
7016 
7017     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
7018     // The same extra argument may be used several times, so log each attempt
7019     // to use it.
7020     for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
7021       assert(Pair.first && "DebugLoc must be set.");
7022       ExternallyUsedValues[Pair.second].push_back(Pair.first);
7023     }
7024 
7025     // The compare instruction of a min/max is the insertion point for new
7026     // instructions and may be replaced with a new compare instruction.
7027     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
7028       assert(isa<SelectInst>(RdxRootInst) &&
7029              "Expected min/max reduction to have select root instruction");
7030       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
7031       assert(isa<Instruction>(ScalarCond) &&
7032              "Expected min/max reduction to have compare condition");
7033       return cast<Instruction>(ScalarCond);
7034     };
7035 
7036     // The reduction root is used as the insertion point for new instructions,
7037     // so set it as externally used to prevent it from being deleted.
7038     ExternallyUsedValues[ReductionRoot];
7039     SmallVector<Value *, 16> IgnoreList;
7040     for (ReductionOpsType &RdxOp : ReductionOps)
7041       IgnoreList.append(RdxOp.begin(), RdxOp.end());
7042 
7043     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
7044     if (NumReducedVals > ReduxWidth) {
7045       // In the loop below, we are building a tree based on a window of
7046       // 'ReduxWidth' values.
7047       // If the operands of those values have common traits (compare predicate,
7048       // constant operand, etc), then we want to group those together to
7049       // minimize the cost of the reduction.
7050 
7051       // TODO: This should be extended to count common operands for
7052       //       compares and binops.
7053 
7054       // Step 1: Count the number of times each compare predicate occurs.
7055       SmallDenseMap<unsigned, unsigned> PredCountMap;
7056       for (Value *RdxVal : ReducedVals) {
7057         CmpInst::Predicate Pred;
7058         if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
7059           ++PredCountMap[Pred];
7060       }
7061       // Step 2: Sort the values so the most common predicates come first.
7062       stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
7063         CmpInst::Predicate PredA, PredB;
7064         if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
7065             match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
7066           return PredCountMap[PredA] > PredCountMap[PredB];
7067         }
7068         return false;
7069       });
7070     }
7071 
7072     Value *VectorizedTree = nullptr;
7073     unsigned i = 0;
7074     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
7075       ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
7076       V.buildTree(VL, ExternallyUsedValues, IgnoreList);
7077       Optional<ArrayRef<unsigned>> Order = V.bestOrder();
7078       if (Order) {
7079         assert(Order->size() == VL.size() &&
7080                "Order size must be the same as number of vectorized "
7081                "instructions.");
7082         // TODO: reorder tree nodes without tree rebuilding.
7083         SmallVector<Value *, 4> ReorderedOps(VL.size());
7084         llvm::transform(*Order, ReorderedOps.begin(),
7085                         [VL](const unsigned Idx) { return VL[Idx]; });
7086         V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
7087       }
7088       if (V.isTreeTinyAndNotFullyVectorizable())
7089         break;
7090       if (V.isLoadCombineReductionCandidate(ReductionData.getOpcode()))
7091         break;
7092 
7093       V.computeMinimumValueSizes();
7094 
7095       // Estimate cost.
7096       InstructionCost TreeCost = V.getTreeCost();
7097       InstructionCost ReductionCost =
7098           getReductionCost(TTI, ReducedVals[i], ReduxWidth);
7099       InstructionCost Cost = TreeCost + ReductionCost;
7100       if (!Cost.isValid()) {
7101         LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
7102         return false;
7103       }
7104       if (Cost >= -SLPCostThreshold) {
7105         V.getORE()->emit([&]() {
7106           return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
7107                                           cast<Instruction>(VL[0]))
7108                  << "Vectorizing horizontal reduction is possible"
7109                  << "but not beneficial with cost " << ore::NV("Cost", Cost)
7110                  << " and threshold "
7111                  << ore::NV("Threshold", -SLPCostThreshold);
7112         });
7113         break;
7114       }
7115 
7116       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
7117                         << Cost << ". (HorRdx)\n");
7118       V.getORE()->emit([&]() {
7119         return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
7120                                   cast<Instruction>(VL[0]))
7121                << "Vectorized horizontal reduction with cost "
7122                << ore::NV("Cost", Cost) << " and with tree size "
7123                << ore::NV("TreeSize", V.getTreeSize());
7124       });
7125 
7126       // Vectorize a tree.
7127       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
7128       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
7129 
7130       // Emit a reduction. For min/max, the root is a select, but the insertion
7131       // point is the compare condition of that select.
7132       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
7133       if (ReductionData.isMinMax())
7134         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
7135       else
7136         Builder.SetInsertPoint(RdxRootInst);
7137 
7138       Value *ReducedSubTree =
7139           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
7140 
7141       if (!VectorizedTree) {
7142         // Initialize the final value in the reduction.
7143         VectorizedTree = ReducedSubTree;
7144       } else {
7145         // Update the final value in the reduction.
7146         Builder.SetCurrentDebugLocation(Loc);
7147         VectorizedTree = ReductionData.createOp(
7148             Builder, VectorizedTree, ReducedSubTree, "op.rdx", ReductionOps);
7149       }
7150       i += ReduxWidth;
7151       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
7152     }
7153 
7154     if (VectorizedTree) {
7155       // Finish the reduction.
7156       for (; i < NumReducedVals; ++i) {
7157         auto *I = cast<Instruction>(ReducedVals[i]);
7158         Builder.SetCurrentDebugLocation(I->getDebugLoc());
7159         VectorizedTree = ReductionData.createOp(Builder, VectorizedTree, I, "",
7160                                                 ReductionOps);
7161       }
7162       for (auto &Pair : ExternallyUsedValues) {
7163         // Add each externally used value to the final reduction.
7164         for (auto *I : Pair.second) {
7165           Builder.SetCurrentDebugLocation(I->getDebugLoc());
7166           VectorizedTree = ReductionData.createOp(Builder, VectorizedTree,
7167                                                   Pair.first, "op.extra", I);
7168         }
7169       }
7170 
7171       // Update users. For a min/max reduction that ends with a compare and
7172       // select, we also have to RAUW for the compare instruction feeding the
7173       // reduction root. That's because the original compare may have extra uses
7174       // besides the final select of the reduction.
7175       if (ReductionData.isMinMax()) {
7176         if (auto *VecSelect = dyn_cast<SelectInst>(VectorizedTree)) {
7177           Instruction *ScalarCmp =
7178               getCmpForMinMaxReduction(cast<Instruction>(ReductionRoot));
7179           ScalarCmp->replaceAllUsesWith(VecSelect->getCondition());
7180         }
7181       }
7182       ReductionRoot->replaceAllUsesWith(VectorizedTree);
7183 
7184       // Mark all scalar reduction ops for deletion, they are replaced by the
7185       // vector reductions.
7186       V.eraseInstructions(IgnoreList);
7187     }
7188     return VectorizedTree != nullptr;
7189   }
7190 
7191   unsigned numReductionValues() const {
7192     return ReducedVals.size();
7193   }
7194 
7195 private:
7196   /// Calculate the cost of a reduction.
7197   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
7198                        unsigned ReduxWidth) {
7199     Type *ScalarTy = FirstReducedVal->getType();
7200     auto *VecTy = FixedVectorType::get(ScalarTy, ReduxWidth);
7201 
7202     int PairwiseRdxCost;
7203     int SplittingRdxCost;
7204     switch (ReductionData.getKind()) {
7205     case RK_Arithmetic:
7206       PairwiseRdxCost =
7207           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
7208                                           /*IsPairwiseForm=*/true);
7209       SplittingRdxCost =
7210           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
7211                                           /*IsPairwiseForm=*/false);
7212       break;
7213     case RK_SMin:
7214     case RK_SMax:
7215     case RK_UMin:
7216     case RK_UMax: {
7217       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VecTy));
7218       bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
7219                         ReductionData.getKind() == RK_UMax;
7220       PairwiseRdxCost =
7221           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
7222                                       /*IsPairwiseForm=*/true, IsUnsigned);
7223       SplittingRdxCost =
7224           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
7225                                       /*IsPairwiseForm=*/false, IsUnsigned);
7226       break;
7227     }
7228     case RK_None:
7229       llvm_unreachable("Expected arithmetic or min/max reduction operation");
7230     }
7231 
7232     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
7233     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
7234 
7235     int ScalarReduxCost = 0;
7236     switch (ReductionData.getKind()) {
7237     case RK_Arithmetic:
7238       ScalarReduxCost =
7239           TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
7240       break;
7241     case RK_SMin:
7242     case RK_SMax:
7243     case RK_UMin:
7244     case RK_UMax:
7245       ScalarReduxCost =
7246           TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
7247           TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
7248                                   CmpInst::makeCmpResultType(ScalarTy));
7249       break;
7250     case RK_None:
7251       llvm_unreachable("Expected arithmetic or min/max reduction operation");
7252     }
7253     ScalarReduxCost *= (ReduxWidth - 1);
7254 
7255     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
7256                       << " for reduction that starts with " << *FirstReducedVal
7257                       << " (It is a "
7258                       << (IsPairwiseReduction ? "pairwise" : "splitting")
7259                       << " reduction)\n");
7260 
7261     return VecReduxCost - ScalarReduxCost;
7262   }
7263 
7264   /// Emit a horizontal reduction of the vectorized value.
7265   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
7266                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
7267     assert(VectorizedValue && "Need to have a vectorized tree node");
7268     assert(isPowerOf2_32(ReduxWidth) &&
7269            "We only handle power-of-two reductions for now");
7270 
7271     if (!IsPairwiseReduction) {
7272       // FIXME: The builder should use an FMF guard. It should not be hard-coded
7273       //        to 'fast'.
7274       assert(Builder.getFastMathFlags().isFast() && "Expected 'fast' FMF");
7275       return createSimpleTargetReduction(
7276           Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
7277           ReductionData.getFlags(), ReductionOps.back());
7278     }
7279 
7280     Value *TmpVec = VectorizedValue;
7281     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
7282       auto LeftMask = createRdxShuffleMask(ReduxWidth, i, true, true);
7283       auto RightMask = createRdxShuffleMask(ReduxWidth, i, true, false);
7284 
7285       Value *LeftShuf =
7286           Builder.CreateShuffleVector(TmpVec, LeftMask, "rdx.shuf.l");
7287       Value *RightShuf =
7288           Builder.CreateShuffleVector(TmpVec, RightMask, "rdx.shuf.r");
7289       TmpVec = ReductionData.createOp(Builder, LeftShuf, RightShuf, "op.rdx",
7290                                       ReductionOps);
7291     }
7292 
7293     // The result is in the first element of the vector.
7294     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
7295   }
7296 };
7297 
7298 } // end anonymous namespace
7299 
7300 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
7301   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
7302     return cast<FixedVectorType>(IE->getType())->getNumElements();
7303 
7304   unsigned AggregateSize = 1;
7305   auto *IV = cast<InsertValueInst>(InsertInst);
7306   Type *CurrentType = IV->getType();
7307   do {
7308     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
7309       for (auto *Elt : ST->elements())
7310         if (Elt != ST->getElementType(0)) // check homogeneity
7311           return None;
7312       AggregateSize *= ST->getNumElements();
7313       CurrentType = ST->getElementType(0);
7314     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
7315       AggregateSize *= AT->getNumElements();
7316       CurrentType = AT->getElementType();
7317     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
7318       AggregateSize *= VT->getNumElements();
7319       return AggregateSize;
7320     } else if (CurrentType->isSingleValueType()) {
7321       return AggregateSize;
7322     } else {
7323       return None;
7324     }
7325   } while (true);
7326 }
7327 
7328 static Optional<unsigned> getOperandIndex(Instruction *InsertInst,
7329                                           unsigned OperandOffset) {
7330   unsigned OperandIndex = OperandOffset;
7331   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
7332     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
7333       auto *VT = cast<FixedVectorType>(IE->getType());
7334       OperandIndex *= VT->getNumElements();
7335       OperandIndex += CI->getZExtValue();
7336       return OperandIndex;
7337     }
7338     return None;
7339   }
7340 
7341   auto *IV = cast<InsertValueInst>(InsertInst);
7342   Type *CurrentType = IV->getType();
7343   for (unsigned int Index : IV->indices()) {
7344     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
7345       OperandIndex *= ST->getNumElements();
7346       CurrentType = ST->getElementType(Index);
7347     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
7348       OperandIndex *= AT->getNumElements();
7349       CurrentType = AT->getElementType();
7350     } else {
7351       return None;
7352     }
7353     OperandIndex += Index;
7354   }
7355   return OperandIndex;
7356 }
7357 
7358 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
7359                                    TargetTransformInfo *TTI,
7360                                    SmallVectorImpl<Value *> &BuildVectorOpds,
7361                                    SmallVectorImpl<Value *> &InsertElts,
7362                                    unsigned OperandOffset) {
7363   do {
7364     Value *InsertedOperand = LastInsertInst->getOperand(1);
7365     Optional<unsigned> OperandIndex =
7366         getOperandIndex(LastInsertInst, OperandOffset);
7367     if (!OperandIndex)
7368       return false;
7369     if (isa<InsertElementInst>(InsertedOperand) ||
7370         isa<InsertValueInst>(InsertedOperand)) {
7371       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
7372                                   BuildVectorOpds, InsertElts, *OperandIndex))
7373         return false;
7374     } else {
7375       BuildVectorOpds[*OperandIndex] = InsertedOperand;
7376       InsertElts[*OperandIndex] = LastInsertInst;
7377     }
7378     if (isa<UndefValue>(LastInsertInst->getOperand(0)))
7379       return true;
7380     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
7381   } while (LastInsertInst != nullptr &&
7382            (isa<InsertValueInst>(LastInsertInst) ||
7383             isa<InsertElementInst>(LastInsertInst)) &&
7384            LastInsertInst->hasOneUse());
7385   return false;
7386 }
7387 
7388 /// Recognize construction of vectors like
7389 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
7390 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
7391 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
7392 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
7393 ///  starting from the last insertelement or insertvalue instruction.
7394 ///
7395 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
7396 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
7397 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
7398 ///
7399 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
7400 ///
7401 /// \return true if it matches.
7402 static bool findBuildAggregate(Instruction *LastInsertInst,
7403                                TargetTransformInfo *TTI,
7404                                SmallVectorImpl<Value *> &BuildVectorOpds,
7405                                SmallVectorImpl<Value *> &InsertElts) {
7406 
7407   assert((isa<InsertElementInst>(LastInsertInst) ||
7408           isa<InsertValueInst>(LastInsertInst)) &&
7409          "Expected insertelement or insertvalue instruction!");
7410 
7411   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
7412          "Expected empty result vectors!");
7413 
7414   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
7415   if (!AggregateSize)
7416     return false;
7417   BuildVectorOpds.resize(*AggregateSize);
7418   InsertElts.resize(*AggregateSize);
7419 
7420   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
7421                              0)) {
7422     llvm::erase_value(BuildVectorOpds, nullptr);
7423     llvm::erase_value(InsertElts, nullptr);
7424     if (BuildVectorOpds.size() >= 2)
7425       return true;
7426   }
7427 
7428   return false;
7429 }
7430 
7431 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
7432   return V->getType() < V2->getType();
7433 }
7434 
7435 /// Try and get a reduction value from a phi node.
7436 ///
7437 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
7438 /// if they come from either \p ParentBB or a containing loop latch.
7439 ///
7440 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
7441 /// if not possible.
7442 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
7443                                 BasicBlock *ParentBB, LoopInfo *LI) {
7444   // There are situations where the reduction value is not dominated by the
7445   // reduction phi. Vectorizing such cases has been reported to cause
7446   // miscompiles. See PR25787.
7447   auto DominatedReduxValue = [&](Value *R) {
7448     return isa<Instruction>(R) &&
7449            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
7450   };
7451 
7452   Value *Rdx = nullptr;
7453 
7454   // Return the incoming value if it comes from the same BB as the phi node.
7455   if (P->getIncomingBlock(0) == ParentBB) {
7456     Rdx = P->getIncomingValue(0);
7457   } else if (P->getIncomingBlock(1) == ParentBB) {
7458     Rdx = P->getIncomingValue(1);
7459   }
7460 
7461   if (Rdx && DominatedReduxValue(Rdx))
7462     return Rdx;
7463 
7464   // Otherwise, check whether we have a loop latch to look at.
7465   Loop *BBL = LI->getLoopFor(ParentBB);
7466   if (!BBL)
7467     return nullptr;
7468   BasicBlock *BBLatch = BBL->getLoopLatch();
7469   if (!BBLatch)
7470     return nullptr;
7471 
7472   // There is a loop latch, return the incoming value if it comes from
7473   // that. This reduction pattern occasionally turns up.
7474   if (P->getIncomingBlock(0) == BBLatch) {
7475     Rdx = P->getIncomingValue(0);
7476   } else if (P->getIncomingBlock(1) == BBLatch) {
7477     Rdx = P->getIncomingValue(1);
7478   }
7479 
7480   if (Rdx && DominatedReduxValue(Rdx))
7481     return Rdx;
7482 
7483   return nullptr;
7484 }
7485 
7486 /// Attempt to reduce a horizontal reduction.
7487 /// If it is legal to match a horizontal reduction feeding the phi node \a P
7488 /// with reduction operators \a Root (or one of its operands) in a basic block
7489 /// \a BB, then check if it can be done. If horizontal reduction is not found
7490 /// and root instruction is a binary operation, vectorization of the operands is
7491 /// attempted.
7492 /// \returns true if a horizontal reduction was matched and reduced or operands
7493 /// of one of the binary instruction were vectorized.
7494 /// \returns false if a horizontal reduction was not matched (or not possible)
7495 /// or no vectorization of any binary operation feeding \a Root instruction was
7496 /// performed.
7497 static bool tryToVectorizeHorReductionOrInstOperands(
7498     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
7499     TargetTransformInfo *TTI,
7500     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
7501   if (!ShouldVectorizeHor)
7502     return false;
7503 
7504   if (!Root)
7505     return false;
7506 
7507   if (Root->getParent() != BB || isa<PHINode>(Root))
7508     return false;
7509   // Start analysis starting from Root instruction. If horizontal reduction is
7510   // found, try to vectorize it. If it is not a horizontal reduction or
7511   // vectorization is not possible or not effective, and currently analyzed
7512   // instruction is a binary operation, try to vectorize the operands, using
7513   // pre-order DFS traversal order. If the operands were not vectorized, repeat
7514   // the same procedure considering each operand as a possible root of the
7515   // horizontal reduction.
7516   // Interrupt the process if the Root instruction itself was vectorized or all
7517   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
7518   SmallVector<std::pair<Instruction *, unsigned>, 8> Stack(1, {Root, 0});
7519   SmallPtrSet<Value *, 8> VisitedInstrs;
7520   bool Res = false;
7521   while (!Stack.empty()) {
7522     Instruction *Inst;
7523     unsigned Level;
7524     std::tie(Inst, Level) = Stack.pop_back_val();
7525     Value *B0, *B1;
7526     bool IsBinop = match(Inst, m_BinOp(m_Value(B0), m_Value(B1)));
7527     bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
7528     if (IsBinop || IsSelect) {
7529       HorizontalReduction HorRdx;
7530       if (HorRdx.matchAssociativeReduction(P, Inst)) {
7531         if (HorRdx.tryToReduce(R, TTI)) {
7532           Res = true;
7533           // Set P to nullptr to avoid re-analysis of phi node in
7534           // matchAssociativeReduction function unless this is the root node.
7535           P = nullptr;
7536           continue;
7537         }
7538       }
7539       if (P && IsBinop) {
7540         Inst = dyn_cast<Instruction>(B0);
7541         if (Inst == P)
7542           Inst = dyn_cast<Instruction>(B1);
7543         if (!Inst) {
7544           // Set P to nullptr to avoid re-analysis of phi node in
7545           // matchAssociativeReduction function unless this is the root node.
7546           P = nullptr;
7547           continue;
7548         }
7549       }
7550     }
7551     // Set P to nullptr to avoid re-analysis of phi node in
7552     // matchAssociativeReduction function unless this is the root node.
7553     P = nullptr;
7554     if (Vectorize(Inst, R)) {
7555       Res = true;
7556       continue;
7557     }
7558 
7559     // Try to vectorize operands.
7560     // Continue analysis for the instruction from the same basic block only to
7561     // save compile time.
7562     if (++Level < RecursionMaxDepth)
7563       for (auto *Op : Inst->operand_values())
7564         if (VisitedInstrs.insert(Op).second)
7565           if (auto *I = dyn_cast<Instruction>(Op))
7566             if (!isa<PHINode>(I) && !R.isDeleted(I) && I->getParent() == BB)
7567               Stack.emplace_back(I, Level);
7568   }
7569   return Res;
7570 }
7571 
7572 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
7573                                                  BasicBlock *BB, BoUpSLP &R,
7574                                                  TargetTransformInfo *TTI) {
7575   auto *I = dyn_cast_or_null<Instruction>(V);
7576   if (!I)
7577     return false;
7578 
7579   if (!isa<BinaryOperator>(I))
7580     P = nullptr;
7581   // Try to match and vectorize a horizontal reduction.
7582   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
7583     return tryToVectorize(I, R);
7584   };
7585   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
7586                                                   ExtraVectorization);
7587 }
7588 
7589 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
7590                                                  BasicBlock *BB, BoUpSLP &R) {
7591   const DataLayout &DL = BB->getModule()->getDataLayout();
7592   if (!R.canMapToVector(IVI->getType(), DL))
7593     return false;
7594 
7595   SmallVector<Value *, 16> BuildVectorOpds;
7596   SmallVector<Value *, 16> BuildVectorInsts;
7597   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
7598     return false;
7599 
7600   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
7601   // Aggregate value is unlikely to be processed in vector register, we need to
7602   // extract scalars into scalar registers, so NeedExtraction is set true.
7603   return tryToVectorizeList(BuildVectorOpds, R, /*AllowReorder=*/false,
7604                             BuildVectorInsts);
7605 }
7606 
7607 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
7608                                                    BasicBlock *BB, BoUpSLP &R) {
7609   SmallVector<Value *, 16> BuildVectorInsts;
7610   SmallVector<Value *, 16> BuildVectorOpds;
7611   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
7612       (llvm::all_of(BuildVectorOpds,
7613                     [](Value *V) { return isa<ExtractElementInst>(V); }) &&
7614        isShuffle(BuildVectorOpds)))
7615     return false;
7616 
7617   // Vectorize starting with the build vector operands ignoring the BuildVector
7618   // instructions for the purpose of scheduling and user extraction.
7619   return tryToVectorizeList(BuildVectorOpds, R, /*AllowReorder=*/false,
7620                             BuildVectorInsts);
7621 }
7622 
7623 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
7624                                          BoUpSLP &R) {
7625   if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
7626     return true;
7627 
7628   bool OpsChanged = false;
7629   for (int Idx = 0; Idx < 2; ++Idx) {
7630     OpsChanged |=
7631         vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
7632   }
7633   return OpsChanged;
7634 }
7635 
7636 bool SLPVectorizerPass::vectorizeSimpleInstructions(
7637     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R) {
7638   bool OpsChanged = false;
7639   for (auto *I : reverse(Instructions)) {
7640     if (R.isDeleted(I))
7641       continue;
7642     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
7643       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
7644     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
7645       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
7646     else if (auto *CI = dyn_cast<CmpInst>(I))
7647       OpsChanged |= vectorizeCmpInst(CI, BB, R);
7648   }
7649   Instructions.clear();
7650   return OpsChanged;
7651 }
7652 
7653 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
7654   bool Changed = false;
7655   SmallVector<Value *, 4> Incoming;
7656   SmallPtrSet<Value *, 16> VisitedInstrs;
7657 
7658   bool HaveVectorizedPhiNodes = true;
7659   while (HaveVectorizedPhiNodes) {
7660     HaveVectorizedPhiNodes = false;
7661 
7662     // Collect the incoming values from the PHIs.
7663     Incoming.clear();
7664     for (Instruction &I : *BB) {
7665       PHINode *P = dyn_cast<PHINode>(&I);
7666       if (!P)
7667         break;
7668 
7669       if (!VisitedInstrs.count(P) && !R.isDeleted(P))
7670         Incoming.push_back(P);
7671     }
7672 
7673     // Sort by type.
7674     llvm::stable_sort(Incoming, PhiTypeSorterFunc);
7675 
7676     // Try to vectorize elements base on their type.
7677     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
7678                                            E = Incoming.end();
7679          IncIt != E;) {
7680 
7681       // Look for the next elements with the same type.
7682       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
7683       while (SameTypeIt != E &&
7684              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
7685         VisitedInstrs.insert(*SameTypeIt);
7686         ++SameTypeIt;
7687       }
7688 
7689       // Try to vectorize them.
7690       unsigned NumElts = (SameTypeIt - IncIt);
7691       LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("
7692                         << NumElts << ")\n");
7693       // The order in which the phi nodes appear in the program does not matter.
7694       // So allow tryToVectorizeList to reorder them if it is beneficial. This
7695       // is done when there are exactly two elements since tryToVectorizeList
7696       // asserts that there are only two values when AllowReorder is true.
7697       bool AllowReorder = NumElts == 2;
7698       if (NumElts > 1 &&
7699           tryToVectorizeList(makeArrayRef(IncIt, NumElts), R, AllowReorder)) {
7700         // Success start over because instructions might have been changed.
7701         HaveVectorizedPhiNodes = true;
7702         Changed = true;
7703         break;
7704       }
7705 
7706       // Start over at the next instruction of a different type (or the end).
7707       IncIt = SameTypeIt;
7708     }
7709   }
7710 
7711   VisitedInstrs.clear();
7712 
7713   SmallVector<Instruction *, 8> PostProcessInstructions;
7714   SmallDenseSet<Instruction *, 4> KeyNodes;
7715   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
7716     // Skip instructions with scalable type. The num of elements is unknown at
7717     // compile-time for scalable type.
7718     if (isa<ScalableVectorType>(it->getType()))
7719       continue;
7720 
7721     // Skip instructions marked for the deletion.
7722     if (R.isDeleted(&*it))
7723       continue;
7724     // We may go through BB multiple times so skip the one we have checked.
7725     if (!VisitedInstrs.insert(&*it).second) {
7726       if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
7727           vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
7728         // We would like to start over since some instructions are deleted
7729         // and the iterator may become invalid value.
7730         Changed = true;
7731         it = BB->begin();
7732         e = BB->end();
7733       }
7734       continue;
7735     }
7736 
7737     if (isa<DbgInfoIntrinsic>(it))
7738       continue;
7739 
7740     // Try to vectorize reductions that use PHINodes.
7741     if (PHINode *P = dyn_cast<PHINode>(it)) {
7742       // Check that the PHI is a reduction PHI.
7743       if (P->getNumIncomingValues() == 2) {
7744         // Try to match and vectorize a horizontal reduction.
7745         if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
7746                                      TTI)) {
7747           Changed = true;
7748           it = BB->begin();
7749           e = BB->end();
7750           continue;
7751         }
7752       }
7753       // Try to vectorize the incoming values of the PHI, to catch reductions
7754       // that feed into PHIs.
7755       for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
7756         // Skip if the incoming block is the current BB for now. Also, bypass
7757         // unreachable IR for efficiency and to avoid crashing.
7758         // TODO: Collect the skipped incoming values and try to vectorize them
7759         // after processing BB.
7760         if (BB == P->getIncomingBlock(I) ||
7761             !DT->isReachableFromEntry(P->getIncomingBlock(I)))
7762           continue;
7763 
7764         Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
7765                                             P->getIncomingBlock(I), R, TTI);
7766       }
7767       continue;
7768     }
7769 
7770     // Ran into an instruction without users, like terminator, or function call
7771     // with ignored return value, store. Ignore unused instructions (basing on
7772     // instruction type, except for CallInst and InvokeInst).
7773     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
7774                             isa<InvokeInst>(it))) {
7775       KeyNodes.insert(&*it);
7776       bool OpsChanged = false;
7777       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
7778         for (auto *V : it->operand_values()) {
7779           // Try to match and vectorize a horizontal reduction.
7780           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
7781         }
7782       }
7783       // Start vectorization of post-process list of instructions from the
7784       // top-tree instructions to try to vectorize as many instructions as
7785       // possible.
7786       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
7787       if (OpsChanged) {
7788         // We would like to start over since some instructions are deleted
7789         // and the iterator may become invalid value.
7790         Changed = true;
7791         it = BB->begin();
7792         e = BB->end();
7793         continue;
7794       }
7795     }
7796 
7797     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
7798         isa<InsertValueInst>(it))
7799       PostProcessInstructions.push_back(&*it);
7800   }
7801 
7802   return Changed;
7803 }
7804 
7805 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
7806   auto Changed = false;
7807   for (auto &Entry : GEPs) {
7808     // If the getelementptr list has fewer than two elements, there's nothing
7809     // to do.
7810     if (Entry.second.size() < 2)
7811       continue;
7812 
7813     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
7814                       << Entry.second.size() << ".\n");
7815 
7816     // Process the GEP list in chunks suitable for the target's supported
7817     // vector size. If a vector register can't hold 1 element, we are done. We
7818     // are trying to vectorize the index computations, so the maximum number of
7819     // elements is based on the size of the index expression, rather than the
7820     // size of the GEP itself (the target's pointer size).
7821     unsigned MaxVecRegSize = R.getMaxVecRegSize();
7822     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
7823     if (MaxVecRegSize < EltSize)
7824       continue;
7825 
7826     unsigned MaxElts = MaxVecRegSize / EltSize;
7827     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
7828       auto Len = std::min<unsigned>(BE - BI, MaxElts);
7829       ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
7830 
7831       // Initialize a set a candidate getelementptrs. Note that we use a
7832       // SetVector here to preserve program order. If the index computations
7833       // are vectorizable and begin with loads, we want to minimize the chance
7834       // of having to reorder them later.
7835       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
7836 
7837       // Some of the candidates may have already been vectorized after we
7838       // initially collected them. If so, they are marked as deleted, so remove
7839       // them from the set of candidates.
7840       Candidates.remove_if(
7841           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
7842 
7843       // Remove from the set of candidates all pairs of getelementptrs with
7844       // constant differences. Such getelementptrs are likely not good
7845       // candidates for vectorization in a bottom-up phase since one can be
7846       // computed from the other. We also ensure all candidate getelementptr
7847       // indices are unique.
7848       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
7849         auto *GEPI = GEPList[I];
7850         if (!Candidates.count(GEPI))
7851           continue;
7852         auto *SCEVI = SE->getSCEV(GEPList[I]);
7853         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
7854           auto *GEPJ = GEPList[J];
7855           auto *SCEVJ = SE->getSCEV(GEPList[J]);
7856           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
7857             Candidates.remove(GEPI);
7858             Candidates.remove(GEPJ);
7859           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
7860             Candidates.remove(GEPJ);
7861           }
7862         }
7863       }
7864 
7865       // We break out of the above computation as soon as we know there are
7866       // fewer than two candidates remaining.
7867       if (Candidates.size() < 2)
7868         continue;
7869 
7870       // Add the single, non-constant index of each candidate to the bundle. We
7871       // ensured the indices met these constraints when we originally collected
7872       // the getelementptrs.
7873       SmallVector<Value *, 16> Bundle(Candidates.size());
7874       auto BundleIndex = 0u;
7875       for (auto *V : Candidates) {
7876         auto *GEP = cast<GetElementPtrInst>(V);
7877         auto *GEPIdx = GEP->idx_begin()->get();
7878         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
7879         Bundle[BundleIndex++] = GEPIdx;
7880       }
7881 
7882       // Try and vectorize the indices. We are currently only interested in
7883       // gather-like cases of the form:
7884       //
7885       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
7886       //
7887       // where the loads of "a", the loads of "b", and the subtractions can be
7888       // performed in parallel. It's likely that detecting this pattern in a
7889       // bottom-up phase will be simpler and less costly than building a
7890       // full-blown top-down phase beginning at the consecutive loads.
7891       Changed |= tryToVectorizeList(Bundle, R);
7892     }
7893   }
7894   return Changed;
7895 }
7896 
7897 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
7898   bool Changed = false;
7899   // Attempt to sort and vectorize each of the store-groups.
7900   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
7901        ++it) {
7902     if (it->second.size() < 2)
7903       continue;
7904 
7905     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
7906                       << it->second.size() << ".\n");
7907 
7908     Changed |= vectorizeStores(it->second, R);
7909   }
7910   return Changed;
7911 }
7912 
7913 char SLPVectorizer::ID = 0;
7914 
7915 static const char lv_name[] = "SLP Vectorizer";
7916 
7917 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
7918 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7919 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7920 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7921 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7922 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
7923 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7924 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7925 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7926 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
7927 
7928 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
7929