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