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