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