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