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