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