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   Instruction *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 ValueOp;
2988       for (Value *V : E->Scalars)
2989         ValueOp.push_back(cast<StoreInst>(V)->getValueOperand());
2990 
2991       setInsertPointAfterBundle(E->Scalars, VL0);
2992 
2993       Value *VecValue = vectorizeTree(ValueOp);
2994       Value *VecPtr = Builder.CreateBitCast(SI->getPointerOperand(),
2995                                             VecTy->getPointerTo(AS));
2996       StoreInst *S = Builder.CreateStore(VecValue, VecPtr);
2997 
2998       // The pointer operand uses an in-tree scalar so we add the new BitCast to
2999       // ExternalUses list to make sure that an extract will be generated in the
3000       // future.
3001       Value *PO = SI->getPointerOperand();
3002       if (getTreeEntry(PO))
3003         ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
3004 
3005       if (!Alignment) {
3006         Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
3007       }
3008       S->setAlignment(Alignment);
3009       E->VectorizedValue = S;
3010       ++NumVectorInstructions;
3011       return propagateMetadata(S, E->Scalars);
3012     }
3013     case Instruction::GetElementPtr: {
3014       setInsertPointAfterBundle(E->Scalars, VL0);
3015 
3016       ValueList Op0VL;
3017       for (Value *V : E->Scalars)
3018         Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
3019 
3020       Value *Op0 = vectorizeTree(Op0VL);
3021 
3022       std::vector<Value *> OpVecs;
3023       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
3024            ++j) {
3025         ValueList OpVL;
3026         for (Value *V : E->Scalars)
3027           OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
3028 
3029         Value *OpVec = vectorizeTree(OpVL);
3030         OpVecs.push_back(OpVec);
3031       }
3032 
3033       Value *V = Builder.CreateGEP(
3034           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
3035       E->VectorizedValue = V;
3036       ++NumVectorInstructions;
3037 
3038       if (Instruction *I = dyn_cast<Instruction>(V))
3039         return propagateMetadata(I, E->Scalars);
3040 
3041       return V;
3042     }
3043     case Instruction::Call: {
3044       CallInst *CI = cast<CallInst>(VL0);
3045       setInsertPointAfterBundle(E->Scalars, VL0);
3046       Function *FI;
3047       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
3048       Value *ScalarArg = nullptr;
3049       if (CI && (FI = CI->getCalledFunction())) {
3050         IID = FI->getIntrinsicID();
3051       }
3052       std::vector<Value *> OpVecs;
3053       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
3054         ValueList OpVL;
3055         // ctlz,cttz and powi are special intrinsics whose second argument is
3056         // a scalar. This argument should not be vectorized.
3057         if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
3058           CallInst *CEI = cast<CallInst>(VL0);
3059           ScalarArg = CEI->getArgOperand(j);
3060           OpVecs.push_back(CEI->getArgOperand(j));
3061           continue;
3062         }
3063         for (Value *V : E->Scalars) {
3064           CallInst *CEI = cast<CallInst>(V);
3065           OpVL.push_back(CEI->getArgOperand(j));
3066         }
3067 
3068         Value *OpVec = vectorizeTree(OpVL);
3069         DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
3070         OpVecs.push_back(OpVec);
3071       }
3072 
3073       Module *M = F->getParent();
3074       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3075       Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
3076       Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
3077       SmallVector<OperandBundleDef, 1> OpBundles;
3078       CI->getOperandBundlesAsDefs(OpBundles);
3079       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
3080 
3081       // The scalar argument uses an in-tree scalar so we add the new vectorized
3082       // call to ExternalUses list to make sure that an extract will be
3083       // generated in the future.
3084       if (ScalarArg && getTreeEntry(ScalarArg))
3085         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
3086 
3087       E->VectorizedValue = V;
3088       propagateIRFlags(E->VectorizedValue, E->Scalars, VL0);
3089       ++NumVectorInstructions;
3090       return V;
3091     }
3092     case Instruction::ShuffleVector: {
3093       ValueList LHSVL, RHSVL;
3094       assert(Instruction::isBinaryOp(S.Opcode) &&
3095              "Invalid Shuffle Vector Operand");
3096       reorderAltShuffleOperands(S.Opcode, E->Scalars, LHSVL, RHSVL);
3097       setInsertPointAfterBundle(E->Scalars, VL0);
3098 
3099       Value *LHS = vectorizeTree(LHSVL);
3100       Value *RHS = vectorizeTree(RHSVL);
3101 
3102       if (Value *V = alreadyVectorized(E->Scalars, VL0))
3103         return V;
3104 
3105       // Create a vector of LHS op1 RHS
3106       Value *V0 = Builder.CreateBinOp(
3107           static_cast<Instruction::BinaryOps>(S.Opcode), LHS, RHS);
3108 
3109       unsigned AltOpcode = getAltOpcode(S.Opcode);
3110       // Create a vector of LHS op2 RHS
3111       Value *V1 = Builder.CreateBinOp(
3112           static_cast<Instruction::BinaryOps>(AltOpcode), LHS, RHS);
3113 
3114       // Create shuffle to take alternate operations from the vector.
3115       // Also, gather up odd and even scalar ops to propagate IR flags to
3116       // each vector operation.
3117       ValueList OddScalars, EvenScalars;
3118       unsigned e = E->Scalars.size();
3119       SmallVector<Constant *, 8> Mask(e);
3120       for (unsigned i = 0; i < e; ++i) {
3121         if (isOdd(i)) {
3122           Mask[i] = Builder.getInt32(e + i);
3123           OddScalars.push_back(E->Scalars[i]);
3124         } else {
3125           Mask[i] = Builder.getInt32(i);
3126           EvenScalars.push_back(E->Scalars[i]);
3127         }
3128       }
3129 
3130       Value *ShuffleMask = ConstantVector::get(Mask);
3131       propagateIRFlags(V0, EvenScalars);
3132       propagateIRFlags(V1, OddScalars);
3133 
3134       Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
3135       E->VectorizedValue = V;
3136       ++NumVectorInstructions;
3137       if (Instruction *I = dyn_cast<Instruction>(V))
3138         return propagateMetadata(I, E->Scalars);
3139 
3140       return V;
3141     }
3142     default:
3143     llvm_unreachable("unknown inst");
3144   }
3145   return nullptr;
3146 }
3147 
3148 Value *BoUpSLP::vectorizeTree() {
3149   ExtraValueToDebugLocsMap ExternallyUsedValues;
3150   return vectorizeTree(ExternallyUsedValues);
3151 }
3152 
3153 Value *
3154 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3155   // All blocks must be scheduled before any instructions are inserted.
3156   for (auto &BSIter : BlocksSchedules) {
3157     scheduleBlock(BSIter.second.get());
3158   }
3159 
3160   Builder.SetInsertPoint(&F->getEntryBlock().front());
3161   auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
3162 
3163   // If the vectorized tree can be rewritten in a smaller type, we truncate the
3164   // vectorized root. InstCombine will then rewrite the entire expression. We
3165   // sign extend the extracted values below.
3166   auto *ScalarRoot = VectorizableTree[0].Scalars[0];
3167   if (MinBWs.count(ScalarRoot)) {
3168     if (auto *I = dyn_cast<Instruction>(VectorRoot))
3169       Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
3170     auto BundleWidth = VectorizableTree[0].Scalars.size();
3171     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
3172     auto *VecTy = VectorType::get(MinTy, BundleWidth);
3173     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
3174     VectorizableTree[0].VectorizedValue = Trunc;
3175   }
3176 
3177   DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size() << " values .\n");
3178 
3179   // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
3180   // specified by ScalarType.
3181   auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
3182     if (!MinBWs.count(ScalarRoot))
3183       return Ex;
3184     if (MinBWs[ScalarRoot].second)
3185       return Builder.CreateSExt(Ex, ScalarType);
3186     return Builder.CreateZExt(Ex, ScalarType);
3187   };
3188 
3189   // Extract all of the elements with the external uses.
3190   for (const auto &ExternalUse : ExternalUses) {
3191     Value *Scalar = ExternalUse.Scalar;
3192     llvm::User *User = ExternalUse.User;
3193 
3194     // Skip users that we already RAUW. This happens when one instruction
3195     // has multiple uses of the same value.
3196     if (User && !is_contained(Scalar->users(), User))
3197       continue;
3198     TreeEntry *E = getTreeEntry(Scalar);
3199     assert(E && "Invalid scalar");
3200     assert(!E->NeedToGather && "Extracting from a gather list");
3201 
3202     Value *Vec = E->VectorizedValue;
3203     assert(Vec && "Can't find vectorizable value");
3204 
3205     Value *Lane = Builder.getInt32(ExternalUse.Lane);
3206     // If User == nullptr, the Scalar is used as extra arg. Generate
3207     // ExtractElement instruction and update the record for this scalar in
3208     // ExternallyUsedValues.
3209     if (!User) {
3210       assert(ExternallyUsedValues.count(Scalar) &&
3211              "Scalar with nullptr as an external user must be registered in "
3212              "ExternallyUsedValues map");
3213       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
3214         Builder.SetInsertPoint(VecI->getParent(),
3215                                std::next(VecI->getIterator()));
3216       } else {
3217         Builder.SetInsertPoint(&F->getEntryBlock().front());
3218       }
3219       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3220       Ex = extend(ScalarRoot, Ex, Scalar->getType());
3221       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
3222       auto &Locs = ExternallyUsedValues[Scalar];
3223       ExternallyUsedValues.insert({Ex, Locs});
3224       ExternallyUsedValues.erase(Scalar);
3225       continue;
3226     }
3227 
3228     // Generate extracts for out-of-tree users.
3229     // Find the insertion point for the extractelement lane.
3230     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
3231       if (PHINode *PH = dyn_cast<PHINode>(User)) {
3232         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
3233           if (PH->getIncomingValue(i) == Scalar) {
3234             TerminatorInst *IncomingTerminator =
3235                 PH->getIncomingBlock(i)->getTerminator();
3236             if (isa<CatchSwitchInst>(IncomingTerminator)) {
3237               Builder.SetInsertPoint(VecI->getParent(),
3238                                      std::next(VecI->getIterator()));
3239             } else {
3240               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
3241             }
3242             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3243             Ex = extend(ScalarRoot, Ex, Scalar->getType());
3244             CSEBlocks.insert(PH->getIncomingBlock(i));
3245             PH->setOperand(i, Ex);
3246           }
3247         }
3248       } else {
3249         Builder.SetInsertPoint(cast<Instruction>(User));
3250         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3251         Ex = extend(ScalarRoot, Ex, Scalar->getType());
3252         CSEBlocks.insert(cast<Instruction>(User)->getParent());
3253         User->replaceUsesOfWith(Scalar, Ex);
3254      }
3255     } else {
3256       Builder.SetInsertPoint(&F->getEntryBlock().front());
3257       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3258       Ex = extend(ScalarRoot, Ex, Scalar->getType());
3259       CSEBlocks.insert(&F->getEntryBlock());
3260       User->replaceUsesOfWith(Scalar, Ex);
3261     }
3262 
3263     DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
3264   }
3265 
3266   // For each vectorized value:
3267   for (TreeEntry &EIdx : VectorizableTree) {
3268     TreeEntry *Entry = &EIdx;
3269 
3270     // No need to handle users of gathered values.
3271     if (Entry->NeedToGather)
3272       continue;
3273 
3274     assert(Entry->VectorizedValue && "Can't find vectorizable value");
3275 
3276     // For each lane:
3277     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3278       Value *Scalar = Entry->Scalars[Lane];
3279 
3280       Type *Ty = Scalar->getType();
3281       if (!Ty->isVoidTy()) {
3282 #ifndef NDEBUG
3283         for (User *U : Scalar->users()) {
3284           DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
3285 
3286           // It is legal to replace users in the ignorelist by undef.
3287           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
3288                  "Replacing out-of-tree value with undef");
3289         }
3290 #endif
3291         Value *Undef = UndefValue::get(Ty);
3292         Scalar->replaceAllUsesWith(Undef);
3293       }
3294       DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
3295       eraseInstruction(cast<Instruction>(Scalar));
3296     }
3297   }
3298 
3299   Builder.ClearInsertionPoint();
3300 
3301   return VectorizableTree[0].VectorizedValue;
3302 }
3303 
3304 void BoUpSLP::optimizeGatherSequence() {
3305   DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
3306         << " gather sequences instructions.\n");
3307   // LICM InsertElementInst sequences.
3308   for (Instruction *it : GatherSeq) {
3309     InsertElementInst *Insert = dyn_cast<InsertElementInst>(it);
3310 
3311     if (!Insert)
3312       continue;
3313 
3314     // Check if this block is inside a loop.
3315     Loop *L = LI->getLoopFor(Insert->getParent());
3316     if (!L)
3317       continue;
3318 
3319     // Check if it has a preheader.
3320     BasicBlock *PreHeader = L->getLoopPreheader();
3321     if (!PreHeader)
3322       continue;
3323 
3324     // If the vector or the element that we insert into it are
3325     // instructions that are defined in this basic block then we can't
3326     // hoist this instruction.
3327     Instruction *CurrVec = dyn_cast<Instruction>(Insert->getOperand(0));
3328     Instruction *NewElem = dyn_cast<Instruction>(Insert->getOperand(1));
3329     if (CurrVec && L->contains(CurrVec))
3330       continue;
3331     if (NewElem && L->contains(NewElem))
3332       continue;
3333 
3334     // We can hoist this instruction. Move it to the pre-header.
3335     Insert->moveBefore(PreHeader->getTerminator());
3336   }
3337 
3338   // Make a list of all reachable blocks in our CSE queue.
3339   SmallVector<const DomTreeNode *, 8> CSEWorkList;
3340   CSEWorkList.reserve(CSEBlocks.size());
3341   for (BasicBlock *BB : CSEBlocks)
3342     if (DomTreeNode *N = DT->getNode(BB)) {
3343       assert(DT->isReachableFromEntry(N));
3344       CSEWorkList.push_back(N);
3345     }
3346 
3347   // Sort blocks by domination. This ensures we visit a block after all blocks
3348   // dominating it are visited.
3349   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
3350                    [this](const DomTreeNode *A, const DomTreeNode *B) {
3351     return DT->properlyDominates(A, B);
3352   });
3353 
3354   // Perform O(N^2) search over the gather sequences and merge identical
3355   // instructions. TODO: We can further optimize this scan if we split the
3356   // instructions into different buckets based on the insert lane.
3357   SmallVector<Instruction *, 16> Visited;
3358   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
3359     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
3360            "Worklist not sorted properly!");
3361     BasicBlock *BB = (*I)->getBlock();
3362     // For all instructions in blocks containing gather sequences:
3363     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
3364       Instruction *In = &*it++;
3365       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
3366         continue;
3367 
3368       // Check if we can replace this instruction with any of the
3369       // visited instructions.
3370       for (Instruction *v : Visited) {
3371         if (In->isIdenticalTo(v) &&
3372             DT->dominates(v->getParent(), In->getParent())) {
3373           In->replaceAllUsesWith(v);
3374           eraseInstruction(In);
3375           In = nullptr;
3376           break;
3377         }
3378       }
3379       if (In) {
3380         assert(!is_contained(Visited, In));
3381         Visited.push_back(In);
3382       }
3383     }
3384   }
3385   CSEBlocks.clear();
3386   GatherSeq.clear();
3387 }
3388 
3389 // Groups the instructions to a bundle (which is then a single scheduling entity)
3390 // and schedules instructions until the bundle gets ready.
3391 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
3392                                                  BoUpSLP *SLP, Value *OpValue) {
3393   if (isa<PHINode>(OpValue))
3394     return true;
3395 
3396   // Initialize the instruction bundle.
3397   Instruction *OldScheduleEnd = ScheduleEnd;
3398   ScheduleData *PrevInBundle = nullptr;
3399   ScheduleData *Bundle = nullptr;
3400   bool ReSchedule = false;
3401   DEBUG(dbgs() << "SLP:  bundle: " << *OpValue << "\n");
3402 
3403   // Make sure that the scheduling region contains all
3404   // instructions of the bundle.
3405   for (Value *V : VL) {
3406     if (!extendSchedulingRegion(V, OpValue))
3407       return false;
3408   }
3409 
3410   for (Value *V : VL) {
3411     ScheduleData *BundleMember = getScheduleData(V);
3412     assert(BundleMember &&
3413            "no ScheduleData for bundle member (maybe not in same basic block)");
3414     if (BundleMember->IsScheduled) {
3415       // A bundle member was scheduled as single instruction before and now
3416       // needs to be scheduled as part of the bundle. We just get rid of the
3417       // existing schedule.
3418       DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
3419                    << " was already scheduled\n");
3420       ReSchedule = true;
3421     }
3422     assert(BundleMember->isSchedulingEntity() &&
3423            "bundle member already part of other bundle");
3424     if (PrevInBundle) {
3425       PrevInBundle->NextInBundle = BundleMember;
3426     } else {
3427       Bundle = BundleMember;
3428     }
3429     BundleMember->UnscheduledDepsInBundle = 0;
3430     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
3431 
3432     // Group the instructions to a bundle.
3433     BundleMember->FirstInBundle = Bundle;
3434     PrevInBundle = BundleMember;
3435   }
3436   if (ScheduleEnd != OldScheduleEnd) {
3437     // The scheduling region got new instructions at the lower end (or it is a
3438     // new region for the first bundle). This makes it necessary to
3439     // recalculate all dependencies.
3440     // It is seldom that this needs to be done a second time after adding the
3441     // initial bundle to the region.
3442     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3443       doForAllOpcodes(I, [](ScheduleData *SD) {
3444         SD->clearDependencies();
3445       });
3446     }
3447     ReSchedule = true;
3448   }
3449   if (ReSchedule) {
3450     resetSchedule();
3451     initialFillReadyList(ReadyInsts);
3452   }
3453 
3454   DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
3455                << BB->getName() << "\n");
3456 
3457   calculateDependencies(Bundle, true, SLP);
3458 
3459   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
3460   // means that there are no cyclic dependencies and we can schedule it.
3461   // Note that's important that we don't "schedule" the bundle yet (see
3462   // cancelScheduling).
3463   while (!Bundle->isReady() && !ReadyInsts.empty()) {
3464 
3465     ScheduleData *pickedSD = ReadyInsts.back();
3466     ReadyInsts.pop_back();
3467 
3468     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
3469       schedule(pickedSD, ReadyInsts);
3470     }
3471   }
3472   if (!Bundle->isReady()) {
3473     cancelScheduling(VL, OpValue);
3474     return false;
3475   }
3476   return true;
3477 }
3478 
3479 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
3480                                                 Value *OpValue) {
3481   if (isa<PHINode>(OpValue))
3482     return;
3483 
3484   ScheduleData *Bundle = getScheduleData(OpValue);
3485   DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
3486   assert(!Bundle->IsScheduled &&
3487          "Can't cancel bundle which is already scheduled");
3488   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
3489          "tried to unbundle something which is not a bundle");
3490 
3491   // Un-bundle: make single instructions out of the bundle.
3492   ScheduleData *BundleMember = Bundle;
3493   while (BundleMember) {
3494     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
3495     BundleMember->FirstInBundle = BundleMember;
3496     ScheduleData *Next = BundleMember->NextInBundle;
3497     BundleMember->NextInBundle = nullptr;
3498     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
3499     if (BundleMember->UnscheduledDepsInBundle == 0) {
3500       ReadyInsts.insert(BundleMember);
3501     }
3502     BundleMember = Next;
3503   }
3504 }
3505 
3506 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
3507   // Allocate a new ScheduleData for the instruction.
3508   if (ChunkPos >= ChunkSize) {
3509     ScheduleDataChunks.push_back(llvm::make_unique<ScheduleData[]>(ChunkSize));
3510     ChunkPos = 0;
3511   }
3512   return &(ScheduleDataChunks.back()[ChunkPos++]);
3513 }
3514 
3515 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
3516                                                       Value *OpValue) {
3517   if (getScheduleData(V, isOneOf(OpValue, V)))
3518     return true;
3519   Instruction *I = dyn_cast<Instruction>(V);
3520   assert(I && "bundle member must be an instruction");
3521   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
3522   auto &&CheckSheduleForI = [this, OpValue](Instruction *I) -> bool {
3523     ScheduleData *ISD = getScheduleData(I);
3524     if (!ISD)
3525       return false;
3526     assert(isInSchedulingRegion(ISD) &&
3527            "ScheduleData not in scheduling region");
3528     ScheduleData *SD = allocateScheduleDataChunks();
3529     SD->Inst = I;
3530     SD->init(SchedulingRegionID, OpValue);
3531     ExtraScheduleDataMap[I][OpValue] = SD;
3532     return true;
3533   };
3534   if (CheckSheduleForI(I))
3535     return true;
3536   if (!ScheduleStart) {
3537     // It's the first instruction in the new region.
3538     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
3539     ScheduleStart = I;
3540     ScheduleEnd = I->getNextNode();
3541     if (isOneOf(OpValue, I) != I)
3542       CheckSheduleForI(I);
3543     assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3544     DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
3545     return true;
3546   }
3547   // Search up and down at the same time, because we don't know if the new
3548   // instruction is above or below the existing scheduling region.
3549   BasicBlock::reverse_iterator UpIter =
3550       ++ScheduleStart->getIterator().getReverse();
3551   BasicBlock::reverse_iterator UpperEnd = BB->rend();
3552   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
3553   BasicBlock::iterator LowerEnd = BB->end();
3554   while (true) {
3555     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
3556       DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
3557       return false;
3558     }
3559 
3560     if (UpIter != UpperEnd) {
3561       if (&*UpIter == I) {
3562         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
3563         ScheduleStart = I;
3564         if (isOneOf(OpValue, I) != I)
3565           CheckSheduleForI(I);
3566         DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I << "\n");
3567         return true;
3568       }
3569       UpIter++;
3570     }
3571     if (DownIter != LowerEnd) {
3572       if (&*DownIter == I) {
3573         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
3574                          nullptr);
3575         ScheduleEnd = I->getNextNode();
3576         if (isOneOf(OpValue, I) != I)
3577           CheckSheduleForI(I);
3578         assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3579         DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I << "\n");
3580         return true;
3581       }
3582       DownIter++;
3583     }
3584     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
3585            "instruction not found in block");
3586   }
3587   return true;
3588 }
3589 
3590 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
3591                                                 Instruction *ToI,
3592                                                 ScheduleData *PrevLoadStore,
3593                                                 ScheduleData *NextLoadStore) {
3594   ScheduleData *CurrentLoadStore = PrevLoadStore;
3595   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
3596     ScheduleData *SD = ScheduleDataMap[I];
3597     if (!SD) {
3598       // Allocate a new ScheduleData for the instruction.
3599       if (ChunkPos >= ChunkSize) {
3600         ScheduleDataChunks.push_back(
3601             llvm::make_unique<ScheduleData[]>(ChunkSize));
3602         ChunkPos = 0;
3603       }
3604       SD = allocateScheduleDataChunks();
3605       ScheduleDataMap[I] = SD;
3606       SD->Inst = I;
3607     }
3608     assert(!isInSchedulingRegion(SD) &&
3609            "new ScheduleData already in scheduling region");
3610     SD->init(SchedulingRegionID, I);
3611 
3612     if (I->mayReadOrWriteMemory()) {
3613       // Update the linked list of memory accessing instructions.
3614       if (CurrentLoadStore) {
3615         CurrentLoadStore->NextLoadStore = SD;
3616       } else {
3617         FirstLoadStoreInRegion = SD;
3618       }
3619       CurrentLoadStore = SD;
3620     }
3621   }
3622   if (NextLoadStore) {
3623     if (CurrentLoadStore)
3624       CurrentLoadStore->NextLoadStore = NextLoadStore;
3625   } else {
3626     LastLoadStoreInRegion = CurrentLoadStore;
3627   }
3628 }
3629 
3630 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
3631                                                      bool InsertInReadyList,
3632                                                      BoUpSLP *SLP) {
3633   assert(SD->isSchedulingEntity());
3634 
3635   SmallVector<ScheduleData *, 10> WorkList;
3636   WorkList.push_back(SD);
3637 
3638   while (!WorkList.empty()) {
3639     ScheduleData *SD = WorkList.back();
3640     WorkList.pop_back();
3641 
3642     ScheduleData *BundleMember = SD;
3643     while (BundleMember) {
3644       assert(isInSchedulingRegion(BundleMember));
3645       if (!BundleMember->hasValidDependencies()) {
3646 
3647         DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember << "\n");
3648         BundleMember->Dependencies = 0;
3649         BundleMember->resetUnscheduledDeps();
3650 
3651         // Handle def-use chain dependencies.
3652         if (BundleMember->OpValue != BundleMember->Inst) {
3653           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
3654           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
3655             BundleMember->Dependencies++;
3656             ScheduleData *DestBundle = UseSD->FirstInBundle;
3657             if (!DestBundle->IsScheduled)
3658               BundleMember->incrementUnscheduledDeps(1);
3659             if (!DestBundle->hasValidDependencies())
3660               WorkList.push_back(DestBundle);
3661           }
3662         } else {
3663           for (User *U : BundleMember->Inst->users()) {
3664             if (isa<Instruction>(U)) {
3665               ScheduleData *UseSD = getScheduleData(U);
3666               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
3667                 BundleMember->Dependencies++;
3668                 ScheduleData *DestBundle = UseSD->FirstInBundle;
3669                 if (!DestBundle->IsScheduled)
3670                   BundleMember->incrementUnscheduledDeps(1);
3671                 if (!DestBundle->hasValidDependencies())
3672                   WorkList.push_back(DestBundle);
3673               }
3674             } else {
3675               // I'm not sure if this can ever happen. But we need to be safe.
3676               // This lets the instruction/bundle never be scheduled and
3677               // eventually disable vectorization.
3678               BundleMember->Dependencies++;
3679               BundleMember->incrementUnscheduledDeps(1);
3680             }
3681           }
3682         }
3683 
3684         // Handle the memory dependencies.
3685         ScheduleData *DepDest = BundleMember->NextLoadStore;
3686         if (DepDest) {
3687           Instruction *SrcInst = BundleMember->Inst;
3688           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
3689           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
3690           unsigned numAliased = 0;
3691           unsigned DistToSrc = 1;
3692 
3693           while (DepDest) {
3694             assert(isInSchedulingRegion(DepDest));
3695 
3696             // We have two limits to reduce the complexity:
3697             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
3698             //    SLP->isAliased (which is the expensive part in this loop).
3699             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
3700             //    the whole loop (even if the loop is fast, it's quadratic).
3701             //    It's important for the loop break condition (see below) to
3702             //    check this limit even between two read-only instructions.
3703             if (DistToSrc >= MaxMemDepDistance ||
3704                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
3705                      (numAliased >= AliasedCheckLimit ||
3706                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
3707 
3708               // We increment the counter only if the locations are aliased
3709               // (instead of counting all alias checks). This gives a better
3710               // balance between reduced runtime and accurate dependencies.
3711               numAliased++;
3712 
3713               DepDest->MemoryDependencies.push_back(BundleMember);
3714               BundleMember->Dependencies++;
3715               ScheduleData *DestBundle = DepDest->FirstInBundle;
3716               if (!DestBundle->IsScheduled) {
3717                 BundleMember->incrementUnscheduledDeps(1);
3718               }
3719               if (!DestBundle->hasValidDependencies()) {
3720                 WorkList.push_back(DestBundle);
3721               }
3722             }
3723             DepDest = DepDest->NextLoadStore;
3724 
3725             // Example, explaining the loop break condition: Let's assume our
3726             // starting instruction is i0 and MaxMemDepDistance = 3.
3727             //
3728             //                      +--------v--v--v
3729             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
3730             //             +--------^--^--^
3731             //
3732             // MaxMemDepDistance let us stop alias-checking at i3 and we add
3733             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
3734             // Previously we already added dependencies from i3 to i6,i7,i8
3735             // (because of MaxMemDepDistance). As we added a dependency from
3736             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
3737             // and we can abort this loop at i6.
3738             if (DistToSrc >= 2 * MaxMemDepDistance)
3739                 break;
3740             DistToSrc++;
3741           }
3742         }
3743       }
3744       BundleMember = BundleMember->NextInBundle;
3745     }
3746     if (InsertInReadyList && SD->isReady()) {
3747       ReadyInsts.push_back(SD);
3748       DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst << "\n");
3749     }
3750   }
3751 }
3752 
3753 void BoUpSLP::BlockScheduling::resetSchedule() {
3754   assert(ScheduleStart &&
3755          "tried to reset schedule on block which has not been scheduled");
3756   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3757     doForAllOpcodes(I, [&](ScheduleData *SD) {
3758       assert(isInSchedulingRegion(SD) &&
3759              "ScheduleData not in scheduling region");
3760       SD->IsScheduled = false;
3761       SD->resetUnscheduledDeps();
3762     });
3763   }
3764   ReadyInsts.clear();
3765 }
3766 
3767 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
3768   if (!BS->ScheduleStart)
3769     return;
3770 
3771   DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
3772 
3773   BS->resetSchedule();
3774 
3775   // For the real scheduling we use a more sophisticated ready-list: it is
3776   // sorted by the original instruction location. This lets the final schedule
3777   // be as  close as possible to the original instruction order.
3778   struct ScheduleDataCompare {
3779     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
3780       return SD2->SchedulingPriority < SD1->SchedulingPriority;
3781     }
3782   };
3783   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
3784 
3785   // Ensure that all dependency data is updated and fill the ready-list with
3786   // initial instructions.
3787   int Idx = 0;
3788   int NumToSchedule = 0;
3789   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
3790        I = I->getNextNode()) {
3791     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
3792       assert(SD->isPartOfBundle() ==
3793                  (getTreeEntry(SD->Inst) != nullptr) &&
3794              "scheduler and vectorizer bundle mismatch");
3795       SD->FirstInBundle->SchedulingPriority = Idx++;
3796       if (SD->isSchedulingEntity()) {
3797         BS->calculateDependencies(SD, false, this);
3798         NumToSchedule++;
3799       }
3800     });
3801   }
3802   BS->initialFillReadyList(ReadyInsts);
3803 
3804   Instruction *LastScheduledInst = BS->ScheduleEnd;
3805 
3806   // Do the "real" scheduling.
3807   while (!ReadyInsts.empty()) {
3808     ScheduleData *picked = *ReadyInsts.begin();
3809     ReadyInsts.erase(ReadyInsts.begin());
3810 
3811     // Move the scheduled instruction(s) to their dedicated places, if not
3812     // there yet.
3813     ScheduleData *BundleMember = picked;
3814     while (BundleMember) {
3815       Instruction *pickedInst = BundleMember->Inst;
3816       if (LastScheduledInst->getNextNode() != pickedInst) {
3817         BS->BB->getInstList().remove(pickedInst);
3818         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
3819                                      pickedInst);
3820       }
3821       LastScheduledInst = pickedInst;
3822       BundleMember = BundleMember->NextInBundle;
3823     }
3824 
3825     BS->schedule(picked, ReadyInsts);
3826     NumToSchedule--;
3827   }
3828   assert(NumToSchedule == 0 && "could not schedule all instructions");
3829 
3830   // Avoid duplicate scheduling of the block.
3831   BS->ScheduleStart = nullptr;
3832 }
3833 
3834 unsigned BoUpSLP::getVectorElementSize(Value *V) {
3835   // If V is a store, just return the width of the stored value without
3836   // traversing the expression tree. This is the common case.
3837   if (auto *Store = dyn_cast<StoreInst>(V))
3838     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
3839 
3840   // If V is not a store, we can traverse the expression tree to find loads
3841   // that feed it. The type of the loaded value may indicate a more suitable
3842   // width than V's type. We want to base the vector element size on the width
3843   // of memory operations where possible.
3844   SmallVector<Instruction *, 16> Worklist;
3845   SmallPtrSet<Instruction *, 16> Visited;
3846   if (auto *I = dyn_cast<Instruction>(V))
3847     Worklist.push_back(I);
3848 
3849   // Traverse the expression tree in bottom-up order looking for loads. If we
3850   // encounter an instruciton we don't yet handle, we give up.
3851   auto MaxWidth = 0u;
3852   auto FoundUnknownInst = false;
3853   while (!Worklist.empty() && !FoundUnknownInst) {
3854     auto *I = Worklist.pop_back_val();
3855     Visited.insert(I);
3856 
3857     // We should only be looking at scalar instructions here. If the current
3858     // instruction has a vector type, give up.
3859     auto *Ty = I->getType();
3860     if (isa<VectorType>(Ty))
3861       FoundUnknownInst = true;
3862 
3863     // If the current instruction is a load, update MaxWidth to reflect the
3864     // width of the loaded value.
3865     else if (isa<LoadInst>(I))
3866       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
3867 
3868     // Otherwise, we need to visit the operands of the instruction. We only
3869     // handle the interesting cases from buildTree here. If an operand is an
3870     // instruction we haven't yet visited, we add it to the worklist.
3871     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
3872              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
3873       for (Use &U : I->operands())
3874         if (auto *J = dyn_cast<Instruction>(U.get()))
3875           if (!Visited.count(J))
3876             Worklist.push_back(J);
3877     }
3878 
3879     // If we don't yet handle the instruction, give up.
3880     else
3881       FoundUnknownInst = true;
3882   }
3883 
3884   // If we didn't encounter a memory access in the expression tree, or if we
3885   // gave up for some reason, just return the width of V.
3886   if (!MaxWidth || FoundUnknownInst)
3887     return DL->getTypeSizeInBits(V->getType());
3888 
3889   // Otherwise, return the maximum width we found.
3890   return MaxWidth;
3891 }
3892 
3893 // Determine if a value V in a vectorizable expression Expr can be demoted to a
3894 // smaller type with a truncation. We collect the values that will be demoted
3895 // in ToDemote and additional roots that require investigating in Roots.
3896 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
3897                                   SmallVectorImpl<Value *> &ToDemote,
3898                                   SmallVectorImpl<Value *> &Roots) {
3899   // We can always demote constants.
3900   if (isa<Constant>(V)) {
3901     ToDemote.push_back(V);
3902     return true;
3903   }
3904 
3905   // If the value is not an instruction in the expression with only one use, it
3906   // cannot be demoted.
3907   auto *I = dyn_cast<Instruction>(V);
3908   if (!I || !I->hasOneUse() || !Expr.count(I))
3909     return false;
3910 
3911   switch (I->getOpcode()) {
3912 
3913   // We can always demote truncations and extensions. Since truncations can
3914   // seed additional demotion, we save the truncated value.
3915   case Instruction::Trunc:
3916     Roots.push_back(I->getOperand(0));
3917   case Instruction::ZExt:
3918   case Instruction::SExt:
3919     break;
3920 
3921   // We can demote certain binary operations if we can demote both of their
3922   // operands.
3923   case Instruction::Add:
3924   case Instruction::Sub:
3925   case Instruction::Mul:
3926   case Instruction::And:
3927   case Instruction::Or:
3928   case Instruction::Xor:
3929     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
3930         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
3931       return false;
3932     break;
3933 
3934   // We can demote selects if we can demote their true and false values.
3935   case Instruction::Select: {
3936     SelectInst *SI = cast<SelectInst>(I);
3937     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
3938         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
3939       return false;
3940     break;
3941   }
3942 
3943   // We can demote phis if we can demote all their incoming operands. Note that
3944   // we don't need to worry about cycles since we ensure single use above.
3945   case Instruction::PHI: {
3946     PHINode *PN = cast<PHINode>(I);
3947     for (Value *IncValue : PN->incoming_values())
3948       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
3949         return false;
3950     break;
3951   }
3952 
3953   // Otherwise, conservatively give up.
3954   default:
3955     return false;
3956   }
3957 
3958   // Record the value that we can demote.
3959   ToDemote.push_back(V);
3960   return true;
3961 }
3962 
3963 void BoUpSLP::computeMinimumValueSizes() {
3964   // If there are no external uses, the expression tree must be rooted by a
3965   // store. We can't demote in-memory values, so there is nothing to do here.
3966   if (ExternalUses.empty())
3967     return;
3968 
3969   // We only attempt to truncate integer expressions.
3970   auto &TreeRoot = VectorizableTree[0].Scalars;
3971   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
3972   if (!TreeRootIT)
3973     return;
3974 
3975   // If the expression is not rooted by a store, these roots should have
3976   // external uses. We will rely on InstCombine to rewrite the expression in
3977   // the narrower type. However, InstCombine only rewrites single-use values.
3978   // This means that if a tree entry other than a root is used externally, it
3979   // must have multiple uses and InstCombine will not rewrite it. The code
3980   // below ensures that only the roots are used externally.
3981   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
3982   for (auto &EU : ExternalUses)
3983     if (!Expr.erase(EU.Scalar))
3984       return;
3985   if (!Expr.empty())
3986     return;
3987 
3988   // Collect the scalar values of the vectorizable expression. We will use this
3989   // context to determine which values can be demoted. If we see a truncation,
3990   // we mark it as seeding another demotion.
3991   for (auto &Entry : VectorizableTree)
3992     Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
3993 
3994   // Ensure the roots of the vectorizable tree don't form a cycle. They must
3995   // have a single external user that is not in the vectorizable tree.
3996   for (auto *Root : TreeRoot)
3997     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
3998       return;
3999 
4000   // Conservatively determine if we can actually truncate the roots of the
4001   // expression. Collect the values that can be demoted in ToDemote and
4002   // additional roots that require investigating in Roots.
4003   SmallVector<Value *, 32> ToDemote;
4004   SmallVector<Value *, 4> Roots;
4005   for (auto *Root : TreeRoot)
4006     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
4007       return;
4008 
4009   // The maximum bit width required to represent all the values that can be
4010   // demoted without loss of precision. It would be safe to truncate the roots
4011   // of the expression to this width.
4012   auto MaxBitWidth = 8u;
4013 
4014   // We first check if all the bits of the roots are demanded. If they're not,
4015   // we can truncate the roots to this narrower type.
4016   for (auto *Root : TreeRoot) {
4017     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
4018     MaxBitWidth = std::max<unsigned>(
4019         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
4020   }
4021 
4022   // True if the roots can be zero-extended back to their original type, rather
4023   // than sign-extended. We know that if the leading bits are not demanded, we
4024   // can safely zero-extend. So we initialize IsKnownPositive to True.
4025   bool IsKnownPositive = true;
4026 
4027   // If all the bits of the roots are demanded, we can try a little harder to
4028   // compute a narrower type. This can happen, for example, if the roots are
4029   // getelementptr indices. InstCombine promotes these indices to the pointer
4030   // width. Thus, all their bits are technically demanded even though the
4031   // address computation might be vectorized in a smaller type.
4032   //
4033   // We start by looking at each entry that can be demoted. We compute the
4034   // maximum bit width required to store the scalar by using ValueTracking to
4035   // compute the number of high-order bits we can truncate.
4036   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType())) {
4037     MaxBitWidth = 8u;
4038 
4039     // Determine if the sign bit of all the roots is known to be zero. If not,
4040     // IsKnownPositive is set to False.
4041     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
4042       KnownBits Known = computeKnownBits(R, *DL);
4043       return Known.isNonNegative();
4044     });
4045 
4046     // Determine the maximum number of bits required to store the scalar
4047     // values.
4048     for (auto *Scalar : ToDemote) {
4049       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
4050       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
4051       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
4052     }
4053 
4054     // If we can't prove that the sign bit is zero, we must add one to the
4055     // maximum bit width to account for the unknown sign bit. This preserves
4056     // the existing sign bit so we can safely sign-extend the root back to the
4057     // original type. Otherwise, if we know the sign bit is zero, we will
4058     // zero-extend the root instead.
4059     //
4060     // FIXME: This is somewhat suboptimal, as there will be cases where adding
4061     //        one to the maximum bit width will yield a larger-than-necessary
4062     //        type. In general, we need to add an extra bit only if we can't
4063     //        prove that the upper bit of the original type is equal to the
4064     //        upper bit of the proposed smaller type. If these two bits are the
4065     //        same (either zero or one) we know that sign-extending from the
4066     //        smaller type will result in the same value. Here, since we can't
4067     //        yet prove this, we are just making the proposed smaller type
4068     //        larger to ensure correctness.
4069     if (!IsKnownPositive)
4070       ++MaxBitWidth;
4071   }
4072 
4073   // Round MaxBitWidth up to the next power-of-two.
4074   if (!isPowerOf2_64(MaxBitWidth))
4075     MaxBitWidth = NextPowerOf2(MaxBitWidth);
4076 
4077   // If the maximum bit width we compute is less than the with of the roots'
4078   // type, we can proceed with the narrowing. Otherwise, do nothing.
4079   if (MaxBitWidth >= TreeRootIT->getBitWidth())
4080     return;
4081 
4082   // If we can truncate the root, we must collect additional values that might
4083   // be demoted as a result. That is, those seeded by truncations we will
4084   // modify.
4085   while (!Roots.empty())
4086     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
4087 
4088   // Finally, map the values we can demote to the maximum bit with we computed.
4089   for (auto *Scalar : ToDemote)
4090     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
4091 }
4092 
4093 namespace {
4094 
4095 /// The SLPVectorizer Pass.
4096 struct SLPVectorizer : public FunctionPass {
4097   SLPVectorizerPass Impl;
4098 
4099   /// Pass identification, replacement for typeid
4100   static char ID;
4101 
4102   explicit SLPVectorizer() : FunctionPass(ID) {
4103     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
4104   }
4105 
4106   bool doInitialization(Module &M) override {
4107     return false;
4108   }
4109 
4110   bool runOnFunction(Function &F) override {
4111     if (skipFunction(F))
4112       return false;
4113 
4114     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4115     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
4116     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
4117     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
4118     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4119     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4120     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4121     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4122     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
4123     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
4124 
4125     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4126   }
4127 
4128   void getAnalysisUsage(AnalysisUsage &AU) const override {
4129     FunctionPass::getAnalysisUsage(AU);
4130     AU.addRequired<AssumptionCacheTracker>();
4131     AU.addRequired<ScalarEvolutionWrapperPass>();
4132     AU.addRequired<AAResultsWrapperPass>();
4133     AU.addRequired<TargetTransformInfoWrapperPass>();
4134     AU.addRequired<LoopInfoWrapperPass>();
4135     AU.addRequired<DominatorTreeWrapperPass>();
4136     AU.addRequired<DemandedBitsWrapperPass>();
4137     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
4138     AU.addPreserved<LoopInfoWrapperPass>();
4139     AU.addPreserved<DominatorTreeWrapperPass>();
4140     AU.addPreserved<AAResultsWrapperPass>();
4141     AU.addPreserved<GlobalsAAWrapperPass>();
4142     AU.setPreservesCFG();
4143   }
4144 };
4145 
4146 } // end anonymous namespace
4147 
4148 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
4149   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
4150   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
4151   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
4152   auto *AA = &AM.getResult<AAManager>(F);
4153   auto *LI = &AM.getResult<LoopAnalysis>(F);
4154   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
4155   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
4156   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
4157   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
4158 
4159   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4160   if (!Changed)
4161     return PreservedAnalyses::all();
4162 
4163   PreservedAnalyses PA;
4164   PA.preserveSet<CFGAnalyses>();
4165   PA.preserve<AAManager>();
4166   PA.preserve<GlobalsAA>();
4167   return PA;
4168 }
4169 
4170 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
4171                                 TargetTransformInfo *TTI_,
4172                                 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
4173                                 LoopInfo *LI_, DominatorTree *DT_,
4174                                 AssumptionCache *AC_, DemandedBits *DB_,
4175                                 OptimizationRemarkEmitter *ORE_) {
4176   SE = SE_;
4177   TTI = TTI_;
4178   TLI = TLI_;
4179   AA = AA_;
4180   LI = LI_;
4181   DT = DT_;
4182   AC = AC_;
4183   DB = DB_;
4184   DL = &F.getParent()->getDataLayout();
4185 
4186   Stores.clear();
4187   GEPs.clear();
4188   bool Changed = false;
4189 
4190   // If the target claims to have no vector registers don't attempt
4191   // vectorization.
4192   if (!TTI->getNumberOfRegisters(true))
4193     return false;
4194 
4195   // Don't vectorize when the attribute NoImplicitFloat is used.
4196   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
4197     return false;
4198 
4199   DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
4200 
4201   // Use the bottom up slp vectorizer to construct chains that start with
4202   // store instructions.
4203   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
4204 
4205   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
4206   // delete instructions.
4207 
4208   // Scan the blocks in the function in post order.
4209   for (auto BB : post_order(&F.getEntryBlock())) {
4210     collectSeedInstructions(BB);
4211 
4212     // Vectorize trees that end at stores.
4213     if (!Stores.empty()) {
4214       DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
4215                    << " underlying objects.\n");
4216       Changed |= vectorizeStoreChains(R);
4217     }
4218 
4219     // Vectorize trees that end at reductions.
4220     Changed |= vectorizeChainsInBlock(BB, R);
4221 
4222     // Vectorize the index computations of getelementptr instructions. This
4223     // is primarily intended to catch gather-like idioms ending at
4224     // non-consecutive loads.
4225     if (!GEPs.empty()) {
4226       DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
4227                    << " underlying objects.\n");
4228       Changed |= vectorizeGEPIndices(BB, R);
4229     }
4230   }
4231 
4232   if (Changed) {
4233     R.optimizeGatherSequence();
4234     DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
4235     DEBUG(verifyFunction(F));
4236   }
4237   return Changed;
4238 }
4239 
4240 /// \brief Check that the Values in the slice in VL array are still existent in
4241 /// the WeakTrackingVH array.
4242 /// Vectorization of part of the VL array may cause later values in the VL array
4243 /// to become invalid. We track when this has happened in the WeakTrackingVH
4244 /// array.
4245 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL,
4246                                ArrayRef<WeakTrackingVH> VH, unsigned SliceBegin,
4247                                unsigned SliceSize) {
4248   VL = VL.slice(SliceBegin, SliceSize);
4249   VH = VH.slice(SliceBegin, SliceSize);
4250   return !std::equal(VL.begin(), VL.end(), VH.begin());
4251 }
4252 
4253 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
4254                                             unsigned VecRegSize) {
4255   unsigned ChainLen = Chain.size();
4256   DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
4257         << "\n");
4258   unsigned Sz = R.getVectorElementSize(Chain[0]);
4259   unsigned VF = VecRegSize / Sz;
4260 
4261   if (!isPowerOf2_32(Sz) || VF < 2)
4262     return false;
4263 
4264   // Keep track of values that were deleted by vectorizing in the loop below.
4265   SmallVector<WeakTrackingVH, 8> TrackValues(Chain.begin(), Chain.end());
4266 
4267   bool Changed = false;
4268   // Look for profitable vectorizable trees at all offsets, starting at zero.
4269   for (unsigned i = 0, e = ChainLen; i < e; ++i) {
4270     if (i + VF > e)
4271       break;
4272 
4273     // Check that a previous iteration of this loop did not delete the Value.
4274     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
4275       continue;
4276 
4277     DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
4278           << "\n");
4279     ArrayRef<Value *> Operands = Chain.slice(i, VF);
4280 
4281     R.buildTree(Operands);
4282     if (R.isTreeTinyAndNotFullyVectorizable())
4283       continue;
4284 
4285     R.computeMinimumValueSizes();
4286 
4287     int Cost = R.getTreeCost();
4288 
4289     DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
4290     if (Cost < -SLPCostThreshold) {
4291       DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
4292 
4293       using namespace ore;
4294 
4295       R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
4296                                           cast<StoreInst>(Chain[i]))
4297                        << "Stores SLP vectorized with cost " << NV("Cost", Cost)
4298                        << " and with tree size "
4299                        << NV("TreeSize", R.getTreeSize()));
4300 
4301       R.vectorizeTree();
4302 
4303       // Move to the next bundle.
4304       i += VF - 1;
4305       Changed = true;
4306     }
4307   }
4308 
4309   return Changed;
4310 }
4311 
4312 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
4313                                         BoUpSLP &R) {
4314   SetVector<StoreInst *> Heads, Tails;
4315   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
4316 
4317   // We may run into multiple chains that merge into a single chain. We mark the
4318   // stores that we vectorized so that we don't visit the same store twice.
4319   BoUpSLP::ValueSet VectorizedStores;
4320   bool Changed = false;
4321 
4322   // Do a quadratic search on all of the given stores and find
4323   // all of the pairs of stores that follow each other.
4324   SmallVector<unsigned, 16> IndexQueue;
4325   for (unsigned i = 0, e = Stores.size(); i < e; ++i) {
4326     IndexQueue.clear();
4327     // If a store has multiple consecutive store candidates, search Stores
4328     // array according to the sequence: from i+1 to e, then from i-1 to 0.
4329     // This is because usually pairing with immediate succeeding or preceding
4330     // candidate create the best chance to find slp vectorization opportunity.
4331     unsigned j = 0;
4332     for (j = i + 1; j < e; ++j)
4333       IndexQueue.push_back(j);
4334     for (j = i; j > 0; --j)
4335       IndexQueue.push_back(j - 1);
4336 
4337     for (auto &k : IndexQueue) {
4338       if (isConsecutiveAccess(Stores[i], Stores[k], *DL, *SE)) {
4339         Tails.insert(Stores[k]);
4340         Heads.insert(Stores[i]);
4341         ConsecutiveChain[Stores[i]] = Stores[k];
4342         break;
4343       }
4344     }
4345   }
4346 
4347   // For stores that start but don't end a link in the chain:
4348   for (SetVector<StoreInst *>::iterator it = Heads.begin(), e = Heads.end();
4349        it != e; ++it) {
4350     if (Tails.count(*it))
4351       continue;
4352 
4353     // We found a store instr that starts a chain. Now follow the chain and try
4354     // to vectorize it.
4355     BoUpSLP::ValueList Operands;
4356     StoreInst *I = *it;
4357     // Collect the chain into a list.
4358     while (Tails.count(I) || Heads.count(I)) {
4359       if (VectorizedStores.count(I))
4360         break;
4361       Operands.push_back(I);
4362       // Move to the next value in the chain.
4363       I = ConsecutiveChain[I];
4364     }
4365 
4366     // FIXME: Is division-by-2 the correct step? Should we assert that the
4367     // register size is a power-of-2?
4368     for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
4369          Size /= 2) {
4370       if (vectorizeStoreChain(Operands, R, Size)) {
4371         // Mark the vectorized stores so that we don't vectorize them again.
4372         VectorizedStores.insert(Operands.begin(), Operands.end());
4373         Changed = true;
4374         break;
4375       }
4376     }
4377   }
4378 
4379   return Changed;
4380 }
4381 
4382 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
4383   // Initialize the collections. We will make a single pass over the block.
4384   Stores.clear();
4385   GEPs.clear();
4386 
4387   // Visit the store and getelementptr instructions in BB and organize them in
4388   // Stores and GEPs according to the underlying objects of their pointer
4389   // operands.
4390   for (Instruction &I : *BB) {
4391     // Ignore store instructions that are volatile or have a pointer operand
4392     // that doesn't point to a scalar type.
4393     if (auto *SI = dyn_cast<StoreInst>(&I)) {
4394       if (!SI->isSimple())
4395         continue;
4396       if (!isValidElementType(SI->getValueOperand()->getType()))
4397         continue;
4398       Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
4399     }
4400 
4401     // Ignore getelementptr instructions that have more than one index, a
4402     // constant index, or a pointer operand that doesn't point to a scalar
4403     // type.
4404     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4405       auto Idx = GEP->idx_begin()->get();
4406       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
4407         continue;
4408       if (!isValidElementType(Idx->getType()))
4409         continue;
4410       if (GEP->getType()->isVectorTy())
4411         continue;
4412       GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
4413     }
4414   }
4415 }
4416 
4417 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
4418   if (!A || !B)
4419     return false;
4420   Value *VL[] = { A, B };
4421   return tryToVectorizeList(VL, R, None, true);
4422 }
4423 
4424 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
4425                                            ArrayRef<Value *> BuildVector,
4426                                            bool AllowReorder) {
4427   if (VL.size() < 2)
4428     return false;
4429 
4430   DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = " << VL.size()
4431                << ".\n");
4432 
4433   // Check that all of the parts are scalar instructions of the same type.
4434   Instruction *I0 = dyn_cast<Instruction>(VL[0]);
4435   if (!I0)
4436     return false;
4437 
4438   unsigned Opcode0 = I0->getOpcode();
4439 
4440   unsigned Sz = R.getVectorElementSize(I0);
4441   unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
4442   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
4443   if (MaxVF < 2)
4444     return false;
4445 
4446   for (Value *V : VL) {
4447     Type *Ty = V->getType();
4448     if (!isValidElementType(Ty))
4449       return false;
4450     Instruction *Inst = dyn_cast<Instruction>(V);
4451     if (!Inst || Inst->getOpcode() != Opcode0)
4452       return false;
4453   }
4454 
4455   bool Changed = false;
4456 
4457   // Keep track of values that were deleted by vectorizing in the loop below.
4458   SmallVector<WeakTrackingVH, 8> TrackValues(VL.begin(), VL.end());
4459 
4460   unsigned NextInst = 0, MaxInst = VL.size();
4461   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
4462        VF /= 2) {
4463     // No actual vectorization should happen, if number of parts is the same as
4464     // provided vectorization factor (i.e. the scalar type is used for vector
4465     // code during codegen).
4466     auto *VecTy = VectorType::get(VL[0]->getType(), VF);
4467     if (TTI->getNumberOfParts(VecTy) == VF)
4468       continue;
4469     for (unsigned I = NextInst; I < MaxInst; ++I) {
4470       unsigned OpsWidth = 0;
4471 
4472       if (I + VF > MaxInst)
4473         OpsWidth = MaxInst - I;
4474       else
4475         OpsWidth = VF;
4476 
4477       if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
4478         break;
4479 
4480       // Check that a previous iteration of this loop did not delete the Value.
4481       if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
4482         continue;
4483 
4484       DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
4485                    << "\n");
4486       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
4487 
4488       ArrayRef<Value *> BuildVectorSlice;
4489       if (!BuildVector.empty())
4490         BuildVectorSlice = BuildVector.slice(I, OpsWidth);
4491 
4492       R.buildTree(Ops, BuildVectorSlice);
4493       // TODO: check if we can allow reordering for more cases.
4494       if (AllowReorder && R.shouldReorder()) {
4495         // Conceptually, there is nothing actually preventing us from trying to
4496         // reorder a larger list. In fact, we do exactly this when vectorizing
4497         // reductions. However, at this point, we only expect to get here when
4498         // there are exactly two operations.
4499         assert(Ops.size() == 2);
4500         assert(BuildVectorSlice.empty());
4501         Value *ReorderedOps[] = {Ops[1], Ops[0]};
4502         R.buildTree(ReorderedOps, None);
4503       }
4504       if (R.isTreeTinyAndNotFullyVectorizable())
4505         continue;
4506 
4507       R.computeMinimumValueSizes();
4508       int Cost = R.getTreeCost();
4509 
4510       if (Cost < -SLPCostThreshold) {
4511         DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
4512         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
4513                                             cast<Instruction>(Ops[0]))
4514                          << "SLP vectorized with cost " << ore::NV("Cost", Cost)
4515                          << " and with tree size "
4516                          << ore::NV("TreeSize", R.getTreeSize()));
4517 
4518         Value *VectorizedRoot = R.vectorizeTree();
4519 
4520         // Reconstruct the build vector by extracting the vectorized root. This
4521         // way we handle the case where some elements of the vector are
4522         // undefined.
4523         //  (return (inserelt <4 xi32> (insertelt undef (opd0) 0) (opd1) 2))
4524         if (!BuildVectorSlice.empty()) {
4525           // The insert point is the last build vector instruction. The
4526           // vectorized root will precede it. This guarantees that we get an
4527           // instruction. The vectorized tree could have been constant folded.
4528           Instruction *InsertAfter = cast<Instruction>(BuildVectorSlice.back());
4529           unsigned VecIdx = 0;
4530           for (auto &V : BuildVectorSlice) {
4531             IRBuilder<NoFolder> Builder(InsertAfter->getParent(),
4532                                         ++BasicBlock::iterator(InsertAfter));
4533             Instruction *I = cast<Instruction>(V);
4534             assert(isa<InsertElementInst>(I) || isa<InsertValueInst>(I));
4535             Instruction *Extract =
4536                 cast<Instruction>(Builder.CreateExtractElement(
4537                     VectorizedRoot, Builder.getInt32(VecIdx++)));
4538             I->setOperand(1, Extract);
4539             I->moveAfter(Extract);
4540             InsertAfter = I;
4541           }
4542         }
4543         // Move to the next bundle.
4544         I += VF - 1;
4545         NextInst = I + 1;
4546         Changed = true;
4547       }
4548     }
4549   }
4550 
4551   return Changed;
4552 }
4553 
4554 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
4555   if (!I)
4556     return false;
4557 
4558   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
4559     return false;
4560 
4561   Value *P = I->getParent();
4562 
4563   // Vectorize in current basic block only.
4564   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
4565   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
4566   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
4567     return false;
4568 
4569   // Try to vectorize V.
4570   if (tryToVectorizePair(Op0, Op1, R))
4571     return true;
4572 
4573   auto *A = dyn_cast<BinaryOperator>(Op0);
4574   auto *B = dyn_cast<BinaryOperator>(Op1);
4575   // Try to skip B.
4576   if (B && B->hasOneUse()) {
4577     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
4578     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
4579     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
4580       return true;
4581     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
4582       return true;
4583   }
4584 
4585   // Try to skip A.
4586   if (A && A->hasOneUse()) {
4587     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
4588     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
4589     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
4590       return true;
4591     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
4592       return true;
4593   }
4594   return false;
4595 }
4596 
4597 /// \brief Generate a shuffle mask to be used in a reduction tree.
4598 ///
4599 /// \param VecLen The length of the vector to be reduced.
4600 /// \param NumEltsToRdx The number of elements that should be reduced in the
4601 ///        vector.
4602 /// \param IsPairwise Whether the reduction is a pairwise or splitting
4603 ///        reduction. A pairwise reduction will generate a mask of
4604 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
4605 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
4606 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
4607 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
4608                                    bool IsPairwise, bool IsLeft,
4609                                    IRBuilder<> &Builder) {
4610   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
4611 
4612   SmallVector<Constant *, 32> ShuffleMask(
4613       VecLen, UndefValue::get(Builder.getInt32Ty()));
4614 
4615   if (IsPairwise)
4616     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
4617     for (unsigned i = 0; i != NumEltsToRdx; ++i)
4618       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
4619   else
4620     // Move the upper half of the vector to the lower half.
4621     for (unsigned i = 0; i != NumEltsToRdx; ++i)
4622       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
4623 
4624   return ConstantVector::get(ShuffleMask);
4625 }
4626 
4627 namespace {
4628 
4629 /// Model horizontal reductions.
4630 ///
4631 /// A horizontal reduction is a tree of reduction operations (currently add and
4632 /// fadd) that has operations that can be put into a vector as its leaf.
4633 /// For example, this tree:
4634 ///
4635 /// mul mul mul mul
4636 ///  \  /    \  /
4637 ///   +       +
4638 ///    \     /
4639 ///       +
4640 /// This tree has "mul" as its reduced values and "+" as its reduction
4641 /// operations. A reduction might be feeding into a store or a binary operation
4642 /// feeding a phi.
4643 ///    ...
4644 ///    \  /
4645 ///     +
4646 ///     |
4647 ///  phi +=
4648 ///
4649 ///  Or:
4650 ///    ...
4651 ///    \  /
4652 ///     +
4653 ///     |
4654 ///   *p =
4655 ///
4656 class HorizontalReduction {
4657   SmallVector<Value *, 16> ReductionOps;
4658   SmallVector<Value *, 32> ReducedVals;
4659   // Use map vector to make stable output.
4660   MapVector<Instruction *, Value *> ExtraArgs;
4661 
4662   /// Kind of the reduction data.
4663   enum ReductionKind {
4664     RK_None,       /// Not a reduction.
4665     RK_Arithmetic, /// Binary reduction data.
4666     RK_Min,        /// Minimum reduction data.
4667     RK_UMin,       /// Unsigned minimum reduction data.
4668     RK_Max,        /// Maximum reduction data.
4669     RK_UMax,       /// Unsigned maximum reduction data.
4670   };
4671   /// Contains info about operation, like its opcode, left and right operands.
4672   class OperationData {
4673     /// Opcode of the instruction.
4674     unsigned Opcode = 0;
4675 
4676     /// Left operand of the reduction operation.
4677     Value *LHS = nullptr;
4678 
4679     /// Right operand of the reduction operation.
4680     Value *RHS = nullptr;
4681     /// Kind of the reduction operation.
4682     ReductionKind Kind = RK_None;
4683     /// True if float point min/max reduction has no NaNs.
4684     bool NoNaN = false;
4685 
4686     /// Checks if the reduction operation can be vectorized.
4687     bool isVectorizable() const {
4688       return LHS && RHS &&
4689              // We currently only support adds && min/max reductions.
4690              ((Kind == RK_Arithmetic &&
4691                (Opcode == Instruction::Add || Opcode == Instruction::FAdd)) ||
4692               ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
4693                (Kind == RK_Min || Kind == RK_Max)) ||
4694               (Opcode == Instruction::ICmp &&
4695                (Kind == RK_UMin || Kind == RK_UMax)));
4696     }
4697 
4698   public:
4699     explicit OperationData() = default;
4700 
4701     /// Construction for reduced values. They are identified by opcode only and
4702     /// don't have associated LHS/RHS values.
4703     explicit OperationData(Value *V) : Kind(RK_None) {
4704       if (auto *I = dyn_cast<Instruction>(V))
4705         Opcode = I->getOpcode();
4706     }
4707 
4708     /// Constructor for reduction operations with opcode and its left and
4709     /// right operands.
4710     OperationData(unsigned Opcode, Value *LHS, Value *RHS, ReductionKind Kind,
4711                   bool NoNaN = false)
4712         : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind), NoNaN(NoNaN) {
4713       assert(Kind != RK_None && "One of the reduction operations is expected.");
4714     }
4715     explicit operator bool() const { return Opcode; }
4716 
4717     /// Get the index of the first operand.
4718     unsigned getFirstOperandIndex() const {
4719       assert(!!*this && "The opcode is not set.");
4720       switch (Kind) {
4721       case RK_Min:
4722       case RK_UMin:
4723       case RK_Max:
4724       case RK_UMax:
4725         return 1;
4726       case RK_Arithmetic:
4727       case RK_None:
4728         break;
4729       }
4730       return 0;
4731     }
4732 
4733     /// Total number of operands in the reduction operation.
4734     unsigned getNumberOfOperands() const {
4735       assert(Kind != RK_None && !!*this && LHS && RHS &&
4736              "Expected reduction operation.");
4737       switch (Kind) {
4738       case RK_Arithmetic:
4739         return 2;
4740       case RK_Min:
4741       case RK_UMin:
4742       case RK_Max:
4743       case RK_UMax:
4744         return 3;
4745       case RK_None:
4746         break;
4747       }
4748       llvm_unreachable("Reduction kind is not set");
4749     }
4750 
4751     /// Expected number of uses for reduction operations/reduced values.
4752     unsigned getRequiredNumberOfUses() const {
4753       assert(Kind != RK_None && !!*this && LHS && RHS &&
4754              "Expected reduction operation.");
4755       switch (Kind) {
4756       case RK_Arithmetic:
4757         return 1;
4758       case RK_Min:
4759       case RK_UMin:
4760       case RK_Max:
4761       case RK_UMax:
4762         return 2;
4763       case RK_None:
4764         break;
4765       }
4766       llvm_unreachable("Reduction kind is not set");
4767     }
4768 
4769     /// Checks if instruction is associative and can be vectorized.
4770     bool isAssociative(Instruction *I) const {
4771       assert(Kind != RK_None && *this && LHS && RHS &&
4772              "Expected reduction operation.");
4773       switch (Kind) {
4774       case RK_Arithmetic:
4775         return I->isAssociative();
4776       case RK_Min:
4777       case RK_Max:
4778         return Opcode == Instruction::ICmp ||
4779                cast<Instruction>(I->getOperand(0))->hasUnsafeAlgebra();
4780       case RK_UMin:
4781       case RK_UMax:
4782         assert(Opcode == Instruction::ICmp &&
4783                "Only integer compare operation is expected.");
4784         return true;
4785       case RK_None:
4786         break;
4787       }
4788       llvm_unreachable("Reduction kind is not set");
4789     }
4790 
4791     /// Checks if the reduction operation can be vectorized.
4792     bool isVectorizable(Instruction *I) const {
4793       return isVectorizable() && isAssociative(I);
4794     }
4795 
4796     /// Checks if two operation data are both a reduction op or both a reduced
4797     /// value.
4798     bool operator==(const OperationData &OD) {
4799       assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&
4800              "One of the comparing operations is incorrect.");
4801       return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
4802     }
4803     bool operator!=(const OperationData &OD) { return !(*this == OD); }
4804     void clear() {
4805       Opcode = 0;
4806       LHS = nullptr;
4807       RHS = nullptr;
4808       Kind = RK_None;
4809       NoNaN = false;
4810     }
4811 
4812     /// Get the opcode of the reduction operation.
4813     unsigned getOpcode() const {
4814       assert(isVectorizable() && "Expected vectorizable operation.");
4815       return Opcode;
4816     }
4817 
4818     /// Get kind of reduction data.
4819     ReductionKind getKind() const { return Kind; }
4820     Value *getLHS() const { return LHS; }
4821     Value *getRHS() const { return RHS; }
4822     Type *getConditionType() const {
4823       switch (Kind) {
4824       case RK_Arithmetic:
4825         return nullptr;
4826       case RK_Min:
4827       case RK_Max:
4828       case RK_UMin:
4829       case RK_UMax:
4830         return CmpInst::makeCmpResultType(LHS->getType());
4831       case RK_None:
4832         break;
4833       }
4834       llvm_unreachable("Reduction kind is not set");
4835     }
4836 
4837     /// Creates reduction operation with the current opcode.
4838     Value *createOp(IRBuilder<> &Builder, const Twine &Name = "") const {
4839       assert(isVectorizable() &&
4840              "Expected add|fadd or min/max reduction operation.");
4841       Value *Cmp;
4842       switch (Kind) {
4843       case RK_Arithmetic:
4844         return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
4845                                    Name);
4846       case RK_Min:
4847         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSLT(LHS, RHS)
4848                                           : Builder.CreateFCmpOLT(LHS, RHS);
4849         break;
4850       case RK_Max:
4851         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSGT(LHS, RHS)
4852                                           : Builder.CreateFCmpOGT(LHS, RHS);
4853         break;
4854       case RK_UMin:
4855         assert(Opcode == Instruction::ICmp && "Expected integer types.");
4856         Cmp = Builder.CreateICmpULT(LHS, RHS);
4857         break;
4858       case RK_UMax:
4859         assert(Opcode == Instruction::ICmp && "Expected integer types.");
4860         Cmp = Builder.CreateICmpUGT(LHS, RHS);
4861         break;
4862       case RK_None:
4863         llvm_unreachable("Unknown reduction operation.");
4864       }
4865       return Builder.CreateSelect(Cmp, LHS, RHS, Name);
4866     }
4867     TargetTransformInfo::ReductionFlags getFlags() const {
4868       TargetTransformInfo::ReductionFlags Flags;
4869       Flags.NoNaN = NoNaN;
4870       switch (Kind) {
4871       case RK_Arithmetic:
4872         break;
4873       case RK_Min:
4874         Flags.IsSigned = Opcode == Instruction::ICmp;
4875         Flags.IsMaxOp = false;
4876         break;
4877       case RK_Max:
4878         Flags.IsSigned = Opcode == Instruction::ICmp;
4879         Flags.IsMaxOp = true;
4880         break;
4881       case RK_UMin:
4882         Flags.IsSigned = false;
4883         Flags.IsMaxOp = false;
4884         break;
4885       case RK_UMax:
4886         Flags.IsSigned = false;
4887         Flags.IsMaxOp = true;
4888         break;
4889       case RK_None:
4890         llvm_unreachable("Reduction kind is not set");
4891       }
4892       return Flags;
4893     }
4894   };
4895 
4896   Instruction *ReductionRoot = nullptr;
4897 
4898   /// The operation data of the reduction operation.
4899   OperationData ReductionData;
4900 
4901   /// The operation data of the values we perform a reduction on.
4902   OperationData ReducedValueData;
4903 
4904   /// Should we model this reduction as a pairwise reduction tree or a tree that
4905   /// splits the vector in halves and adds those halves.
4906   bool IsPairwiseReduction = false;
4907 
4908   /// Checks if the ParentStackElem.first should be marked as a reduction
4909   /// operation with an extra argument or as extra argument itself.
4910   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
4911                     Value *ExtraArg) {
4912     if (ExtraArgs.count(ParentStackElem.first)) {
4913       ExtraArgs[ParentStackElem.first] = nullptr;
4914       // We ran into something like:
4915       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
4916       // The whole ParentStackElem.first should be considered as an extra value
4917       // in this case.
4918       // Do not perform analysis of remaining operands of ParentStackElem.first
4919       // instruction, this whole instruction is an extra argument.
4920       ParentStackElem.second = ParentStackElem.first->getNumOperands();
4921     } else {
4922       // We ran into something like:
4923       // ParentStackElem.first += ... + ExtraArg + ...
4924       ExtraArgs[ParentStackElem.first] = ExtraArg;
4925     }
4926   }
4927 
4928   static OperationData getOperationData(Value *V) {
4929     if (!V)
4930       return OperationData();
4931 
4932     Value *LHS;
4933     Value *RHS;
4934     if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(V)) {
4935       return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS,
4936                            RK_Arithmetic);
4937     }
4938     if (auto *Select = dyn_cast<SelectInst>(V)) {
4939       // Look for a min/max pattern.
4940       if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
4941         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
4942       } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
4943         return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
4944       } else if (m_OrdFMin(m_Value(LHS), m_Value(RHS)).match(Select) ||
4945                  m_UnordFMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
4946         return OperationData(
4947             Instruction::FCmp, LHS, RHS, RK_Min,
4948             cast<Instruction>(Select->getCondition())->hasNoNaNs());
4949       } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
4950         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
4951       } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
4952         return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
4953       } else if (m_OrdFMax(m_Value(LHS), m_Value(RHS)).match(Select) ||
4954                  m_UnordFMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
4955         return OperationData(
4956             Instruction::FCmp, LHS, RHS, RK_Max,
4957             cast<Instruction>(Select->getCondition())->hasNoNaNs());
4958       }
4959     }
4960     return OperationData(V);
4961   }
4962 
4963 public:
4964   HorizontalReduction() = default;
4965 
4966   /// \brief Try to find a reduction tree.
4967   bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
4968     assert((!Phi || is_contained(Phi->operands(), B)) &&
4969            "Thi phi needs to use the binary operator");
4970 
4971     ReductionData = getOperationData(B);
4972 
4973     // We could have a initial reductions that is not an add.
4974     //  r *= v1 + v2 + v3 + v4
4975     // In such a case start looking for a tree rooted in the first '+'.
4976     if (Phi) {
4977       if (ReductionData.getLHS() == Phi) {
4978         Phi = nullptr;
4979         B = dyn_cast<Instruction>(ReductionData.getRHS());
4980         ReductionData = getOperationData(B);
4981       } else if (ReductionData.getRHS() == Phi) {
4982         Phi = nullptr;
4983         B = dyn_cast<Instruction>(ReductionData.getLHS());
4984         ReductionData = getOperationData(B);
4985       }
4986     }
4987 
4988     if (!ReductionData.isVectorizable(B))
4989       return false;
4990 
4991     Type *Ty = B->getType();
4992     if (!isValidElementType(Ty))
4993       return false;
4994 
4995     ReducedValueData.clear();
4996     ReductionRoot = B;
4997 
4998     // Post order traverse the reduction tree starting at B. We only handle true
4999     // trees containing only binary operators.
5000     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
5001     Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
5002     const unsigned NUses = ReductionData.getRequiredNumberOfUses();
5003     while (!Stack.empty()) {
5004       Instruction *TreeN = Stack.back().first;
5005       unsigned EdgeToVist = Stack.back().second++;
5006       OperationData OpData = getOperationData(TreeN);
5007       bool IsReducedValue = OpData != ReductionData;
5008 
5009       // Postorder vist.
5010       if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
5011         if (IsReducedValue)
5012           ReducedVals.push_back(TreeN);
5013         else {
5014           auto I = ExtraArgs.find(TreeN);
5015           if (I != ExtraArgs.end() && !I->second) {
5016             // Check if TreeN is an extra argument of its parent operation.
5017             if (Stack.size() <= 1) {
5018               // TreeN can't be an extra argument as it is a root reduction
5019               // operation.
5020               return false;
5021             }
5022             // Yes, TreeN is an extra argument, do not add it to a list of
5023             // reduction operations.
5024             // Stack[Stack.size() - 2] always points to the parent operation.
5025             markExtraArg(Stack[Stack.size() - 2], TreeN);
5026             ExtraArgs.erase(TreeN);
5027           } else
5028             ReductionOps.push_back(TreeN);
5029         }
5030         // Retract.
5031         Stack.pop_back();
5032         continue;
5033       }
5034 
5035       // Visit left or right.
5036       Value *NextV = TreeN->getOperand(EdgeToVist);
5037       if (NextV != Phi) {
5038         auto *I = dyn_cast<Instruction>(NextV);
5039         OpData = getOperationData(I);
5040         // Continue analysis if the next operand is a reduction operation or
5041         // (possibly) a reduced value. If the reduced value opcode is not set,
5042         // the first met operation != reduction operation is considered as the
5043         // reduced value class.
5044         if (I && (!ReducedValueData || OpData == ReducedValueData ||
5045                   OpData == ReductionData)) {
5046           // Only handle trees in the current basic block.
5047           if (I->getParent() != B->getParent()) {
5048             // I is an extra argument for TreeN (its parent operation).
5049             markExtraArg(Stack.back(), I);
5050             continue;
5051           }
5052 
5053           // Each tree node needs to have minimal number of users except for the
5054           // ultimate reduction.
5055           if (!I->hasNUses(NUses) && I != B) {
5056             // I is an extra argument for TreeN (its parent operation).
5057             markExtraArg(Stack.back(), I);
5058             continue;
5059           }
5060 
5061           if (OpData == ReductionData) {
5062             // We need to be able to reassociate the reduction operations.
5063             if (!OpData.isAssociative(I)) {
5064               // I is an extra argument for TreeN (its parent operation).
5065               markExtraArg(Stack.back(), I);
5066               continue;
5067             }
5068           } else if (ReducedValueData &&
5069                      ReducedValueData != OpData) {
5070             // Make sure that the opcodes of the operations that we are going to
5071             // reduce match.
5072             // I is an extra argument for TreeN (its parent operation).
5073             markExtraArg(Stack.back(), I);
5074             continue;
5075           } else if (!ReducedValueData)
5076             ReducedValueData = OpData;
5077 
5078           Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
5079           continue;
5080         }
5081       }
5082       // NextV is an extra argument for TreeN (its parent operation).
5083       markExtraArg(Stack.back(), NextV);
5084     }
5085     return true;
5086   }
5087 
5088   /// \brief Attempt to vectorize the tree found by
5089   /// matchAssociativeReduction.
5090   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
5091     if (ReducedVals.empty())
5092       return false;
5093 
5094     // If there is a sufficient number of reduction values, reduce
5095     // to a nearby power-of-2. Can safely generate oversized
5096     // vectors and rely on the backend to split them to legal sizes.
5097     unsigned NumReducedVals = ReducedVals.size();
5098     if (NumReducedVals < 4)
5099       return false;
5100 
5101     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
5102 
5103     Value *VectorizedTree = nullptr;
5104     IRBuilder<> Builder(ReductionRoot);
5105     FastMathFlags Unsafe;
5106     Unsafe.setUnsafeAlgebra();
5107     Builder.setFastMathFlags(Unsafe);
5108     unsigned i = 0;
5109 
5110     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
5111     // The same extra argument may be used several time, so log each attempt
5112     // to use it.
5113     for (auto &Pair : ExtraArgs)
5114       ExternallyUsedValues[Pair.second].push_back(Pair.first);
5115     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
5116       auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
5117       V.buildTree(VL, ExternallyUsedValues, ReductionOps);
5118       if (V.shouldReorder()) {
5119         SmallVector<Value *, 8> Reversed(VL.rbegin(), VL.rend());
5120         V.buildTree(Reversed, ExternallyUsedValues, ReductionOps);
5121       }
5122       if (V.isTreeTinyAndNotFullyVectorizable())
5123         break;
5124 
5125       V.computeMinimumValueSizes();
5126 
5127       // Estimate cost.
5128       int Cost =
5129           V.getTreeCost() + getReductionCost(TTI, ReducedVals[i], ReduxWidth);
5130       if (Cost >= -SLPCostThreshold)
5131         break;
5132 
5133       DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:" << Cost
5134                    << ". (HorRdx)\n");
5135       auto *I0 = cast<Instruction>(VL[0]);
5136       V.getORE()->emit(
5137           OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction", I0)
5138           << "Vectorized horizontal reduction with cost "
5139           << ore::NV("Cost", Cost) << " and with tree size "
5140           << ore::NV("TreeSize", V.getTreeSize()));
5141 
5142       // Vectorize a tree.
5143       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
5144       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
5145 
5146       // Emit a reduction.
5147       Value *ReducedSubTree =
5148           emitReduction(VectorizedRoot, Builder, ReduxWidth, ReductionOps, TTI);
5149       if (VectorizedTree) {
5150         Builder.SetCurrentDebugLocation(Loc);
5151         OperationData VectReductionData(ReductionData.getOpcode(),
5152                                         VectorizedTree, ReducedSubTree,
5153                                         ReductionData.getKind());
5154         VectorizedTree = VectReductionData.createOp(Builder, "op.rdx");
5155         propagateIRFlags(VectorizedTree, ReductionOps);
5156       } else
5157         VectorizedTree = ReducedSubTree;
5158       i += ReduxWidth;
5159       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
5160     }
5161 
5162     if (VectorizedTree) {
5163       // Finish the reduction.
5164       for (; i < NumReducedVals; ++i) {
5165         auto *I = cast<Instruction>(ReducedVals[i]);
5166         Builder.SetCurrentDebugLocation(I->getDebugLoc());
5167         OperationData VectReductionData(ReductionData.getOpcode(),
5168                                         VectorizedTree, I,
5169                                         ReductionData.getKind());
5170         VectorizedTree = VectReductionData.createOp(Builder);
5171         propagateIRFlags(VectorizedTree, ReductionOps);
5172       }
5173       for (auto &Pair : ExternallyUsedValues) {
5174         assert(!Pair.second.empty() &&
5175                "At least one DebugLoc must be inserted");
5176         // Add each externally used value to the final reduction.
5177         for (auto *I : Pair.second) {
5178           Builder.SetCurrentDebugLocation(I->getDebugLoc());
5179           OperationData VectReductionData(ReductionData.getOpcode(),
5180                                           VectorizedTree, Pair.first,
5181                                           ReductionData.getKind());
5182           VectorizedTree = VectReductionData.createOp(Builder, "op.extra");
5183           propagateIRFlags(VectorizedTree, I);
5184         }
5185       }
5186       // Update users.
5187       ReductionRoot->replaceAllUsesWith(VectorizedTree);
5188     }
5189     return VectorizedTree != nullptr;
5190   }
5191 
5192   unsigned numReductionValues() const {
5193     return ReducedVals.size();
5194   }
5195 
5196 private:
5197   /// \brief Calculate the cost of a reduction.
5198   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
5199                        unsigned ReduxWidth) {
5200     Type *ScalarTy = FirstReducedVal->getType();
5201     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
5202 
5203     int PairwiseRdxCost;
5204     int SplittingRdxCost;
5205     bool IsUnsigned = true;
5206     switch (ReductionData.getKind()) {
5207     case RK_Arithmetic:
5208       PairwiseRdxCost =
5209           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
5210                                           /*IsPairwiseForm=*/true);
5211       SplittingRdxCost =
5212           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
5213                                           /*IsPairwiseForm=*/false);
5214       break;
5215     case RK_Min:
5216     case RK_Max:
5217       IsUnsigned = false;
5218     case RK_UMin:
5219     case RK_UMax: {
5220       Type *VecCondTy = CmpInst::makeCmpResultType(VecTy);
5221       PairwiseRdxCost =
5222           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
5223                                       /*IsPairwiseForm=*/true, IsUnsigned);
5224       SplittingRdxCost =
5225           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
5226                                       /*IsPairwiseForm=*/false, IsUnsigned);
5227       break;
5228     }
5229     case RK_None:
5230       llvm_unreachable("Expected arithmetic or min/max reduction operation");
5231     }
5232 
5233     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
5234     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
5235 
5236     int ScalarReduxCost;
5237     switch (ReductionData.getKind()) {
5238     case RK_Arithmetic:
5239       ScalarReduxCost =
5240           TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
5241       break;
5242     case RK_Min:
5243     case RK_Max:
5244     case RK_UMin:
5245     case RK_UMax:
5246       ScalarReduxCost =
5247           TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
5248           TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
5249                                   CmpInst::makeCmpResultType(ScalarTy));
5250       break;
5251     case RK_None:
5252       llvm_unreachable("Expected arithmetic or min/max reduction operation");
5253     }
5254     ScalarReduxCost *= (ReduxWidth - 1);
5255 
5256     DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
5257                  << " for reduction that starts with " << *FirstReducedVal
5258                  << " (It is a "
5259                  << (IsPairwiseReduction ? "pairwise" : "splitting")
5260                  << " reduction)\n");
5261 
5262     return VecReduxCost - ScalarReduxCost;
5263   }
5264 
5265   /// \brief Emit a horizontal reduction of the vectorized value.
5266   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
5267                        unsigned ReduxWidth, ArrayRef<Value *> RedOps,
5268                        const TargetTransformInfo *TTI) {
5269     assert(VectorizedValue && "Need to have a vectorized tree node");
5270     assert(isPowerOf2_32(ReduxWidth) &&
5271            "We only handle power-of-two reductions for now");
5272 
5273     if (!IsPairwiseReduction)
5274       return createSimpleTargetReduction(
5275           Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
5276           ReductionData.getFlags(), RedOps);
5277 
5278     Value *TmpVec = VectorizedValue;
5279     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
5280       Value *LeftMask =
5281           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
5282       Value *RightMask =
5283           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
5284 
5285       Value *LeftShuf = Builder.CreateShuffleVector(
5286           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
5287       Value *RightShuf = Builder.CreateShuffleVector(
5288           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
5289           "rdx.shuf.r");
5290       OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
5291                                       RightShuf, ReductionData.getKind());
5292       TmpVec = VectReductionData.createOp(Builder, "op.rdx");
5293       propagateIRFlags(TmpVec, RedOps);
5294     }
5295 
5296     // The result is in the first element of the vector.
5297     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
5298   }
5299 };
5300 
5301 } // end anonymous namespace
5302 
5303 /// \brief Recognize construction of vectors like
5304 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
5305 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
5306 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
5307 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
5308 ///  starting from the last insertelement instruction.
5309 ///
5310 /// Returns true if it matches
5311 ///
5312 static bool findBuildVector(InsertElementInst *LastInsertElem,
5313                             SmallVectorImpl<Value *> &BuildVector,
5314                             SmallVectorImpl<Value *> &BuildVectorOpds) {
5315   Value *V = nullptr;
5316   do {
5317     BuildVector.push_back(LastInsertElem);
5318     BuildVectorOpds.push_back(LastInsertElem->getOperand(1));
5319     V = LastInsertElem->getOperand(0);
5320     if (isa<UndefValue>(V))
5321       break;
5322     LastInsertElem = dyn_cast<InsertElementInst>(V);
5323     if (!LastInsertElem || !LastInsertElem->hasOneUse())
5324       return false;
5325   } while (true);
5326   std::reverse(BuildVector.begin(), BuildVector.end());
5327   std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
5328   return true;
5329 }
5330 
5331 /// \brief Like findBuildVector, but looks for construction of aggregate.
5332 ///
5333 /// \return true if it matches.
5334 static bool findBuildAggregate(InsertValueInst *IV,
5335                                SmallVectorImpl<Value *> &BuildVector,
5336                                SmallVectorImpl<Value *> &BuildVectorOpds) {
5337   Value *V;
5338   do {
5339     BuildVector.push_back(IV);
5340     BuildVectorOpds.push_back(IV->getInsertedValueOperand());
5341     V = IV->getAggregateOperand();
5342     if (isa<UndefValue>(V))
5343       break;
5344     IV = dyn_cast<InsertValueInst>(V);
5345     if (!IV || !IV->hasOneUse())
5346       return false;
5347   } while (true);
5348   std::reverse(BuildVector.begin(), BuildVector.end());
5349   std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
5350   return true;
5351 }
5352 
5353 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
5354   return V->getType() < V2->getType();
5355 }
5356 
5357 /// \brief Try and get a reduction value from a phi node.
5358 ///
5359 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
5360 /// if they come from either \p ParentBB or a containing loop latch.
5361 ///
5362 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
5363 /// if not possible.
5364 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
5365                                 BasicBlock *ParentBB, LoopInfo *LI) {
5366   // There are situations where the reduction value is not dominated by the
5367   // reduction phi. Vectorizing such cases has been reported to cause
5368   // miscompiles. See PR25787.
5369   auto DominatedReduxValue = [&](Value *R) {
5370     return (
5371         dyn_cast<Instruction>(R) &&
5372         DT->dominates(P->getParent(), dyn_cast<Instruction>(R)->getParent()));
5373   };
5374 
5375   Value *Rdx = nullptr;
5376 
5377   // Return the incoming value if it comes from the same BB as the phi node.
5378   if (P->getIncomingBlock(0) == ParentBB) {
5379     Rdx = P->getIncomingValue(0);
5380   } else if (P->getIncomingBlock(1) == ParentBB) {
5381     Rdx = P->getIncomingValue(1);
5382   }
5383 
5384   if (Rdx && DominatedReduxValue(Rdx))
5385     return Rdx;
5386 
5387   // Otherwise, check whether we have a loop latch to look at.
5388   Loop *BBL = LI->getLoopFor(ParentBB);
5389   if (!BBL)
5390     return nullptr;
5391   BasicBlock *BBLatch = BBL->getLoopLatch();
5392   if (!BBLatch)
5393     return nullptr;
5394 
5395   // There is a loop latch, return the incoming value if it comes from
5396   // that. This reduction pattern occasionally turns up.
5397   if (P->getIncomingBlock(0) == BBLatch) {
5398     Rdx = P->getIncomingValue(0);
5399   } else if (P->getIncomingBlock(1) == BBLatch) {
5400     Rdx = P->getIncomingValue(1);
5401   }
5402 
5403   if (Rdx && DominatedReduxValue(Rdx))
5404     return Rdx;
5405 
5406   return nullptr;
5407 }
5408 
5409 /// Attempt to reduce a horizontal reduction.
5410 /// If it is legal to match a horizontal reduction feeding the phi node \a P
5411 /// with reduction operators \a Root (or one of its operands) in a basic block
5412 /// \a BB, then check if it can be done. If horizontal reduction is not found
5413 /// and root instruction is a binary operation, vectorization of the operands is
5414 /// attempted.
5415 /// \returns true if a horizontal reduction was matched and reduced or operands
5416 /// of one of the binary instruction were vectorized.
5417 /// \returns false if a horizontal reduction was not matched (or not possible)
5418 /// or no vectorization of any binary operation feeding \a Root instruction was
5419 /// performed.
5420 static bool tryToVectorizeHorReductionOrInstOperands(
5421     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
5422     TargetTransformInfo *TTI,
5423     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
5424   if (!ShouldVectorizeHor)
5425     return false;
5426 
5427   if (!Root)
5428     return false;
5429 
5430   if (Root->getParent() != BB || isa<PHINode>(Root))
5431     return false;
5432   // Start analysis starting from Root instruction. If horizontal reduction is
5433   // found, try to vectorize it. If it is not a horizontal reduction or
5434   // vectorization is not possible or not effective, and currently analyzed
5435   // instruction is a binary operation, try to vectorize the operands, using
5436   // pre-order DFS traversal order. If the operands were not vectorized, repeat
5437   // the same procedure considering each operand as a possible root of the
5438   // horizontal reduction.
5439   // Interrupt the process if the Root instruction itself was vectorized or all
5440   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
5441   SmallVector<std::pair<WeakTrackingVH, unsigned>, 8> Stack(1, {Root, 0});
5442   SmallSet<Value *, 8> VisitedInstrs;
5443   bool Res = false;
5444   while (!Stack.empty()) {
5445     Value *V;
5446     unsigned Level;
5447     std::tie(V, Level) = Stack.pop_back_val();
5448     if (!V)
5449       continue;
5450     auto *Inst = dyn_cast<Instruction>(V);
5451     if (!Inst)
5452       continue;
5453     auto *BI = dyn_cast<BinaryOperator>(Inst);
5454     auto *SI = dyn_cast<SelectInst>(Inst);
5455     if (BI || SI) {
5456       HorizontalReduction HorRdx;
5457       if (HorRdx.matchAssociativeReduction(P, Inst)) {
5458         if (HorRdx.tryToReduce(R, TTI)) {
5459           Res = true;
5460           // Set P to nullptr to avoid re-analysis of phi node in
5461           // matchAssociativeReduction function unless this is the root node.
5462           P = nullptr;
5463           continue;
5464         }
5465       }
5466       if (P && BI) {
5467         Inst = dyn_cast<Instruction>(BI->getOperand(0));
5468         if (Inst == P)
5469           Inst = dyn_cast<Instruction>(BI->getOperand(1));
5470         if (!Inst) {
5471           // Set P to nullptr to avoid re-analysis of phi node in
5472           // matchAssociativeReduction function unless this is the root node.
5473           P = nullptr;
5474           continue;
5475         }
5476       }
5477     }
5478     // Set P to nullptr to avoid re-analysis of phi node in
5479     // matchAssociativeReduction function unless this is the root node.
5480     P = nullptr;
5481     if (Vectorize(Inst, R)) {
5482       Res = true;
5483       continue;
5484     }
5485 
5486     // Try to vectorize operands.
5487     // Continue analysis for the instruction from the same basic block only to
5488     // save compile time.
5489     if (++Level < RecursionMaxDepth)
5490       for (auto *Op : Inst->operand_values())
5491         if (VisitedInstrs.insert(Op).second)
5492           if (auto *I = dyn_cast<Instruction>(Op))
5493             if (!isa<PHINode>(Inst) && I->getParent() == BB)
5494               Stack.emplace_back(Op, Level);
5495   }
5496   return Res;
5497 }
5498 
5499 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
5500                                                  BasicBlock *BB, BoUpSLP &R,
5501                                                  TargetTransformInfo *TTI) {
5502   if (!V)
5503     return false;
5504   auto *I = dyn_cast<Instruction>(V);
5505   if (!I)
5506     return false;
5507 
5508   if (!isa<BinaryOperator>(I))
5509     P = nullptr;
5510   // Try to match and vectorize a horizontal reduction.
5511   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
5512     return tryToVectorize(I, R);
5513   };
5514   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
5515                                                   ExtraVectorization);
5516 }
5517 
5518 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
5519                                                  BasicBlock *BB, BoUpSLP &R) {
5520   const DataLayout &DL = BB->getModule()->getDataLayout();
5521   if (!R.canMapToVector(IVI->getType(), DL))
5522     return false;
5523 
5524   SmallVector<Value *, 16> BuildVector;
5525   SmallVector<Value *, 16> BuildVectorOpds;
5526   if (!findBuildAggregate(IVI, BuildVector, BuildVectorOpds))
5527     return false;
5528 
5529   DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
5530   return tryToVectorizeList(BuildVectorOpds, R, BuildVector, false);
5531 }
5532 
5533 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
5534                                                    BasicBlock *BB, BoUpSLP &R) {
5535   SmallVector<Value *, 16> BuildVector;
5536   SmallVector<Value *, 16> BuildVectorOpds;
5537   if (!findBuildVector(IEI, BuildVector, BuildVectorOpds))
5538     return false;
5539 
5540   // Vectorize starting with the build vector operands ignoring the BuildVector
5541   // instructions for the purpose of scheduling and user extraction.
5542   return tryToVectorizeList(BuildVectorOpds, R, BuildVector);
5543 }
5544 
5545 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
5546                                          BoUpSLP &R) {
5547   if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
5548     return true;
5549 
5550   bool OpsChanged = false;
5551   for (int Idx = 0; Idx < 2; ++Idx) {
5552     OpsChanged |=
5553         vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
5554   }
5555   return OpsChanged;
5556 }
5557 
5558 bool SLPVectorizerPass::vectorizeSimpleInstructions(
5559     SmallVectorImpl<WeakVH> &Instructions, BasicBlock *BB, BoUpSLP &R) {
5560   bool OpsChanged = false;
5561   for (auto &VH : reverse(Instructions)) {
5562     auto *I = dyn_cast_or_null<Instruction>(VH);
5563     if (!I)
5564       continue;
5565     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
5566       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
5567     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
5568       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
5569     else if (auto *CI = dyn_cast<CmpInst>(I))
5570       OpsChanged |= vectorizeCmpInst(CI, BB, R);
5571   }
5572   Instructions.clear();
5573   return OpsChanged;
5574 }
5575 
5576 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
5577   bool Changed = false;
5578   SmallVector<Value *, 4> Incoming;
5579   SmallSet<Value *, 16> VisitedInstrs;
5580 
5581   bool HaveVectorizedPhiNodes = true;
5582   while (HaveVectorizedPhiNodes) {
5583     HaveVectorizedPhiNodes = false;
5584 
5585     // Collect the incoming values from the PHIs.
5586     Incoming.clear();
5587     for (Instruction &I : *BB) {
5588       PHINode *P = dyn_cast<PHINode>(&I);
5589       if (!P)
5590         break;
5591 
5592       if (!VisitedInstrs.count(P))
5593         Incoming.push_back(P);
5594     }
5595 
5596     // Sort by type.
5597     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
5598 
5599     // Try to vectorize elements base on their type.
5600     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
5601                                            E = Incoming.end();
5602          IncIt != E;) {
5603 
5604       // Look for the next elements with the same type.
5605       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
5606       while (SameTypeIt != E &&
5607              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
5608         VisitedInstrs.insert(*SameTypeIt);
5609         ++SameTypeIt;
5610       }
5611 
5612       // Try to vectorize them.
5613       unsigned NumElts = (SameTypeIt - IncIt);
5614       DEBUG(errs() << "SLP: Trying to vectorize starting at PHIs (" << NumElts << ")\n");
5615       // The order in which the phi nodes appear in the program does not matter.
5616       // So allow tryToVectorizeList to reorder them if it is beneficial. This
5617       // is done when there are exactly two elements since tryToVectorizeList
5618       // asserts that there are only two values when AllowReorder is true.
5619       bool AllowReorder = NumElts == 2;
5620       if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R,
5621                                             None, AllowReorder)) {
5622         // Success start over because instructions might have been changed.
5623         HaveVectorizedPhiNodes = true;
5624         Changed = true;
5625         break;
5626       }
5627 
5628       // Start over at the next instruction of a different type (or the end).
5629       IncIt = SameTypeIt;
5630     }
5631   }
5632 
5633   VisitedInstrs.clear();
5634 
5635   SmallVector<WeakVH, 8> PostProcessInstructions;
5636   SmallDenseSet<Instruction *, 4> KeyNodes;
5637   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
5638     // We may go through BB multiple times so skip the one we have checked.
5639     if (!VisitedInstrs.insert(&*it).second) {
5640       if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
5641           vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
5642         // We would like to start over since some instructions are deleted
5643         // and the iterator may become invalid value.
5644         Changed = true;
5645         it = BB->begin();
5646         e = BB->end();
5647       }
5648       continue;
5649     }
5650 
5651     if (isa<DbgInfoIntrinsic>(it))
5652       continue;
5653 
5654     // Try to vectorize reductions that use PHINodes.
5655     if (PHINode *P = dyn_cast<PHINode>(it)) {
5656       // Check that the PHI is a reduction PHI.
5657       if (P->getNumIncomingValues() != 2)
5658         return Changed;
5659 
5660       // Try to match and vectorize a horizontal reduction.
5661       if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
5662                                    TTI)) {
5663         Changed = true;
5664         it = BB->begin();
5665         e = BB->end();
5666         continue;
5667       }
5668       continue;
5669     }
5670 
5671     // Ran into an instruction without users, like terminator, or function call
5672     // with ignored return value, store. Ignore unused instructions (basing on
5673     // instruction type, except for CallInst and InvokeInst).
5674     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
5675                             isa<InvokeInst>(it))) {
5676       KeyNodes.insert(&*it);
5677       bool OpsChanged = false;
5678       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
5679         for (auto *V : it->operand_values()) {
5680           // Try to match and vectorize a horizontal reduction.
5681           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
5682         }
5683       }
5684       // Start vectorization of post-process list of instructions from the
5685       // top-tree instructions to try to vectorize as many instructions as
5686       // possible.
5687       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
5688       if (OpsChanged) {
5689         // We would like to start over since some instructions are deleted
5690         // and the iterator may become invalid value.
5691         Changed = true;
5692         it = BB->begin();
5693         e = BB->end();
5694         continue;
5695       }
5696     }
5697 
5698     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
5699         isa<InsertValueInst>(it))
5700       PostProcessInstructions.push_back(&*it);
5701 
5702   }
5703 
5704   return Changed;
5705 }
5706 
5707 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
5708   auto Changed = false;
5709   for (auto &Entry : GEPs) {
5710     // If the getelementptr list has fewer than two elements, there's nothing
5711     // to do.
5712     if (Entry.second.size() < 2)
5713       continue;
5714 
5715     DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
5716                  << Entry.second.size() << ".\n");
5717 
5718     // We process the getelementptr list in chunks of 16 (like we do for
5719     // stores) to minimize compile-time.
5720     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
5721       auto Len = std::min<unsigned>(BE - BI, 16);
5722       auto GEPList = makeArrayRef(&Entry.second[BI], Len);
5723 
5724       // Initialize a set a candidate getelementptrs. Note that we use a
5725       // SetVector here to preserve program order. If the index computations
5726       // are vectorizable and begin with loads, we want to minimize the chance
5727       // of having to reorder them later.
5728       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
5729 
5730       // Some of the candidates may have already been vectorized after we
5731       // initially collected them. If so, the WeakTrackingVHs will have
5732       // nullified the
5733       // values, so remove them from the set of candidates.
5734       Candidates.remove(nullptr);
5735 
5736       // Remove from the set of candidates all pairs of getelementptrs with
5737       // constant differences. Such getelementptrs are likely not good
5738       // candidates for vectorization in a bottom-up phase since one can be
5739       // computed from the other. We also ensure all candidate getelementptr
5740       // indices are unique.
5741       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
5742         auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
5743         if (!Candidates.count(GEPI))
5744           continue;
5745         auto *SCEVI = SE->getSCEV(GEPList[I]);
5746         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
5747           auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
5748           auto *SCEVJ = SE->getSCEV(GEPList[J]);
5749           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
5750             Candidates.remove(GEPList[I]);
5751             Candidates.remove(GEPList[J]);
5752           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
5753             Candidates.remove(GEPList[J]);
5754           }
5755         }
5756       }
5757 
5758       // We break out of the above computation as soon as we know there are
5759       // fewer than two candidates remaining.
5760       if (Candidates.size() < 2)
5761         continue;
5762 
5763       // Add the single, non-constant index of each candidate to the bundle. We
5764       // ensured the indices met these constraints when we originally collected
5765       // the getelementptrs.
5766       SmallVector<Value *, 16> Bundle(Candidates.size());
5767       auto BundleIndex = 0u;
5768       for (auto *V : Candidates) {
5769         auto *GEP = cast<GetElementPtrInst>(V);
5770         auto *GEPIdx = GEP->idx_begin()->get();
5771         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
5772         Bundle[BundleIndex++] = GEPIdx;
5773       }
5774 
5775       // Try and vectorize the indices. We are currently only interested in
5776       // gather-like cases of the form:
5777       //
5778       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
5779       //
5780       // where the loads of "a", the loads of "b", and the subtractions can be
5781       // performed in parallel. It's likely that detecting this pattern in a
5782       // bottom-up phase will be simpler and less costly than building a
5783       // full-blown top-down phase beginning at the consecutive loads.
5784       Changed |= tryToVectorizeList(Bundle, R);
5785     }
5786   }
5787   return Changed;
5788 }
5789 
5790 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
5791   bool Changed = false;
5792   // Attempt to sort and vectorize each of the store-groups.
5793   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
5794        ++it) {
5795     if (it->second.size() < 2)
5796       continue;
5797 
5798     DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
5799           << it->second.size() << ".\n");
5800 
5801     // Process the stores in chunks of 16.
5802     // TODO: The limit of 16 inhibits greater vectorization factors.
5803     //       For example, AVX2 supports v32i8. Increasing this limit, however,
5804     //       may cause a significant compile-time increase.
5805     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
5806       unsigned Len = std::min<unsigned>(CE - CI, 16);
5807       Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
5808     }
5809   }
5810   return Changed;
5811 }
5812 
5813 char SLPVectorizer::ID = 0;
5814 
5815 static const char lv_name[] = "SLP Vectorizer";
5816 
5817 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
5818 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
5819 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
5820 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
5821 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
5822 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
5823 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
5824 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
5825 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
5826 
5827 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
5828