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