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