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