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_None;
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 *CInt = nullptr;
2235       for (unsigned i = 0; i < VL.size(); ++i) {
2236         const Instruction *I = cast<Instruction>(VL[i]);
2237         if (!isa<ConstantInt>(I->getOperand(1))) {
2238           Op2VK = TargetTransformInfo::OK_AnyValue;
2239           break;
2240         }
2241         if (i == 0) {
2242           CInt = cast<ConstantInt>(I->getOperand(1));
2243           continue;
2244         }
2245         if (Op2VK == TargetTransformInfo::OK_UniformConstantValue &&
2246             CInt != cast<ConstantInt>(I->getOperand(1)))
2247           Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
2248       }
2249       // FIXME: Currently cost of model modification for division by power of
2250       // 2 is handled for X86 and AArch64. Add support for other targets.
2251       if (Op2VK == TargetTransformInfo::OK_UniformConstantValue && CInt &&
2252           CInt->getValue().isPowerOf2())
2253         Op2VP = TargetTransformInfo::OP_PowerOf2;
2254 
2255       SmallVector<const Value *, 4> Operands(VL0->operand_values());
2256       if (NeedToShuffleReuses) {
2257         ReuseShuffleCost -=
2258             (ReuseShuffleNumbers - VL.size()) *
2259             TTI->getArithmeticInstrCost(S.Opcode, ScalarTy, Op1VK, Op2VK, Op1VP,
2260                                         Op2VP, Operands);
2261       }
2262       int ScalarCost =
2263           VecTy->getNumElements() *
2264           TTI->getArithmeticInstrCost(S.Opcode, ScalarTy, Op1VK, Op2VK, Op1VP,
2265                                       Op2VP, Operands);
2266       int VecCost = TTI->getArithmeticInstrCost(S.Opcode, VecTy, Op1VK, Op2VK,
2267                                                 Op1VP, Op2VP, Operands);
2268       return ReuseShuffleCost + VecCost - ScalarCost;
2269     }
2270     case Instruction::GetElementPtr: {
2271       TargetTransformInfo::OperandValueKind Op1VK =
2272           TargetTransformInfo::OK_AnyValue;
2273       TargetTransformInfo::OperandValueKind Op2VK =
2274           TargetTransformInfo::OK_UniformConstantValue;
2275 
2276       if (NeedToShuffleReuses) {
2277         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) *
2278                             TTI->getArithmeticInstrCost(Instruction::Add,
2279                                                         ScalarTy, Op1VK, Op2VK);
2280       }
2281       int ScalarCost =
2282           VecTy->getNumElements() *
2283           TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
2284       int VecCost =
2285           TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
2286 
2287       return ReuseShuffleCost + VecCost - ScalarCost;
2288     }
2289     case Instruction::Load: {
2290       // Cost of wide load - cost of scalar loads.
2291       unsigned alignment = cast<LoadInst>(VL0)->getAlignment();
2292       if (NeedToShuffleReuses) {
2293         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) *
2294                             TTI->getMemoryOpCost(Instruction::Load, ScalarTy,
2295                                                  alignment, 0, VL0);
2296       }
2297       int ScalarLdCost = VecTy->getNumElements() *
2298           TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0, VL0);
2299       int VecLdCost = TTI->getMemoryOpCost(Instruction::Load,
2300                                            VecTy, alignment, 0, VL0);
2301       if (!E->ReorderIndices.empty()) {
2302         // TODO: Merge this shuffle with the ReuseShuffleCost.
2303         VecLdCost += TTI->getShuffleCost(
2304             TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
2305       }
2306       return ReuseShuffleCost + VecLdCost - ScalarLdCost;
2307     }
2308     case Instruction::Store: {
2309       // We know that we can merge the stores. Calculate the cost.
2310       unsigned alignment = cast<StoreInst>(VL0)->getAlignment();
2311       if (NeedToShuffleReuses) {
2312         ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) *
2313                             TTI->getMemoryOpCost(Instruction::Store, ScalarTy,
2314                                                  alignment, 0, VL0);
2315       }
2316       int ScalarStCost = VecTy->getNumElements() *
2317           TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0, VL0);
2318       int VecStCost = TTI->getMemoryOpCost(Instruction::Store,
2319                                            VecTy, alignment, 0, VL0);
2320       return ReuseShuffleCost + VecStCost - ScalarStCost;
2321     }
2322     case Instruction::Call: {
2323       CallInst *CI = cast<CallInst>(VL0);
2324       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
2325 
2326       // Calculate the cost of the scalar and vector calls.
2327       SmallVector<Type*, 4> ScalarTys;
2328       for (unsigned op = 0, opc = CI->getNumArgOperands(); op!= opc; ++op)
2329         ScalarTys.push_back(CI->getArgOperand(op)->getType());
2330 
2331       FastMathFlags FMF;
2332       if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
2333         FMF = FPMO->getFastMathFlags();
2334 
2335       if (NeedToShuffleReuses) {
2336         ReuseShuffleCost -=
2337             (ReuseShuffleNumbers - VL.size()) *
2338             TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
2339       }
2340       int ScalarCallCost = VecTy->getNumElements() *
2341           TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
2342 
2343       SmallVector<Value *, 4> Args(CI->arg_operands());
2344       int VecCallCost = TTI->getIntrinsicInstrCost(ID, CI->getType(), Args, FMF,
2345                                                    VecTy->getNumElements());
2346 
2347       LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
2348                         << " (" << VecCallCost << "-" << ScalarCallCost << ")"
2349                         << " for " << *CI << "\n");
2350 
2351       return ReuseShuffleCost + VecCallCost - ScalarCallCost;
2352     }
2353     case Instruction::ShuffleVector: {
2354       int ScalarCost = 0;
2355       if (NeedToShuffleReuses) {
2356         for (unsigned Idx : E->ReuseShuffleIndices) {
2357           Instruction *I = cast<Instruction>(VL[Idx]);
2358           if (!I)
2359             continue;
2360           ReuseShuffleCost -=
2361               TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy);
2362         }
2363         for (Value *V : VL) {
2364           Instruction *I = cast<Instruction>(V);
2365           if (!I)
2366             continue;
2367           ReuseShuffleCost +=
2368               TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy);
2369         }
2370       }
2371       int VecCost = 0;
2372       for (Value *i : VL) {
2373         Instruction *I = cast<Instruction>(i);
2374         if (!I)
2375           break;
2376         ScalarCost += TTI->getArithmeticInstrCost(I->getOpcode(), ScalarTy);
2377       }
2378       // VecCost is equal to sum of the cost of creating 2 vectors
2379       // and the cost of creating shuffle.
2380       Instruction *I0 = cast<Instruction>(VL[0]);
2381       VecCost = TTI->getArithmeticInstrCost(I0->getOpcode(), VecTy);
2382       Instruction *I1 = cast<Instruction>(VL[1]);
2383       VecCost += TTI->getArithmeticInstrCost(I1->getOpcode(), VecTy);
2384       VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_Select, VecTy, 0);
2385       return ReuseShuffleCost + VecCost - ScalarCost;
2386     }
2387     default:
2388       llvm_unreachable("Unknown instruction");
2389   }
2390 }
2391 
2392 bool BoUpSLP::isFullyVectorizableTinyTree() {
2393   LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
2394                     << VectorizableTree.size() << " is fully vectorizable .\n");
2395 
2396   // We only handle trees of heights 1 and 2.
2397   if (VectorizableTree.size() == 1 && !VectorizableTree[0].NeedToGather)
2398     return true;
2399 
2400   if (VectorizableTree.size() != 2)
2401     return false;
2402 
2403   // Handle splat and all-constants stores.
2404   if (!VectorizableTree[0].NeedToGather &&
2405       (allConstant(VectorizableTree[1].Scalars) ||
2406        isSplat(VectorizableTree[1].Scalars)))
2407     return true;
2408 
2409   // Gathering cost would be too much for tiny trees.
2410   if (VectorizableTree[0].NeedToGather || VectorizableTree[1].NeedToGather)
2411     return false;
2412 
2413   return true;
2414 }
2415 
2416 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() {
2417   // We can vectorize the tree if its size is greater than or equal to the
2418   // minimum size specified by the MinTreeSize command line option.
2419   if (VectorizableTree.size() >= MinTreeSize)
2420     return false;
2421 
2422   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
2423   // can vectorize it if we can prove it fully vectorizable.
2424   if (isFullyVectorizableTinyTree())
2425     return false;
2426 
2427   assert(VectorizableTree.empty()
2428              ? ExternalUses.empty()
2429              : true && "We shouldn't have any external users");
2430 
2431   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
2432   // vectorizable.
2433   return true;
2434 }
2435 
2436 int BoUpSLP::getSpillCost() {
2437   // Walk from the bottom of the tree to the top, tracking which values are
2438   // live. When we see a call instruction that is not part of our tree,
2439   // query TTI to see if there is a cost to keeping values live over it
2440   // (for example, if spills and fills are required).
2441   unsigned BundleWidth = VectorizableTree.front().Scalars.size();
2442   int Cost = 0;
2443 
2444   SmallPtrSet<Instruction*, 4> LiveValues;
2445   Instruction *PrevInst = nullptr;
2446 
2447   for (const auto &N : VectorizableTree) {
2448     Instruction *Inst = dyn_cast<Instruction>(N.Scalars[0]);
2449     if (!Inst)
2450       continue;
2451 
2452     if (!PrevInst) {
2453       PrevInst = Inst;
2454       continue;
2455     }
2456 
2457     // Update LiveValues.
2458     LiveValues.erase(PrevInst);
2459     for (auto &J : PrevInst->operands()) {
2460       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
2461         LiveValues.insert(cast<Instruction>(&*J));
2462     }
2463 
2464     LLVM_DEBUG({
2465       dbgs() << "SLP: #LV: " << LiveValues.size();
2466       for (auto *X : LiveValues)
2467         dbgs() << " " << X->getName();
2468       dbgs() << ", Looking at ";
2469       Inst->dump();
2470     });
2471 
2472     // Now find the sequence of instructions between PrevInst and Inst.
2473     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
2474                                  PrevInstIt =
2475                                      PrevInst->getIterator().getReverse();
2476     while (InstIt != PrevInstIt) {
2477       if (PrevInstIt == PrevInst->getParent()->rend()) {
2478         PrevInstIt = Inst->getParent()->rbegin();
2479         continue;
2480       }
2481 
2482       // Debug informations don't impact spill cost.
2483       if ((isa<CallInst>(&*PrevInstIt) &&
2484            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
2485           &*PrevInstIt != PrevInst) {
2486         SmallVector<Type*, 4> V;
2487         for (auto *II : LiveValues)
2488           V.push_back(VectorType::get(II->getType(), BundleWidth));
2489         Cost += TTI->getCostOfKeepingLiveOverCall(V);
2490       }
2491 
2492       ++PrevInstIt;
2493     }
2494 
2495     PrevInst = Inst;
2496   }
2497 
2498   return Cost;
2499 }
2500 
2501 int BoUpSLP::getTreeCost() {
2502   int Cost = 0;
2503   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
2504                     << VectorizableTree.size() << ".\n");
2505 
2506   unsigned BundleWidth = VectorizableTree[0].Scalars.size();
2507 
2508   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
2509     TreeEntry &TE = VectorizableTree[I];
2510 
2511     // We create duplicate tree entries for gather sequences that have multiple
2512     // uses. However, we should not compute the cost of duplicate sequences.
2513     // For example, if we have a build vector (i.e., insertelement sequence)
2514     // that is used by more than one vector instruction, we only need to
2515     // compute the cost of the insertelement instructions once. The redundent
2516     // instructions will be eliminated by CSE.
2517     //
2518     // We should consider not creating duplicate tree entries for gather
2519     // sequences, and instead add additional edges to the tree representing
2520     // their uses. Since such an approach results in fewer total entries,
2521     // existing heuristics based on tree size may yeild different results.
2522     //
2523     if (TE.NeedToGather &&
2524         std::any_of(std::next(VectorizableTree.begin(), I + 1),
2525                     VectorizableTree.end(), [TE](TreeEntry &Entry) {
2526                       return Entry.NeedToGather && Entry.isSame(TE.Scalars);
2527                     }))
2528       continue;
2529 
2530     int C = getEntryCost(&TE);
2531     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
2532                       << " for bundle that starts with " << *TE.Scalars[0]
2533                       << ".\n");
2534     Cost += C;
2535   }
2536 
2537   SmallPtrSet<Value *, 16> ExtractCostCalculated;
2538   int ExtractCost = 0;
2539   for (ExternalUser &EU : ExternalUses) {
2540     // We only add extract cost once for the same scalar.
2541     if (!ExtractCostCalculated.insert(EU.Scalar).second)
2542       continue;
2543 
2544     // Uses by ephemeral values are free (because the ephemeral value will be
2545     // removed prior to code generation, and so the extraction will be
2546     // removed as well).
2547     if (EphValues.count(EU.User))
2548       continue;
2549 
2550     // If we plan to rewrite the tree in a smaller type, we will need to sign
2551     // extend the extracted value back to the original type. Here, we account
2552     // for the extract and the added cost of the sign extend if needed.
2553     auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
2554     auto *ScalarRoot = VectorizableTree[0].Scalars[0];
2555     if (MinBWs.count(ScalarRoot)) {
2556       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
2557       auto Extend =
2558           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
2559       VecTy = VectorType::get(MinTy, BundleWidth);
2560       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
2561                                                    VecTy, EU.Lane);
2562     } else {
2563       ExtractCost +=
2564           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
2565     }
2566   }
2567 
2568   int SpillCost = getSpillCost();
2569   Cost += SpillCost + ExtractCost;
2570 
2571   std::string Str;
2572   {
2573     raw_string_ostream OS(Str);
2574     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
2575        << "SLP: Extract Cost = " << ExtractCost << ".\n"
2576        << "SLP: Total Cost = " << Cost << ".\n";
2577   }
2578   LLVM_DEBUG(dbgs() << Str);
2579 
2580   if (ViewSLPTree)
2581     ViewGraph(this, "SLP" + F->getName(), false, Str);
2582 
2583   return Cost;
2584 }
2585 
2586 int BoUpSLP::getGatherCost(Type *Ty,
2587                            const DenseSet<unsigned> &ShuffledIndices) {
2588   int Cost = 0;
2589   for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
2590     if (!ShuffledIndices.count(i))
2591       Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
2592   if (!ShuffledIndices.empty())
2593       Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
2594   return Cost;
2595 }
2596 
2597 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) {
2598   // Find the type of the operands in VL.
2599   Type *ScalarTy = VL[0]->getType();
2600   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
2601     ScalarTy = SI->getValueOperand()->getType();
2602   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2603   // Find the cost of inserting/extracting values from the vector.
2604   // Check if the same elements are inserted several times and count them as
2605   // shuffle candidates.
2606   DenseSet<unsigned> ShuffledElements;
2607   DenseSet<Value *> UniqueElements;
2608   // Iterate in reverse order to consider insert elements with the high cost.
2609   for (unsigned I = VL.size(); I > 0; --I) {
2610     unsigned Idx = I - 1;
2611     if (!UniqueElements.insert(VL[Idx]).second)
2612       ShuffledElements.insert(Idx);
2613   }
2614   return getGatherCost(VecTy, ShuffledElements);
2615 }
2616 
2617 // Reorder commutative operations in alternate shuffle if the resulting vectors
2618 // are consecutive loads. This would allow us to vectorize the tree.
2619 // If we have something like-
2620 // load a[0] - load b[0]
2621 // load b[1] + load a[1]
2622 // load a[2] - load b[2]
2623 // load a[3] + load b[3]
2624 // Reordering the second load b[1]  load a[1] would allow us to vectorize this
2625 // code.
2626 void BoUpSLP::reorderAltShuffleOperands(const InstructionsState &S,
2627                                         ArrayRef<Value *> VL,
2628                                         SmallVectorImpl<Value *> &Left,
2629                                         SmallVectorImpl<Value *> &Right) {
2630   // Push left and right operands of binary operation into Left and Right
2631   for (Value *V : VL) {
2632     auto *I = cast<Instruction>(V);
2633     assert(sameOpcodeOrAlt(S.Opcode, S.AltOpcode, I->getOpcode()) &&
2634            "Incorrect instruction in vector");
2635     Left.push_back(I->getOperand(0));
2636     Right.push_back(I->getOperand(1));
2637   }
2638 
2639   // Reorder if we have a commutative operation and consecutive access
2640   // are on either side of the alternate instructions.
2641   for (unsigned j = 0; j < VL.size() - 1; ++j) {
2642     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2643       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2644         Instruction *VL1 = cast<Instruction>(VL[j]);
2645         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2646         if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2647           std::swap(Left[j], Right[j]);
2648           continue;
2649         } else if (VL2->isCommutative() &&
2650                    isConsecutiveAccess(L, L1, *DL, *SE)) {
2651           std::swap(Left[j + 1], Right[j + 1]);
2652           continue;
2653         }
2654         // else unchanged
2655       }
2656     }
2657     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2658       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2659         Instruction *VL1 = cast<Instruction>(VL[j]);
2660         Instruction *VL2 = cast<Instruction>(VL[j + 1]);
2661         if (VL1->isCommutative() && isConsecutiveAccess(L, L1, *DL, *SE)) {
2662           std::swap(Left[j], Right[j]);
2663           continue;
2664         } else if (VL2->isCommutative() &&
2665                    isConsecutiveAccess(L, L1, *DL, *SE)) {
2666           std::swap(Left[j + 1], Right[j + 1]);
2667           continue;
2668         }
2669         // else unchanged
2670       }
2671     }
2672   }
2673 }
2674 
2675 // Return true if I should be commuted before adding it's left and right
2676 // operands to the arrays Left and Right.
2677 //
2678 // The vectorizer is trying to either have all elements one side being
2679 // instruction with the same opcode to enable further vectorization, or having
2680 // a splat to lower the vectorizing cost.
2681 static bool shouldReorderOperands(
2682     int i, unsigned Opcode, Instruction &I, ArrayRef<Value *> Left,
2683     ArrayRef<Value *> Right, bool AllSameOpcodeLeft, bool AllSameOpcodeRight,
2684     bool SplatLeft, bool SplatRight, Value *&VLeft, Value *&VRight) {
2685   VLeft = I.getOperand(0);
2686   VRight = I.getOperand(1);
2687   // If we have "SplatRight", try to see if commuting is needed to preserve it.
2688   if (SplatRight) {
2689     if (VRight == Right[i - 1])
2690       // Preserve SplatRight
2691       return false;
2692     if (VLeft == Right[i - 1]) {
2693       // Commuting would preserve SplatRight, but we don't want to break
2694       // SplatLeft either, i.e. preserve the original order if possible.
2695       // (FIXME: why do we care?)
2696       if (SplatLeft && VLeft == Left[i - 1])
2697         return false;
2698       return true;
2699     }
2700   }
2701   // Symmetrically handle Right side.
2702   if (SplatLeft) {
2703     if (VLeft == Left[i - 1])
2704       // Preserve SplatLeft
2705       return false;
2706     if (VRight == Left[i - 1])
2707       return true;
2708   }
2709 
2710   Instruction *ILeft = dyn_cast<Instruction>(VLeft);
2711   Instruction *IRight = dyn_cast<Instruction>(VRight);
2712 
2713   // If we have "AllSameOpcodeRight", try to see if the left operands preserves
2714   // it and not the right, in this case we want to commute.
2715   if (AllSameOpcodeRight) {
2716     unsigned RightPrevOpcode = cast<Instruction>(Right[i - 1])->getOpcode();
2717     if (IRight && RightPrevOpcode == IRight->getOpcode())
2718       // Do not commute, a match on the right preserves AllSameOpcodeRight
2719       return false;
2720     if (ILeft && RightPrevOpcode == ILeft->getOpcode()) {
2721       // We have a match and may want to commute, but first check if there is
2722       // not also a match on the existing operands on the Left to preserve
2723       // AllSameOpcodeLeft, i.e. preserve the original order if possible.
2724       // (FIXME: why do we care?)
2725       if (AllSameOpcodeLeft && ILeft &&
2726           cast<Instruction>(Left[i - 1])->getOpcode() == ILeft->getOpcode())
2727         return false;
2728       return true;
2729     }
2730   }
2731   // Symmetrically handle Left side.
2732   if (AllSameOpcodeLeft) {
2733     unsigned LeftPrevOpcode = cast<Instruction>(Left[i - 1])->getOpcode();
2734     if (ILeft && LeftPrevOpcode == ILeft->getOpcode())
2735       return false;
2736     if (IRight && LeftPrevOpcode == IRight->getOpcode())
2737       return true;
2738   }
2739   return false;
2740 }
2741 
2742 void BoUpSLP::reorderInputsAccordingToOpcode(unsigned Opcode,
2743                                              ArrayRef<Value *> VL,
2744                                              SmallVectorImpl<Value *> &Left,
2745                                              SmallVectorImpl<Value *> &Right) {
2746   if (!VL.empty()) {
2747     // Peel the first iteration out of the loop since there's nothing
2748     // interesting to do anyway and it simplifies the checks in the loop.
2749     auto *I = cast<Instruction>(VL[0]);
2750     Value *VLeft = I->getOperand(0);
2751     Value *VRight = I->getOperand(1);
2752     if (!isa<Instruction>(VRight) && isa<Instruction>(VLeft))
2753       // Favor having instruction to the right. FIXME: why?
2754       std::swap(VLeft, VRight);
2755     Left.push_back(VLeft);
2756     Right.push_back(VRight);
2757   }
2758 
2759   // Keep track if we have instructions with all the same opcode on one side.
2760   bool AllSameOpcodeLeft = isa<Instruction>(Left[0]);
2761   bool AllSameOpcodeRight = isa<Instruction>(Right[0]);
2762   // Keep track if we have one side with all the same value (broadcast).
2763   bool SplatLeft = true;
2764   bool SplatRight = true;
2765 
2766   for (unsigned i = 1, e = VL.size(); i != e; ++i) {
2767     Instruction *I = cast<Instruction>(VL[i]);
2768     assert(((I->getOpcode() == Opcode && I->isCommutative()) ||
2769             (I->getOpcode() != Opcode && Instruction::isCommutative(Opcode))) &&
2770            "Can only process commutative instruction");
2771     // Commute to favor either a splat or maximizing having the same opcodes on
2772     // one side.
2773     Value *VLeft;
2774     Value *VRight;
2775     if (shouldReorderOperands(i, Opcode, *I, Left, Right, AllSameOpcodeLeft,
2776                               AllSameOpcodeRight, SplatLeft, SplatRight, VLeft,
2777                               VRight)) {
2778       Left.push_back(VRight);
2779       Right.push_back(VLeft);
2780     } else {
2781       Left.push_back(VLeft);
2782       Right.push_back(VRight);
2783     }
2784     // Update Splat* and AllSameOpcode* after the insertion.
2785     SplatRight = SplatRight && (Right[i - 1] == Right[i]);
2786     SplatLeft = SplatLeft && (Left[i - 1] == Left[i]);
2787     AllSameOpcodeLeft = AllSameOpcodeLeft && isa<Instruction>(Left[i]) &&
2788                         (cast<Instruction>(Left[i - 1])->getOpcode() ==
2789                          cast<Instruction>(Left[i])->getOpcode());
2790     AllSameOpcodeRight = AllSameOpcodeRight && isa<Instruction>(Right[i]) &&
2791                          (cast<Instruction>(Right[i - 1])->getOpcode() ==
2792                           cast<Instruction>(Right[i])->getOpcode());
2793   }
2794 
2795   // If one operand end up being broadcast, return this operand order.
2796   if (SplatRight || SplatLeft)
2797     return;
2798 
2799   // Finally check if we can get longer vectorizable chain by reordering
2800   // without breaking the good operand order detected above.
2801   // E.g. If we have something like-
2802   // load a[0]  load b[0]
2803   // load b[1]  load a[1]
2804   // load a[2]  load b[2]
2805   // load a[3]  load b[3]
2806   // Reordering the second load b[1]  load a[1] would allow us to vectorize
2807   // this code and we still retain AllSameOpcode property.
2808   // FIXME: This load reordering might break AllSameOpcode in some rare cases
2809   // such as-
2810   // add a[0],c[0]  load b[0]
2811   // add a[1],c[2]  load b[1]
2812   // b[2]           load b[2]
2813   // add a[3],c[3]  load b[3]
2814   for (unsigned j = 0, e = VL.size() - 1; j < e; ++j) {
2815     if (LoadInst *L = dyn_cast<LoadInst>(Left[j])) {
2816       if (LoadInst *L1 = dyn_cast<LoadInst>(Right[j + 1])) {
2817         if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2818           std::swap(Left[j + 1], Right[j + 1]);
2819           continue;
2820         }
2821       }
2822     }
2823     if (LoadInst *L = dyn_cast<LoadInst>(Right[j])) {
2824       if (LoadInst *L1 = dyn_cast<LoadInst>(Left[j + 1])) {
2825         if (isConsecutiveAccess(L, L1, *DL, *SE)) {
2826           std::swap(Left[j + 1], Right[j + 1]);
2827           continue;
2828         }
2829       }
2830     }
2831     // else unchanged
2832   }
2833 }
2834 
2835 void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL,
2836                                         const InstructionsState &S) {
2837   // Get the basic block this bundle is in. All instructions in the bundle
2838   // should be in this block.
2839   auto *Front = cast<Instruction>(S.OpValue);
2840   auto *BB = Front->getParent();
2841   const unsigned Opcode = S.Opcode;
2842   const unsigned AltOpcode = S.AltOpcode;
2843   assert(llvm::all_of(make_range(VL.begin(), VL.end()), [=](Value *V) -> bool {
2844     return !sameOpcodeOrAlt(Opcode, AltOpcode,
2845                             cast<Instruction>(V)->getOpcode()) ||
2846            cast<Instruction>(V)->getParent() == BB;
2847   }));
2848 
2849   // The last instruction in the bundle in program order.
2850   Instruction *LastInst = nullptr;
2851 
2852   // Find the last instruction. The common case should be that BB has been
2853   // scheduled, and the last instruction is VL.back(). So we start with
2854   // VL.back() and iterate over schedule data until we reach the end of the
2855   // bundle. The end of the bundle is marked by null ScheduleData.
2856   if (BlocksSchedules.count(BB)) {
2857     auto *Bundle =
2858         BlocksSchedules[BB]->getScheduleData(isOneOf(S, VL.back()));
2859     if (Bundle && Bundle->isPartOfBundle())
2860       for (; Bundle; Bundle = Bundle->NextInBundle)
2861         if (Bundle->OpValue == Bundle->Inst)
2862           LastInst = Bundle->Inst;
2863   }
2864 
2865   // LastInst can still be null at this point if there's either not an entry
2866   // for BB in BlocksSchedules or there's no ScheduleData available for
2867   // VL.back(). This can be the case if buildTree_rec aborts for various
2868   // reasons (e.g., the maximum recursion depth is reached, the maximum region
2869   // size is reached, etc.). ScheduleData is initialized in the scheduling
2870   // "dry-run".
2871   //
2872   // If this happens, we can still find the last instruction by brute force. We
2873   // iterate forwards from Front (inclusive) until we either see all
2874   // instructions in the bundle or reach the end of the block. If Front is the
2875   // last instruction in program order, LastInst will be set to Front, and we
2876   // will visit all the remaining instructions in the block.
2877   //
2878   // One of the reasons we exit early from buildTree_rec is to place an upper
2879   // bound on compile-time. Thus, taking an additional compile-time hit here is
2880   // not ideal. However, this should be exceedingly rare since it requires that
2881   // we both exit early from buildTree_rec and that the bundle be out-of-order
2882   // (causing us to iterate all the way to the end of the block).
2883   if (!LastInst) {
2884     SmallPtrSet<Value *, 16> Bundle(VL.begin(), VL.end());
2885     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
2886       if (Bundle.erase(&I) && sameOpcodeOrAlt(Opcode, AltOpcode, I.getOpcode()))
2887         LastInst = &I;
2888       if (Bundle.empty())
2889         break;
2890     }
2891   }
2892 
2893   // Set the insertion point after the last instruction in the bundle. Set the
2894   // debug location to Front.
2895   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
2896   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
2897 }
2898 
2899 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
2900   Value *Vec = UndefValue::get(Ty);
2901   // Generate the 'InsertElement' instruction.
2902   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
2903     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
2904     if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
2905       GatherSeq.insert(Insrt);
2906       CSEBlocks.insert(Insrt->getParent());
2907 
2908       // Add to our 'need-to-extract' list.
2909       if (TreeEntry *E = getTreeEntry(VL[i])) {
2910         // Find which lane we need to extract.
2911         int FoundLane = -1;
2912         for (unsigned Lane = 0, LE = E->Scalars.size(); Lane != LE; ++Lane) {
2913           // Is this the lane of the scalar that we are looking for ?
2914           if (E->Scalars[Lane] == VL[i]) {
2915             FoundLane = Lane;
2916             break;
2917           }
2918         }
2919         assert(FoundLane >= 0 && "Could not find the correct lane");
2920         if (!E->ReuseShuffleIndices.empty()) {
2921           FoundLane =
2922               std::distance(E->ReuseShuffleIndices.begin(),
2923                             llvm::find(E->ReuseShuffleIndices, FoundLane));
2924         }
2925         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
2926       }
2927     }
2928   }
2929 
2930   return Vec;
2931 }
2932 
2933 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
2934   InstructionsState S = getSameOpcode(VL);
2935   if (S.Opcode) {
2936     if (TreeEntry *E = getTreeEntry(S.OpValue)) {
2937       if (E->isSame(VL)) {
2938         Value *V = vectorizeTree(E);
2939         if (VL.size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) {
2940           // We need to get the vectorized value but without shuffle.
2941           if (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
2942             V = SV->getOperand(0);
2943           } else {
2944             // Reshuffle to get only unique values.
2945             SmallVector<unsigned, 4> UniqueIdxs;
2946             SmallSet<unsigned, 4> UsedIdxs;
2947             for(unsigned Idx : E->ReuseShuffleIndices)
2948               if (UsedIdxs.insert(Idx).second)
2949                 UniqueIdxs.emplace_back(Idx);
2950             V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
2951                                             UniqueIdxs);
2952           }
2953         }
2954         return V;
2955       }
2956     }
2957   }
2958 
2959   Type *ScalarTy = S.OpValue->getType();
2960   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
2961     ScalarTy = SI->getValueOperand()->getType();
2962 
2963   // Check that every instruction appears once in this bundle.
2964   SmallVector<unsigned, 4> ReuseShuffleIndicies;
2965   SmallVector<Value *, 4> UniqueValues;
2966   if (VL.size() > 2) {
2967     DenseMap<Value *, unsigned> UniquePositions;
2968     for (Value *V : VL) {
2969       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
2970       ReuseShuffleIndicies.emplace_back(Res.first->second);
2971       if (Res.second || isa<Constant>(V))
2972         UniqueValues.emplace_back(V);
2973     }
2974     // Do not shuffle single element or if number of unique values is not power
2975     // of 2.
2976     if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 ||
2977         !llvm::isPowerOf2_32(UniqueValues.size()))
2978       ReuseShuffleIndicies.clear();
2979     else
2980       VL = UniqueValues;
2981   }
2982   VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
2983 
2984   Value *V = Gather(VL, VecTy);
2985   if (!ReuseShuffleIndicies.empty()) {
2986     V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
2987                                     ReuseShuffleIndicies, "shuffle");
2988     if (auto *I = dyn_cast<Instruction>(V)) {
2989       GatherSeq.insert(I);
2990       CSEBlocks.insert(I->getParent());
2991     }
2992   }
2993   return V;
2994 }
2995 
2996 static void inversePermutation(ArrayRef<unsigned> Indices,
2997                                SmallVectorImpl<unsigned> &Mask) {
2998   Mask.clear();
2999   const unsigned E = Indices.size();
3000   Mask.resize(E);
3001   for (unsigned I = 0; I < E; ++I)
3002     Mask[Indices[I]] = I;
3003 }
3004 
3005 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
3006   IRBuilder<>::InsertPointGuard Guard(Builder);
3007 
3008   if (E->VectorizedValue) {
3009     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
3010     return E->VectorizedValue;
3011   }
3012 
3013   InstructionsState S = getSameOpcode(E->Scalars);
3014   Instruction *VL0 = cast<Instruction>(S.OpValue);
3015   Type *ScalarTy = VL0->getType();
3016   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
3017     ScalarTy = SI->getValueOperand()->getType();
3018   VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
3019 
3020   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
3021 
3022   if (E->NeedToGather) {
3023     setInsertPointAfterBundle(E->Scalars, S);
3024     auto *V = Gather(E->Scalars, VecTy);
3025     if (NeedToShuffleReuses) {
3026       V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3027                                       E->ReuseShuffleIndices, "shuffle");
3028       if (auto *I = dyn_cast<Instruction>(V)) {
3029         GatherSeq.insert(I);
3030         CSEBlocks.insert(I->getParent());
3031       }
3032     }
3033     E->VectorizedValue = V;
3034     return V;
3035   }
3036 
3037   unsigned ShuffleOrOp = S.isAltShuffle() ?
3038            (unsigned) Instruction::ShuffleVector : S.Opcode;
3039   switch (ShuffleOrOp) {
3040     case Instruction::PHI: {
3041       PHINode *PH = dyn_cast<PHINode>(VL0);
3042       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
3043       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
3044       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
3045       Value *V = NewPhi;
3046       if (NeedToShuffleReuses) {
3047         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3048                                         E->ReuseShuffleIndices, "shuffle");
3049       }
3050       E->VectorizedValue = V;
3051 
3052       // PHINodes may have multiple entries from the same block. We want to
3053       // visit every block once.
3054       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
3055 
3056       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
3057         ValueList Operands;
3058         BasicBlock *IBB = PH->getIncomingBlock(i);
3059 
3060         if (!VisitedBBs.insert(IBB).second) {
3061           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
3062           continue;
3063         }
3064 
3065         // Prepare the operand vector.
3066         for (Value *V : E->Scalars)
3067           Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(IBB));
3068 
3069         Builder.SetInsertPoint(IBB->getTerminator());
3070         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
3071         Value *Vec = vectorizeTree(Operands);
3072         NewPhi->addIncoming(Vec, IBB);
3073       }
3074 
3075       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
3076              "Invalid number of incoming values");
3077       return V;
3078     }
3079 
3080     case Instruction::ExtractElement: {
3081       if (!E->NeedToGather) {
3082         Value *V = VL0->getOperand(0);
3083         if (!E->ReorderIndices.empty()) {
3084           OrdersType Mask;
3085           inversePermutation(E->ReorderIndices, Mask);
3086           Builder.SetInsertPoint(VL0);
3087           V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), Mask,
3088                                           "reorder_shuffle");
3089         }
3090         if (NeedToShuffleReuses) {
3091           // TODO: Merge this shuffle with the ReorderShuffleMask.
3092           if (!E->ReorderIndices.empty())
3093             Builder.SetInsertPoint(VL0);
3094           V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3095                                           E->ReuseShuffleIndices, "shuffle");
3096         }
3097         E->VectorizedValue = V;
3098         return V;
3099       }
3100       setInsertPointAfterBundle(E->Scalars, S);
3101       auto *V = Gather(E->Scalars, VecTy);
3102       if (NeedToShuffleReuses) {
3103         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3104                                         E->ReuseShuffleIndices, "shuffle");
3105         if (auto *I = dyn_cast<Instruction>(V)) {
3106           GatherSeq.insert(I);
3107           CSEBlocks.insert(I->getParent());
3108         }
3109       }
3110       E->VectorizedValue = V;
3111       return V;
3112     }
3113     case Instruction::ExtractValue: {
3114       if (!E->NeedToGather) {
3115         LoadInst *LI = cast<LoadInst>(VL0->getOperand(0));
3116         Builder.SetInsertPoint(LI);
3117         PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
3118         Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
3119         LoadInst *V = Builder.CreateAlignedLoad(Ptr, LI->getAlignment());
3120         Value *NewV = propagateMetadata(V, E->Scalars);
3121         if (!E->ReorderIndices.empty()) {
3122           OrdersType Mask;
3123           inversePermutation(E->ReorderIndices, Mask);
3124           NewV = Builder.CreateShuffleVector(NewV, UndefValue::get(VecTy), Mask,
3125                                              "reorder_shuffle");
3126         }
3127         if (NeedToShuffleReuses) {
3128           // TODO: Merge this shuffle with the ReorderShuffleMask.
3129           NewV = Builder.CreateShuffleVector(
3130               NewV, UndefValue::get(VecTy), E->ReuseShuffleIndices, "shuffle");
3131         }
3132         E->VectorizedValue = NewV;
3133         return NewV;
3134       }
3135       setInsertPointAfterBundle(E->Scalars, S);
3136       auto *V = Gather(E->Scalars, VecTy);
3137       if (NeedToShuffleReuses) {
3138         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3139                                         E->ReuseShuffleIndices, "shuffle");
3140         if (auto *I = dyn_cast<Instruction>(V)) {
3141           GatherSeq.insert(I);
3142           CSEBlocks.insert(I->getParent());
3143         }
3144       }
3145       E->VectorizedValue = V;
3146       return V;
3147     }
3148     case Instruction::ZExt:
3149     case Instruction::SExt:
3150     case Instruction::FPToUI:
3151     case Instruction::FPToSI:
3152     case Instruction::FPExt:
3153     case Instruction::PtrToInt:
3154     case Instruction::IntToPtr:
3155     case Instruction::SIToFP:
3156     case Instruction::UIToFP:
3157     case Instruction::Trunc:
3158     case Instruction::FPTrunc:
3159     case Instruction::BitCast: {
3160       ValueList INVL;
3161       for (Value *V : E->Scalars)
3162         INVL.push_back(cast<Instruction>(V)->getOperand(0));
3163 
3164       setInsertPointAfterBundle(E->Scalars, S);
3165 
3166       Value *InVec = vectorizeTree(INVL);
3167 
3168       if (E->VectorizedValue) {
3169         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3170         return E->VectorizedValue;
3171       }
3172 
3173       CastInst *CI = dyn_cast<CastInst>(VL0);
3174       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
3175       if (NeedToShuffleReuses) {
3176         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3177                                         E->ReuseShuffleIndices, "shuffle");
3178       }
3179       E->VectorizedValue = V;
3180       ++NumVectorInstructions;
3181       return V;
3182     }
3183     case Instruction::FCmp:
3184     case Instruction::ICmp: {
3185       ValueList LHSV, RHSV;
3186       for (Value *V : E->Scalars) {
3187         LHSV.push_back(cast<Instruction>(V)->getOperand(0));
3188         RHSV.push_back(cast<Instruction>(V)->getOperand(1));
3189       }
3190 
3191       setInsertPointAfterBundle(E->Scalars, S);
3192 
3193       Value *L = vectorizeTree(LHSV);
3194       Value *R = vectorizeTree(RHSV);
3195 
3196       if (E->VectorizedValue) {
3197         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3198         return E->VectorizedValue;
3199       }
3200 
3201       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
3202       Value *V;
3203       if (S.Opcode == Instruction::FCmp)
3204         V = Builder.CreateFCmp(P0, L, R);
3205       else
3206         V = Builder.CreateICmp(P0, L, R);
3207 
3208       propagateIRFlags(V, E->Scalars, VL0);
3209       if (NeedToShuffleReuses) {
3210         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3211                                         E->ReuseShuffleIndices, "shuffle");
3212       }
3213       E->VectorizedValue = V;
3214       ++NumVectorInstructions;
3215       return V;
3216     }
3217     case Instruction::Select: {
3218       ValueList TrueVec, FalseVec, CondVec;
3219       for (Value *V : E->Scalars) {
3220         CondVec.push_back(cast<Instruction>(V)->getOperand(0));
3221         TrueVec.push_back(cast<Instruction>(V)->getOperand(1));
3222         FalseVec.push_back(cast<Instruction>(V)->getOperand(2));
3223       }
3224 
3225       setInsertPointAfterBundle(E->Scalars, S);
3226 
3227       Value *Cond = vectorizeTree(CondVec);
3228       Value *True = vectorizeTree(TrueVec);
3229       Value *False = vectorizeTree(FalseVec);
3230 
3231       if (E->VectorizedValue) {
3232         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3233         return E->VectorizedValue;
3234       }
3235 
3236       Value *V = Builder.CreateSelect(Cond, True, False);
3237       if (NeedToShuffleReuses) {
3238         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3239                                         E->ReuseShuffleIndices, "shuffle");
3240       }
3241       E->VectorizedValue = V;
3242       ++NumVectorInstructions;
3243       return V;
3244     }
3245     case Instruction::Add:
3246     case Instruction::FAdd:
3247     case Instruction::Sub:
3248     case Instruction::FSub:
3249     case Instruction::Mul:
3250     case Instruction::FMul:
3251     case Instruction::UDiv:
3252     case Instruction::SDiv:
3253     case Instruction::FDiv:
3254     case Instruction::URem:
3255     case Instruction::SRem:
3256     case Instruction::FRem:
3257     case Instruction::Shl:
3258     case Instruction::LShr:
3259     case Instruction::AShr:
3260     case Instruction::And:
3261     case Instruction::Or:
3262     case Instruction::Xor: {
3263       ValueList LHSVL, RHSVL;
3264       if (isa<BinaryOperator>(VL0) && VL0->isCommutative())
3265         reorderInputsAccordingToOpcode(S.Opcode, E->Scalars, LHSVL,
3266                                        RHSVL);
3267       else
3268         for (Value *V : E->Scalars) {
3269           auto *I = cast<Instruction>(V);
3270           LHSVL.push_back(I->getOperand(0));
3271           RHSVL.push_back(I->getOperand(1));
3272         }
3273 
3274       setInsertPointAfterBundle(E->Scalars, S);
3275 
3276       Value *LHS = vectorizeTree(LHSVL);
3277       Value *RHS = vectorizeTree(RHSVL);
3278 
3279       if (E->VectorizedValue) {
3280         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3281         return E->VectorizedValue;
3282       }
3283 
3284       Value *V = Builder.CreateBinOp(
3285           static_cast<Instruction::BinaryOps>(S.Opcode), LHS, RHS);
3286       propagateIRFlags(V, E->Scalars, VL0);
3287       if (auto *I = dyn_cast<Instruction>(V))
3288         V = propagateMetadata(I, E->Scalars);
3289 
3290       if (NeedToShuffleReuses) {
3291         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3292                                         E->ReuseShuffleIndices, "shuffle");
3293       }
3294       E->VectorizedValue = V;
3295       ++NumVectorInstructions;
3296 
3297       return V;
3298     }
3299     case Instruction::Load: {
3300       // Loads are inserted at the head of the tree because we don't want to
3301       // sink them all the way down past store instructions.
3302       bool IsReorder = !E->ReorderIndices.empty();
3303       if (IsReorder) {
3304         S = getSameOpcode(E->Scalars, E->ReorderIndices.front());
3305         VL0 = cast<Instruction>(S.OpValue);
3306       }
3307       setInsertPointAfterBundle(E->Scalars, S);
3308 
3309       LoadInst *LI = cast<LoadInst>(VL0);
3310       Type *ScalarLoadTy = LI->getType();
3311       unsigned AS = LI->getPointerAddressSpace();
3312 
3313       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
3314                                             VecTy->getPointerTo(AS));
3315 
3316       // The pointer operand uses an in-tree scalar so we add the new BitCast to
3317       // ExternalUses list to make sure that an extract will be generated in the
3318       // future.
3319       Value *PO = LI->getPointerOperand();
3320       if (getTreeEntry(PO))
3321         ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
3322 
3323       unsigned Alignment = LI->getAlignment();
3324       LI = Builder.CreateLoad(VecPtr);
3325       if (!Alignment) {
3326         Alignment = DL->getABITypeAlignment(ScalarLoadTy);
3327       }
3328       LI->setAlignment(Alignment);
3329       Value *V = propagateMetadata(LI, E->Scalars);
3330       if (IsReorder) {
3331         OrdersType Mask;
3332         inversePermutation(E->ReorderIndices, Mask);
3333         V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
3334                                         Mask, "reorder_shuffle");
3335       }
3336       if (NeedToShuffleReuses) {
3337         // TODO: Merge this shuffle with the ReorderShuffleMask.
3338         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3339                                         E->ReuseShuffleIndices, "shuffle");
3340       }
3341       E->VectorizedValue = V;
3342       ++NumVectorInstructions;
3343       return V;
3344     }
3345     case Instruction::Store: {
3346       StoreInst *SI = cast<StoreInst>(VL0);
3347       unsigned Alignment = SI->getAlignment();
3348       unsigned AS = SI->getPointerAddressSpace();
3349 
3350       ValueList ScalarStoreValues;
3351       for (Value *V : E->Scalars)
3352         ScalarStoreValues.push_back(cast<StoreInst>(V)->getValueOperand());
3353 
3354       setInsertPointAfterBundle(E->Scalars, S);
3355 
3356       Value *VecValue = vectorizeTree(ScalarStoreValues);
3357       Value *ScalarPtr = SI->getPointerOperand();
3358       Value *VecPtr = Builder.CreateBitCast(ScalarPtr, VecTy->getPointerTo(AS));
3359       StoreInst *ST = Builder.CreateStore(VecValue, VecPtr);
3360 
3361       // The pointer operand uses an in-tree scalar, so add the new BitCast to
3362       // ExternalUses to make sure that an extract will be generated in the
3363       // future.
3364       if (getTreeEntry(ScalarPtr))
3365         ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
3366 
3367       if (!Alignment)
3368         Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
3369 
3370       ST->setAlignment(Alignment);
3371       Value *V = propagateMetadata(ST, E->Scalars);
3372       if (NeedToShuffleReuses) {
3373         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3374                                         E->ReuseShuffleIndices, "shuffle");
3375       }
3376       E->VectorizedValue = V;
3377       ++NumVectorInstructions;
3378       return V;
3379     }
3380     case Instruction::GetElementPtr: {
3381       setInsertPointAfterBundle(E->Scalars, S);
3382 
3383       ValueList Op0VL;
3384       for (Value *V : E->Scalars)
3385         Op0VL.push_back(cast<GetElementPtrInst>(V)->getOperand(0));
3386 
3387       Value *Op0 = vectorizeTree(Op0VL);
3388 
3389       std::vector<Value *> OpVecs;
3390       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
3391            ++j) {
3392         ValueList OpVL;
3393         for (Value *V : E->Scalars)
3394           OpVL.push_back(cast<GetElementPtrInst>(V)->getOperand(j));
3395 
3396         Value *OpVec = vectorizeTree(OpVL);
3397         OpVecs.push_back(OpVec);
3398       }
3399 
3400       Value *V = Builder.CreateGEP(
3401           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
3402       if (Instruction *I = dyn_cast<Instruction>(V))
3403         V = propagateMetadata(I, E->Scalars);
3404 
3405       if (NeedToShuffleReuses) {
3406         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3407                                         E->ReuseShuffleIndices, "shuffle");
3408       }
3409       E->VectorizedValue = V;
3410       ++NumVectorInstructions;
3411 
3412       return V;
3413     }
3414     case Instruction::Call: {
3415       CallInst *CI = cast<CallInst>(VL0);
3416       setInsertPointAfterBundle(E->Scalars, S);
3417       Function *FI;
3418       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
3419       Value *ScalarArg = nullptr;
3420       if (CI && (FI = CI->getCalledFunction())) {
3421         IID = FI->getIntrinsicID();
3422       }
3423       std::vector<Value *> OpVecs;
3424       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
3425         ValueList OpVL;
3426         // ctlz,cttz and powi are special intrinsics whose second argument is
3427         // a scalar. This argument should not be vectorized.
3428         if (hasVectorInstrinsicScalarOpd(IID, 1) && j == 1) {
3429           CallInst *CEI = cast<CallInst>(VL0);
3430           ScalarArg = CEI->getArgOperand(j);
3431           OpVecs.push_back(CEI->getArgOperand(j));
3432           continue;
3433         }
3434         for (Value *V : E->Scalars) {
3435           CallInst *CEI = cast<CallInst>(V);
3436           OpVL.push_back(CEI->getArgOperand(j));
3437         }
3438 
3439         Value *OpVec = vectorizeTree(OpVL);
3440         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
3441         OpVecs.push_back(OpVec);
3442       }
3443 
3444       Module *M = F->getParent();
3445       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
3446       Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
3447       Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
3448       SmallVector<OperandBundleDef, 1> OpBundles;
3449       CI->getOperandBundlesAsDefs(OpBundles);
3450       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
3451 
3452       // The scalar argument uses an in-tree scalar so we add the new vectorized
3453       // call to ExternalUses list to make sure that an extract will be
3454       // generated in the future.
3455       if (ScalarArg && getTreeEntry(ScalarArg))
3456         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
3457 
3458       propagateIRFlags(V, E->Scalars, VL0);
3459       if (NeedToShuffleReuses) {
3460         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3461                                         E->ReuseShuffleIndices, "shuffle");
3462       }
3463       E->VectorizedValue = V;
3464       ++NumVectorInstructions;
3465       return V;
3466     }
3467     case Instruction::ShuffleVector: {
3468       ValueList LHSVL, RHSVL;
3469       assert(Instruction::isBinaryOp(S.Opcode) &&
3470              "Invalid Shuffle Vector Operand");
3471       reorderAltShuffleOperands(S, E->Scalars, LHSVL, RHSVL);
3472       setInsertPointAfterBundle(E->Scalars, S);
3473 
3474       Value *LHS = vectorizeTree(LHSVL);
3475       Value *RHS = vectorizeTree(RHSVL);
3476 
3477       if (E->VectorizedValue) {
3478         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
3479         return E->VectorizedValue;
3480       }
3481 
3482       // Create a vector of LHS op1 RHS
3483       Value *V0 = Builder.CreateBinOp(
3484           static_cast<Instruction::BinaryOps>(S.Opcode), LHS, RHS);
3485 
3486       // Create a vector of LHS op2 RHS
3487       Value *V1 = Builder.CreateBinOp(
3488           static_cast<Instruction::BinaryOps>(S.AltOpcode), LHS, RHS);
3489 
3490       // Create shuffle to take alternate operations from the vector.
3491       // Also, gather up odd and even scalar ops to propagate IR flags to
3492       // each vector operation.
3493       ValueList OpScalars, AltScalars;
3494       unsigned e = E->Scalars.size();
3495       SmallVector<Constant *, 8> Mask(e);
3496       for (unsigned i = 0; i < e; ++i) {
3497         auto *OpInst = cast<Instruction>(E->Scalars[i]);
3498         unsigned InstOpcode = OpInst->getOpcode();
3499         assert(sameOpcodeOrAlt(S.Opcode, S.AltOpcode, InstOpcode) &&
3500                "Unexpected main/alternate opcode");
3501         if (InstOpcode == S.AltOpcode) {
3502           Mask[i] = Builder.getInt32(e + i);
3503           AltScalars.push_back(E->Scalars[i]);
3504         } else {
3505           Mask[i] = Builder.getInt32(i);
3506           OpScalars.push_back(E->Scalars[i]);
3507         }
3508       }
3509 
3510       Value *ShuffleMask = ConstantVector::get(Mask);
3511       propagateIRFlags(V0, OpScalars);
3512       propagateIRFlags(V1, AltScalars);
3513 
3514       Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
3515       if (Instruction *I = dyn_cast<Instruction>(V))
3516         V = propagateMetadata(I, E->Scalars);
3517       if (NeedToShuffleReuses) {
3518         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
3519                                         E->ReuseShuffleIndices, "shuffle");
3520       }
3521       E->VectorizedValue = V;
3522       ++NumVectorInstructions;
3523 
3524       return V;
3525     }
3526     default:
3527     llvm_unreachable("unknown inst");
3528   }
3529   return nullptr;
3530 }
3531 
3532 Value *BoUpSLP::vectorizeTree() {
3533   ExtraValueToDebugLocsMap ExternallyUsedValues;
3534   return vectorizeTree(ExternallyUsedValues);
3535 }
3536 
3537 Value *
3538 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
3539   // All blocks must be scheduled before any instructions are inserted.
3540   for (auto &BSIter : BlocksSchedules) {
3541     scheduleBlock(BSIter.second.get());
3542   }
3543 
3544   Builder.SetInsertPoint(&F->getEntryBlock().front());
3545   auto *VectorRoot = vectorizeTree(&VectorizableTree[0]);
3546 
3547   // If the vectorized tree can be rewritten in a smaller type, we truncate the
3548   // vectorized root. InstCombine will then rewrite the entire expression. We
3549   // sign extend the extracted values below.
3550   auto *ScalarRoot = VectorizableTree[0].Scalars[0];
3551   if (MinBWs.count(ScalarRoot)) {
3552     if (auto *I = dyn_cast<Instruction>(VectorRoot))
3553       Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
3554     auto BundleWidth = VectorizableTree[0].Scalars.size();
3555     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
3556     auto *VecTy = VectorType::get(MinTy, BundleWidth);
3557     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
3558     VectorizableTree[0].VectorizedValue = Trunc;
3559   }
3560 
3561   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
3562                     << " values .\n");
3563 
3564   // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
3565   // specified by ScalarType.
3566   auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
3567     if (!MinBWs.count(ScalarRoot))
3568       return Ex;
3569     if (MinBWs[ScalarRoot].second)
3570       return Builder.CreateSExt(Ex, ScalarType);
3571     return Builder.CreateZExt(Ex, ScalarType);
3572   };
3573 
3574   // Extract all of the elements with the external uses.
3575   for (const auto &ExternalUse : ExternalUses) {
3576     Value *Scalar = ExternalUse.Scalar;
3577     llvm::User *User = ExternalUse.User;
3578 
3579     // Skip users that we already RAUW. This happens when one instruction
3580     // has multiple uses of the same value.
3581     if (User && !is_contained(Scalar->users(), User))
3582       continue;
3583     TreeEntry *E = getTreeEntry(Scalar);
3584     assert(E && "Invalid scalar");
3585     assert(!E->NeedToGather && "Extracting from a gather list");
3586 
3587     Value *Vec = E->VectorizedValue;
3588     assert(Vec && "Can't find vectorizable value");
3589 
3590     Value *Lane = Builder.getInt32(ExternalUse.Lane);
3591     // If User == nullptr, the Scalar is used as extra arg. Generate
3592     // ExtractElement instruction and update the record for this scalar in
3593     // ExternallyUsedValues.
3594     if (!User) {
3595       assert(ExternallyUsedValues.count(Scalar) &&
3596              "Scalar with nullptr as an external user must be registered in "
3597              "ExternallyUsedValues map");
3598       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
3599         Builder.SetInsertPoint(VecI->getParent(),
3600                                std::next(VecI->getIterator()));
3601       } else {
3602         Builder.SetInsertPoint(&F->getEntryBlock().front());
3603       }
3604       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3605       Ex = extend(ScalarRoot, Ex, Scalar->getType());
3606       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
3607       auto &Locs = ExternallyUsedValues[Scalar];
3608       ExternallyUsedValues.insert({Ex, Locs});
3609       ExternallyUsedValues.erase(Scalar);
3610       continue;
3611     }
3612 
3613     // Generate extracts for out-of-tree users.
3614     // Find the insertion point for the extractelement lane.
3615     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
3616       if (PHINode *PH = dyn_cast<PHINode>(User)) {
3617         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
3618           if (PH->getIncomingValue(i) == Scalar) {
3619             TerminatorInst *IncomingTerminator =
3620                 PH->getIncomingBlock(i)->getTerminator();
3621             if (isa<CatchSwitchInst>(IncomingTerminator)) {
3622               Builder.SetInsertPoint(VecI->getParent(),
3623                                      std::next(VecI->getIterator()));
3624             } else {
3625               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
3626             }
3627             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3628             Ex = extend(ScalarRoot, Ex, Scalar->getType());
3629             CSEBlocks.insert(PH->getIncomingBlock(i));
3630             PH->setOperand(i, Ex);
3631           }
3632         }
3633       } else {
3634         Builder.SetInsertPoint(cast<Instruction>(User));
3635         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3636         Ex = extend(ScalarRoot, Ex, Scalar->getType());
3637         CSEBlocks.insert(cast<Instruction>(User)->getParent());
3638         User->replaceUsesOfWith(Scalar, Ex);
3639       }
3640     } else {
3641       Builder.SetInsertPoint(&F->getEntryBlock().front());
3642       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
3643       Ex = extend(ScalarRoot, Ex, Scalar->getType());
3644       CSEBlocks.insert(&F->getEntryBlock());
3645       User->replaceUsesOfWith(Scalar, Ex);
3646     }
3647 
3648     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
3649   }
3650 
3651   // For each vectorized value:
3652   for (TreeEntry &EIdx : VectorizableTree) {
3653     TreeEntry *Entry = &EIdx;
3654 
3655     // No need to handle users of gathered values.
3656     if (Entry->NeedToGather)
3657       continue;
3658 
3659     assert(Entry->VectorizedValue && "Can't find vectorizable value");
3660 
3661     // For each lane:
3662     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
3663       Value *Scalar = Entry->Scalars[Lane];
3664 
3665       Type *Ty = Scalar->getType();
3666       if (!Ty->isVoidTy()) {
3667 #ifndef NDEBUG
3668         for (User *U : Scalar->users()) {
3669           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
3670 
3671           // It is legal to replace users in the ignorelist by undef.
3672           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
3673                  "Replacing out-of-tree value with undef");
3674         }
3675 #endif
3676         Value *Undef = UndefValue::get(Ty);
3677         Scalar->replaceAllUsesWith(Undef);
3678       }
3679       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
3680       eraseInstruction(cast<Instruction>(Scalar));
3681     }
3682   }
3683 
3684   Builder.ClearInsertionPoint();
3685 
3686   return VectorizableTree[0].VectorizedValue;
3687 }
3688 
3689 void BoUpSLP::optimizeGatherSequence() {
3690   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
3691                     << " gather sequences instructions.\n");
3692   // LICM InsertElementInst sequences.
3693   for (Instruction *I : GatherSeq) {
3694     if (!isa<InsertElementInst>(I) && !isa<ShuffleVectorInst>(I))
3695       continue;
3696 
3697     // Check if this block is inside a loop.
3698     Loop *L = LI->getLoopFor(I->getParent());
3699     if (!L)
3700       continue;
3701 
3702     // Check if it has a preheader.
3703     BasicBlock *PreHeader = L->getLoopPreheader();
3704     if (!PreHeader)
3705       continue;
3706 
3707     // If the vector or the element that we insert into it are
3708     // instructions that are defined in this basic block then we can't
3709     // hoist this instruction.
3710     auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
3711     auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
3712     if (Op0 && L->contains(Op0))
3713       continue;
3714     if (Op1 && L->contains(Op1))
3715       continue;
3716 
3717     // We can hoist this instruction. Move it to the pre-header.
3718     I->moveBefore(PreHeader->getTerminator());
3719   }
3720 
3721   // Make a list of all reachable blocks in our CSE queue.
3722   SmallVector<const DomTreeNode *, 8> CSEWorkList;
3723   CSEWorkList.reserve(CSEBlocks.size());
3724   for (BasicBlock *BB : CSEBlocks)
3725     if (DomTreeNode *N = DT->getNode(BB)) {
3726       assert(DT->isReachableFromEntry(N));
3727       CSEWorkList.push_back(N);
3728     }
3729 
3730   // Sort blocks by domination. This ensures we visit a block after all blocks
3731   // dominating it are visited.
3732   std::stable_sort(CSEWorkList.begin(), CSEWorkList.end(),
3733                    [this](const DomTreeNode *A, const DomTreeNode *B) {
3734     return DT->properlyDominates(A, B);
3735   });
3736 
3737   // Perform O(N^2) search over the gather sequences and merge identical
3738   // instructions. TODO: We can further optimize this scan if we split the
3739   // instructions into different buckets based on the insert lane.
3740   SmallVector<Instruction *, 16> Visited;
3741   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
3742     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
3743            "Worklist not sorted properly!");
3744     BasicBlock *BB = (*I)->getBlock();
3745     // For all instructions in blocks containing gather sequences:
3746     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
3747       Instruction *In = &*it++;
3748       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
3749         continue;
3750 
3751       // Check if we can replace this instruction with any of the
3752       // visited instructions.
3753       for (Instruction *v : Visited) {
3754         if (In->isIdenticalTo(v) &&
3755             DT->dominates(v->getParent(), In->getParent())) {
3756           In->replaceAllUsesWith(v);
3757           eraseInstruction(In);
3758           In = nullptr;
3759           break;
3760         }
3761       }
3762       if (In) {
3763         assert(!is_contained(Visited, In));
3764         Visited.push_back(In);
3765       }
3766     }
3767   }
3768   CSEBlocks.clear();
3769   GatherSeq.clear();
3770 }
3771 
3772 // Groups the instructions to a bundle (which is then a single scheduling entity)
3773 // and schedules instructions until the bundle gets ready.
3774 bool BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL,
3775                                                  BoUpSLP *SLP,
3776                                                  const InstructionsState &S) {
3777   if (isa<PHINode>(S.OpValue))
3778     return true;
3779 
3780   // Initialize the instruction bundle.
3781   Instruction *OldScheduleEnd = ScheduleEnd;
3782   ScheduleData *PrevInBundle = nullptr;
3783   ScheduleData *Bundle = nullptr;
3784   bool ReSchedule = false;
3785   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
3786 
3787   // Make sure that the scheduling region contains all
3788   // instructions of the bundle.
3789   for (Value *V : VL) {
3790     if (!extendSchedulingRegion(V, S))
3791       return false;
3792   }
3793 
3794   for (Value *V : VL) {
3795     ScheduleData *BundleMember = getScheduleData(V);
3796     assert(BundleMember &&
3797            "no ScheduleData for bundle member (maybe not in same basic block)");
3798     if (BundleMember->IsScheduled) {
3799       // A bundle member was scheduled as single instruction before and now
3800       // needs to be scheduled as part of the bundle. We just get rid of the
3801       // existing schedule.
3802       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
3803                         << " was already scheduled\n");
3804       ReSchedule = true;
3805     }
3806     assert(BundleMember->isSchedulingEntity() &&
3807            "bundle member already part of other bundle");
3808     if (PrevInBundle) {
3809       PrevInBundle->NextInBundle = BundleMember;
3810     } else {
3811       Bundle = BundleMember;
3812     }
3813     BundleMember->UnscheduledDepsInBundle = 0;
3814     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
3815 
3816     // Group the instructions to a bundle.
3817     BundleMember->FirstInBundle = Bundle;
3818     PrevInBundle = BundleMember;
3819   }
3820   if (ScheduleEnd != OldScheduleEnd) {
3821     // The scheduling region got new instructions at the lower end (or it is a
3822     // new region for the first bundle). This makes it necessary to
3823     // recalculate all dependencies.
3824     // It is seldom that this needs to be done a second time after adding the
3825     // initial bundle to the region.
3826     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3827       doForAllOpcodes(I, [](ScheduleData *SD) {
3828         SD->clearDependencies();
3829       });
3830     }
3831     ReSchedule = true;
3832   }
3833   if (ReSchedule) {
3834     resetSchedule();
3835     initialFillReadyList(ReadyInsts);
3836   }
3837 
3838   LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
3839                     << BB->getName() << "\n");
3840 
3841   calculateDependencies(Bundle, true, SLP);
3842 
3843   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
3844   // means that there are no cyclic dependencies and we can schedule it.
3845   // Note that's important that we don't "schedule" the bundle yet (see
3846   // cancelScheduling).
3847   while (!Bundle->isReady() && !ReadyInsts.empty()) {
3848 
3849     ScheduleData *pickedSD = ReadyInsts.back();
3850     ReadyInsts.pop_back();
3851 
3852     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
3853       schedule(pickedSD, ReadyInsts);
3854     }
3855   }
3856   if (!Bundle->isReady()) {
3857     cancelScheduling(VL, S.OpValue);
3858     return false;
3859   }
3860   return true;
3861 }
3862 
3863 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
3864                                                 Value *OpValue) {
3865   if (isa<PHINode>(OpValue))
3866     return;
3867 
3868   ScheduleData *Bundle = getScheduleData(OpValue);
3869   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
3870   assert(!Bundle->IsScheduled &&
3871          "Can't cancel bundle which is already scheduled");
3872   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
3873          "tried to unbundle something which is not a bundle");
3874 
3875   // Un-bundle: make single instructions out of the bundle.
3876   ScheduleData *BundleMember = Bundle;
3877   while (BundleMember) {
3878     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
3879     BundleMember->FirstInBundle = BundleMember;
3880     ScheduleData *Next = BundleMember->NextInBundle;
3881     BundleMember->NextInBundle = nullptr;
3882     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
3883     if (BundleMember->UnscheduledDepsInBundle == 0) {
3884       ReadyInsts.insert(BundleMember);
3885     }
3886     BundleMember = Next;
3887   }
3888 }
3889 
3890 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
3891   // Allocate a new ScheduleData for the instruction.
3892   if (ChunkPos >= ChunkSize) {
3893     ScheduleDataChunks.push_back(llvm::make_unique<ScheduleData[]>(ChunkSize));
3894     ChunkPos = 0;
3895   }
3896   return &(ScheduleDataChunks.back()[ChunkPos++]);
3897 }
3898 
3899 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
3900                                                       const InstructionsState &S) {
3901   if (getScheduleData(V, isOneOf(S, V)))
3902     return true;
3903   Instruction *I = dyn_cast<Instruction>(V);
3904   assert(I && "bundle member must be an instruction");
3905   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
3906   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
3907     ScheduleData *ISD = getScheduleData(I);
3908     if (!ISD)
3909       return false;
3910     assert(isInSchedulingRegion(ISD) &&
3911            "ScheduleData not in scheduling region");
3912     ScheduleData *SD = allocateScheduleDataChunks();
3913     SD->Inst = I;
3914     SD->init(SchedulingRegionID, S.OpValue);
3915     ExtraScheduleDataMap[I][S.OpValue] = SD;
3916     return true;
3917   };
3918   if (CheckSheduleForI(I))
3919     return true;
3920   if (!ScheduleStart) {
3921     // It's the first instruction in the new region.
3922     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
3923     ScheduleStart = I;
3924     ScheduleEnd = I->getNextNode();
3925     if (isOneOf(S, I) != I)
3926       CheckSheduleForI(I);
3927     assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3928     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
3929     return true;
3930   }
3931   // Search up and down at the same time, because we don't know if the new
3932   // instruction is above or below the existing scheduling region.
3933   BasicBlock::reverse_iterator UpIter =
3934       ++ScheduleStart->getIterator().getReverse();
3935   BasicBlock::reverse_iterator UpperEnd = BB->rend();
3936   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
3937   BasicBlock::iterator LowerEnd = BB->end();
3938   while (true) {
3939     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
3940       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
3941       return false;
3942     }
3943 
3944     if (UpIter != UpperEnd) {
3945       if (&*UpIter == I) {
3946         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
3947         ScheduleStart = I;
3948         if (isOneOf(S, I) != I)
3949           CheckSheduleForI(I);
3950         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
3951                           << "\n");
3952         return true;
3953       }
3954       UpIter++;
3955     }
3956     if (DownIter != LowerEnd) {
3957       if (&*DownIter == I) {
3958         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
3959                          nullptr);
3960         ScheduleEnd = I->getNextNode();
3961         if (isOneOf(S, I) != I)
3962           CheckSheduleForI(I);
3963         assert(ScheduleEnd && "tried to vectorize a TerminatorInst?");
3964         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I
3965                           << "\n");
3966         return true;
3967       }
3968       DownIter++;
3969     }
3970     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
3971            "instruction not found in block");
3972   }
3973   return true;
3974 }
3975 
3976 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
3977                                                 Instruction *ToI,
3978                                                 ScheduleData *PrevLoadStore,
3979                                                 ScheduleData *NextLoadStore) {
3980   ScheduleData *CurrentLoadStore = PrevLoadStore;
3981   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
3982     ScheduleData *SD = ScheduleDataMap[I];
3983     if (!SD) {
3984       SD = allocateScheduleDataChunks();
3985       ScheduleDataMap[I] = SD;
3986       SD->Inst = I;
3987     }
3988     assert(!isInSchedulingRegion(SD) &&
3989            "new ScheduleData already in scheduling region");
3990     SD->init(SchedulingRegionID, I);
3991 
3992     if (I->mayReadOrWriteMemory() &&
3993         (!isa<IntrinsicInst>(I) ||
3994          cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect)) {
3995       // Update the linked list of memory accessing instructions.
3996       if (CurrentLoadStore) {
3997         CurrentLoadStore->NextLoadStore = SD;
3998       } else {
3999         FirstLoadStoreInRegion = SD;
4000       }
4001       CurrentLoadStore = SD;
4002     }
4003   }
4004   if (NextLoadStore) {
4005     if (CurrentLoadStore)
4006       CurrentLoadStore->NextLoadStore = NextLoadStore;
4007   } else {
4008     LastLoadStoreInRegion = CurrentLoadStore;
4009   }
4010 }
4011 
4012 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
4013                                                      bool InsertInReadyList,
4014                                                      BoUpSLP *SLP) {
4015   assert(SD->isSchedulingEntity());
4016 
4017   SmallVector<ScheduleData *, 10> WorkList;
4018   WorkList.push_back(SD);
4019 
4020   while (!WorkList.empty()) {
4021     ScheduleData *SD = WorkList.back();
4022     WorkList.pop_back();
4023 
4024     ScheduleData *BundleMember = SD;
4025     while (BundleMember) {
4026       assert(isInSchedulingRegion(BundleMember));
4027       if (!BundleMember->hasValidDependencies()) {
4028 
4029         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
4030                           << "\n");
4031         BundleMember->Dependencies = 0;
4032         BundleMember->resetUnscheduledDeps();
4033 
4034         // Handle def-use chain dependencies.
4035         if (BundleMember->OpValue != BundleMember->Inst) {
4036           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
4037           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
4038             BundleMember->Dependencies++;
4039             ScheduleData *DestBundle = UseSD->FirstInBundle;
4040             if (!DestBundle->IsScheduled)
4041               BundleMember->incrementUnscheduledDeps(1);
4042             if (!DestBundle->hasValidDependencies())
4043               WorkList.push_back(DestBundle);
4044           }
4045         } else {
4046           for (User *U : BundleMember->Inst->users()) {
4047             if (isa<Instruction>(U)) {
4048               ScheduleData *UseSD = getScheduleData(U);
4049               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
4050                 BundleMember->Dependencies++;
4051                 ScheduleData *DestBundle = UseSD->FirstInBundle;
4052                 if (!DestBundle->IsScheduled)
4053                   BundleMember->incrementUnscheduledDeps(1);
4054                 if (!DestBundle->hasValidDependencies())
4055                   WorkList.push_back(DestBundle);
4056               }
4057             } else {
4058               // I'm not sure if this can ever happen. But we need to be safe.
4059               // This lets the instruction/bundle never be scheduled and
4060               // eventually disable vectorization.
4061               BundleMember->Dependencies++;
4062               BundleMember->incrementUnscheduledDeps(1);
4063             }
4064           }
4065         }
4066 
4067         // Handle the memory dependencies.
4068         ScheduleData *DepDest = BundleMember->NextLoadStore;
4069         if (DepDest) {
4070           Instruction *SrcInst = BundleMember->Inst;
4071           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
4072           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
4073           unsigned numAliased = 0;
4074           unsigned DistToSrc = 1;
4075 
4076           while (DepDest) {
4077             assert(isInSchedulingRegion(DepDest));
4078 
4079             // We have two limits to reduce the complexity:
4080             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
4081             //    SLP->isAliased (which is the expensive part in this loop).
4082             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
4083             //    the whole loop (even if the loop is fast, it's quadratic).
4084             //    It's important for the loop break condition (see below) to
4085             //    check this limit even between two read-only instructions.
4086             if (DistToSrc >= MaxMemDepDistance ||
4087                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
4088                      (numAliased >= AliasedCheckLimit ||
4089                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
4090 
4091               // We increment the counter only if the locations are aliased
4092               // (instead of counting all alias checks). This gives a better
4093               // balance between reduced runtime and accurate dependencies.
4094               numAliased++;
4095 
4096               DepDest->MemoryDependencies.push_back(BundleMember);
4097               BundleMember->Dependencies++;
4098               ScheduleData *DestBundle = DepDest->FirstInBundle;
4099               if (!DestBundle->IsScheduled) {
4100                 BundleMember->incrementUnscheduledDeps(1);
4101               }
4102               if (!DestBundle->hasValidDependencies()) {
4103                 WorkList.push_back(DestBundle);
4104               }
4105             }
4106             DepDest = DepDest->NextLoadStore;
4107 
4108             // Example, explaining the loop break condition: Let's assume our
4109             // starting instruction is i0 and MaxMemDepDistance = 3.
4110             //
4111             //                      +--------v--v--v
4112             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
4113             //             +--------^--^--^
4114             //
4115             // MaxMemDepDistance let us stop alias-checking at i3 and we add
4116             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
4117             // Previously we already added dependencies from i3 to i6,i7,i8
4118             // (because of MaxMemDepDistance). As we added a dependency from
4119             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
4120             // and we can abort this loop at i6.
4121             if (DistToSrc >= 2 * MaxMemDepDistance)
4122               break;
4123             DistToSrc++;
4124           }
4125         }
4126       }
4127       BundleMember = BundleMember->NextInBundle;
4128     }
4129     if (InsertInReadyList && SD->isReady()) {
4130       ReadyInsts.push_back(SD);
4131       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
4132                         << "\n");
4133     }
4134   }
4135 }
4136 
4137 void BoUpSLP::BlockScheduling::resetSchedule() {
4138   assert(ScheduleStart &&
4139          "tried to reset schedule on block which has not been scheduled");
4140   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
4141     doForAllOpcodes(I, [&](ScheduleData *SD) {
4142       assert(isInSchedulingRegion(SD) &&
4143              "ScheduleData not in scheduling region");
4144       SD->IsScheduled = false;
4145       SD->resetUnscheduledDeps();
4146     });
4147   }
4148   ReadyInsts.clear();
4149 }
4150 
4151 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
4152   if (!BS->ScheduleStart)
4153     return;
4154 
4155   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
4156 
4157   BS->resetSchedule();
4158 
4159   // For the real scheduling we use a more sophisticated ready-list: it is
4160   // sorted by the original instruction location. This lets the final schedule
4161   // be as  close as possible to the original instruction order.
4162   struct ScheduleDataCompare {
4163     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
4164       return SD2->SchedulingPriority < SD1->SchedulingPriority;
4165     }
4166   };
4167   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
4168 
4169   // Ensure that all dependency data is updated and fill the ready-list with
4170   // initial instructions.
4171   int Idx = 0;
4172   int NumToSchedule = 0;
4173   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
4174        I = I->getNextNode()) {
4175     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
4176       assert(SD->isPartOfBundle() ==
4177                  (getTreeEntry(SD->Inst) != nullptr) &&
4178              "scheduler and vectorizer bundle mismatch");
4179       SD->FirstInBundle->SchedulingPriority = Idx++;
4180       if (SD->isSchedulingEntity()) {
4181         BS->calculateDependencies(SD, false, this);
4182         NumToSchedule++;
4183       }
4184     });
4185   }
4186   BS->initialFillReadyList(ReadyInsts);
4187 
4188   Instruction *LastScheduledInst = BS->ScheduleEnd;
4189 
4190   // Do the "real" scheduling.
4191   while (!ReadyInsts.empty()) {
4192     ScheduleData *picked = *ReadyInsts.begin();
4193     ReadyInsts.erase(ReadyInsts.begin());
4194 
4195     // Move the scheduled instruction(s) to their dedicated places, if not
4196     // there yet.
4197     ScheduleData *BundleMember = picked;
4198     while (BundleMember) {
4199       Instruction *pickedInst = BundleMember->Inst;
4200       if (LastScheduledInst->getNextNode() != pickedInst) {
4201         BS->BB->getInstList().remove(pickedInst);
4202         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
4203                                      pickedInst);
4204       }
4205       LastScheduledInst = pickedInst;
4206       BundleMember = BundleMember->NextInBundle;
4207     }
4208 
4209     BS->schedule(picked, ReadyInsts);
4210     NumToSchedule--;
4211   }
4212   assert(NumToSchedule == 0 && "could not schedule all instructions");
4213 
4214   // Avoid duplicate scheduling of the block.
4215   BS->ScheduleStart = nullptr;
4216 }
4217 
4218 unsigned BoUpSLP::getVectorElementSize(Value *V) {
4219   // If V is a store, just return the width of the stored value without
4220   // traversing the expression tree. This is the common case.
4221   if (auto *Store = dyn_cast<StoreInst>(V))
4222     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
4223 
4224   // If V is not a store, we can traverse the expression tree to find loads
4225   // that feed it. The type of the loaded value may indicate a more suitable
4226   // width than V's type. We want to base the vector element size on the width
4227   // of memory operations where possible.
4228   SmallVector<Instruction *, 16> Worklist;
4229   SmallPtrSet<Instruction *, 16> Visited;
4230   if (auto *I = dyn_cast<Instruction>(V))
4231     Worklist.push_back(I);
4232 
4233   // Traverse the expression tree in bottom-up order looking for loads. If we
4234   // encounter an instruciton we don't yet handle, we give up.
4235   auto MaxWidth = 0u;
4236   auto FoundUnknownInst = false;
4237   while (!Worklist.empty() && !FoundUnknownInst) {
4238     auto *I = Worklist.pop_back_val();
4239     Visited.insert(I);
4240 
4241     // We should only be looking at scalar instructions here. If the current
4242     // instruction has a vector type, give up.
4243     auto *Ty = I->getType();
4244     if (isa<VectorType>(Ty))
4245       FoundUnknownInst = true;
4246 
4247     // If the current instruction is a load, update MaxWidth to reflect the
4248     // width of the loaded value.
4249     else if (isa<LoadInst>(I))
4250       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
4251 
4252     // Otherwise, we need to visit the operands of the instruction. We only
4253     // handle the interesting cases from buildTree here. If an operand is an
4254     // instruction we haven't yet visited, we add it to the worklist.
4255     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
4256              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
4257       for (Use &U : I->operands())
4258         if (auto *J = dyn_cast<Instruction>(U.get()))
4259           if (!Visited.count(J))
4260             Worklist.push_back(J);
4261     }
4262 
4263     // If we don't yet handle the instruction, give up.
4264     else
4265       FoundUnknownInst = true;
4266   }
4267 
4268   // If we didn't encounter a memory access in the expression tree, or if we
4269   // gave up for some reason, just return the width of V.
4270   if (!MaxWidth || FoundUnknownInst)
4271     return DL->getTypeSizeInBits(V->getType());
4272 
4273   // Otherwise, return the maximum width we found.
4274   return MaxWidth;
4275 }
4276 
4277 // Determine if a value V in a vectorizable expression Expr can be demoted to a
4278 // smaller type with a truncation. We collect the values that will be demoted
4279 // in ToDemote and additional roots that require investigating in Roots.
4280 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
4281                                   SmallVectorImpl<Value *> &ToDemote,
4282                                   SmallVectorImpl<Value *> &Roots) {
4283   // We can always demote constants.
4284   if (isa<Constant>(V)) {
4285     ToDemote.push_back(V);
4286     return true;
4287   }
4288 
4289   // If the value is not an instruction in the expression with only one use, it
4290   // cannot be demoted.
4291   auto *I = dyn_cast<Instruction>(V);
4292   if (!I || !I->hasOneUse() || !Expr.count(I))
4293     return false;
4294 
4295   switch (I->getOpcode()) {
4296 
4297   // We can always demote truncations and extensions. Since truncations can
4298   // seed additional demotion, we save the truncated value.
4299   case Instruction::Trunc:
4300     Roots.push_back(I->getOperand(0));
4301     break;
4302   case Instruction::ZExt:
4303   case Instruction::SExt:
4304     break;
4305 
4306   // We can demote certain binary operations if we can demote both of their
4307   // operands.
4308   case Instruction::Add:
4309   case Instruction::Sub:
4310   case Instruction::Mul:
4311   case Instruction::And:
4312   case Instruction::Or:
4313   case Instruction::Xor:
4314     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
4315         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
4316       return false;
4317     break;
4318 
4319   // We can demote selects if we can demote their true and false values.
4320   case Instruction::Select: {
4321     SelectInst *SI = cast<SelectInst>(I);
4322     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
4323         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
4324       return false;
4325     break;
4326   }
4327 
4328   // We can demote phis if we can demote all their incoming operands. Note that
4329   // we don't need to worry about cycles since we ensure single use above.
4330   case Instruction::PHI: {
4331     PHINode *PN = cast<PHINode>(I);
4332     for (Value *IncValue : PN->incoming_values())
4333       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
4334         return false;
4335     break;
4336   }
4337 
4338   // Otherwise, conservatively give up.
4339   default:
4340     return false;
4341   }
4342 
4343   // Record the value that we can demote.
4344   ToDemote.push_back(V);
4345   return true;
4346 }
4347 
4348 void BoUpSLP::computeMinimumValueSizes() {
4349   // If there are no external uses, the expression tree must be rooted by a
4350   // store. We can't demote in-memory values, so there is nothing to do here.
4351   if (ExternalUses.empty())
4352     return;
4353 
4354   // We only attempt to truncate integer expressions.
4355   auto &TreeRoot = VectorizableTree[0].Scalars;
4356   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
4357   if (!TreeRootIT)
4358     return;
4359 
4360   // If the expression is not rooted by a store, these roots should have
4361   // external uses. We will rely on InstCombine to rewrite the expression in
4362   // the narrower type. However, InstCombine only rewrites single-use values.
4363   // This means that if a tree entry other than a root is used externally, it
4364   // must have multiple uses and InstCombine will not rewrite it. The code
4365   // below ensures that only the roots are used externally.
4366   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
4367   for (auto &EU : ExternalUses)
4368     if (!Expr.erase(EU.Scalar))
4369       return;
4370   if (!Expr.empty())
4371     return;
4372 
4373   // Collect the scalar values of the vectorizable expression. We will use this
4374   // context to determine which values can be demoted. If we see a truncation,
4375   // we mark it as seeding another demotion.
4376   for (auto &Entry : VectorizableTree)
4377     Expr.insert(Entry.Scalars.begin(), Entry.Scalars.end());
4378 
4379   // Ensure the roots of the vectorizable tree don't form a cycle. They must
4380   // have a single external user that is not in the vectorizable tree.
4381   for (auto *Root : TreeRoot)
4382     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
4383       return;
4384 
4385   // Conservatively determine if we can actually truncate the roots of the
4386   // expression. Collect the values that can be demoted in ToDemote and
4387   // additional roots that require investigating in Roots.
4388   SmallVector<Value *, 32> ToDemote;
4389   SmallVector<Value *, 4> Roots;
4390   for (auto *Root : TreeRoot)
4391     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
4392       return;
4393 
4394   // The maximum bit width required to represent all the values that can be
4395   // demoted without loss of precision. It would be safe to truncate the roots
4396   // of the expression to this width.
4397   auto MaxBitWidth = 8u;
4398 
4399   // We first check if all the bits of the roots are demanded. If they're not,
4400   // we can truncate the roots to this narrower type.
4401   for (auto *Root : TreeRoot) {
4402     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
4403     MaxBitWidth = std::max<unsigned>(
4404         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
4405   }
4406 
4407   // True if the roots can be zero-extended back to their original type, rather
4408   // than sign-extended. We know that if the leading bits are not demanded, we
4409   // can safely zero-extend. So we initialize IsKnownPositive to True.
4410   bool IsKnownPositive = true;
4411 
4412   // If all the bits of the roots are demanded, we can try a little harder to
4413   // compute a narrower type. This can happen, for example, if the roots are
4414   // getelementptr indices. InstCombine promotes these indices to the pointer
4415   // width. Thus, all their bits are technically demanded even though the
4416   // address computation might be vectorized in a smaller type.
4417   //
4418   // We start by looking at each entry that can be demoted. We compute the
4419   // maximum bit width required to store the scalar by using ValueTracking to
4420   // compute the number of high-order bits we can truncate.
4421   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
4422       llvm::all_of(TreeRoot, [](Value *R) {
4423         assert(R->hasOneUse() && "Root should have only one use!");
4424         return isa<GetElementPtrInst>(R->user_back());
4425       })) {
4426     MaxBitWidth = 8u;
4427 
4428     // Determine if the sign bit of all the roots is known to be zero. If not,
4429     // IsKnownPositive is set to False.
4430     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
4431       KnownBits Known = computeKnownBits(R, *DL);
4432       return Known.isNonNegative();
4433     });
4434 
4435     // Determine the maximum number of bits required to store the scalar
4436     // values.
4437     for (auto *Scalar : ToDemote) {
4438       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
4439       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
4440       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
4441     }
4442 
4443     // If we can't prove that the sign bit is zero, we must add one to the
4444     // maximum bit width to account for the unknown sign bit. This preserves
4445     // the existing sign bit so we can safely sign-extend the root back to the
4446     // original type. Otherwise, if we know the sign bit is zero, we will
4447     // zero-extend the root instead.
4448     //
4449     // FIXME: This is somewhat suboptimal, as there will be cases where adding
4450     //        one to the maximum bit width will yield a larger-than-necessary
4451     //        type. In general, we need to add an extra bit only if we can't
4452     //        prove that the upper bit of the original type is equal to the
4453     //        upper bit of the proposed smaller type. If these two bits are the
4454     //        same (either zero or one) we know that sign-extending from the
4455     //        smaller type will result in the same value. Here, since we can't
4456     //        yet prove this, we are just making the proposed smaller type
4457     //        larger to ensure correctness.
4458     if (!IsKnownPositive)
4459       ++MaxBitWidth;
4460   }
4461 
4462   // Round MaxBitWidth up to the next power-of-two.
4463   if (!isPowerOf2_64(MaxBitWidth))
4464     MaxBitWidth = NextPowerOf2(MaxBitWidth);
4465 
4466   // If the maximum bit width we compute is less than the with of the roots'
4467   // type, we can proceed with the narrowing. Otherwise, do nothing.
4468   if (MaxBitWidth >= TreeRootIT->getBitWidth())
4469     return;
4470 
4471   // If we can truncate the root, we must collect additional values that might
4472   // be demoted as a result. That is, those seeded by truncations we will
4473   // modify.
4474   while (!Roots.empty())
4475     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
4476 
4477   // Finally, map the values we can demote to the maximum bit with we computed.
4478   for (auto *Scalar : ToDemote)
4479     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
4480 }
4481 
4482 namespace {
4483 
4484 /// The SLPVectorizer Pass.
4485 struct SLPVectorizer : public FunctionPass {
4486   SLPVectorizerPass Impl;
4487 
4488   /// Pass identification, replacement for typeid
4489   static char ID;
4490 
4491   explicit SLPVectorizer() : FunctionPass(ID) {
4492     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
4493   }
4494 
4495   bool doInitialization(Module &M) override {
4496     return false;
4497   }
4498 
4499   bool runOnFunction(Function &F) override {
4500     if (skipFunction(F))
4501       return false;
4502 
4503     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
4504     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
4505     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
4506     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
4507     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
4508     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
4509     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
4510     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
4511     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
4512     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
4513 
4514     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4515   }
4516 
4517   void getAnalysisUsage(AnalysisUsage &AU) const override {
4518     FunctionPass::getAnalysisUsage(AU);
4519     AU.addRequired<AssumptionCacheTracker>();
4520     AU.addRequired<ScalarEvolutionWrapperPass>();
4521     AU.addRequired<AAResultsWrapperPass>();
4522     AU.addRequired<TargetTransformInfoWrapperPass>();
4523     AU.addRequired<LoopInfoWrapperPass>();
4524     AU.addRequired<DominatorTreeWrapperPass>();
4525     AU.addRequired<DemandedBitsWrapperPass>();
4526     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
4527     AU.addPreserved<LoopInfoWrapperPass>();
4528     AU.addPreserved<DominatorTreeWrapperPass>();
4529     AU.addPreserved<AAResultsWrapperPass>();
4530     AU.addPreserved<GlobalsAAWrapperPass>();
4531     AU.setPreservesCFG();
4532   }
4533 };
4534 
4535 } // end anonymous namespace
4536 
4537 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
4538   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
4539   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
4540   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
4541   auto *AA = &AM.getResult<AAManager>(F);
4542   auto *LI = &AM.getResult<LoopAnalysis>(F);
4543   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
4544   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
4545   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
4546   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
4547 
4548   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
4549   if (!Changed)
4550     return PreservedAnalyses::all();
4551 
4552   PreservedAnalyses PA;
4553   PA.preserveSet<CFGAnalyses>();
4554   PA.preserve<AAManager>();
4555   PA.preserve<GlobalsAA>();
4556   return PA;
4557 }
4558 
4559 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
4560                                 TargetTransformInfo *TTI_,
4561                                 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
4562                                 LoopInfo *LI_, DominatorTree *DT_,
4563                                 AssumptionCache *AC_, DemandedBits *DB_,
4564                                 OptimizationRemarkEmitter *ORE_) {
4565   SE = SE_;
4566   TTI = TTI_;
4567   TLI = TLI_;
4568   AA = AA_;
4569   LI = LI_;
4570   DT = DT_;
4571   AC = AC_;
4572   DB = DB_;
4573   DL = &F.getParent()->getDataLayout();
4574 
4575   Stores.clear();
4576   GEPs.clear();
4577   bool Changed = false;
4578 
4579   // If the target claims to have no vector registers don't attempt
4580   // vectorization.
4581   if (!TTI->getNumberOfRegisters(true))
4582     return false;
4583 
4584   // Don't vectorize when the attribute NoImplicitFloat is used.
4585   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
4586     return false;
4587 
4588   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
4589 
4590   // Use the bottom up slp vectorizer to construct chains that start with
4591   // store instructions.
4592   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
4593 
4594   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
4595   // delete instructions.
4596 
4597   // Scan the blocks in the function in post order.
4598   for (auto BB : post_order(&F.getEntryBlock())) {
4599     collectSeedInstructions(BB);
4600 
4601     // Vectorize trees that end at stores.
4602     if (!Stores.empty()) {
4603       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
4604                         << " underlying objects.\n");
4605       Changed |= vectorizeStoreChains(R);
4606     }
4607 
4608     // Vectorize trees that end at reductions.
4609     Changed |= vectorizeChainsInBlock(BB, R);
4610 
4611     // Vectorize the index computations of getelementptr instructions. This
4612     // is primarily intended to catch gather-like idioms ending at
4613     // non-consecutive loads.
4614     if (!GEPs.empty()) {
4615       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
4616                         << " underlying objects.\n");
4617       Changed |= vectorizeGEPIndices(BB, R);
4618     }
4619   }
4620 
4621   if (Changed) {
4622     R.optimizeGatherSequence();
4623     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
4624     LLVM_DEBUG(verifyFunction(F));
4625   }
4626   return Changed;
4627 }
4628 
4629 /// Check that the Values in the slice in VL array are still existent in
4630 /// the WeakTrackingVH array.
4631 /// Vectorization of part of the VL array may cause later values in the VL array
4632 /// to become invalid. We track when this has happened in the WeakTrackingVH
4633 /// array.
4634 static bool hasValueBeenRAUWed(ArrayRef<Value *> VL,
4635                                ArrayRef<WeakTrackingVH> VH, unsigned SliceBegin,
4636                                unsigned SliceSize) {
4637   VL = VL.slice(SliceBegin, SliceSize);
4638   VH = VH.slice(SliceBegin, SliceSize);
4639   return !std::equal(VL.begin(), VL.end(), VH.begin());
4640 }
4641 
4642 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
4643                                             unsigned VecRegSize) {
4644   const unsigned ChainLen = Chain.size();
4645   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
4646                     << "\n");
4647   const unsigned Sz = R.getVectorElementSize(Chain[0]);
4648   const unsigned VF = VecRegSize / Sz;
4649 
4650   if (!isPowerOf2_32(Sz) || VF < 2)
4651     return false;
4652 
4653   // Keep track of values that were deleted by vectorizing in the loop below.
4654   const SmallVector<WeakTrackingVH, 8> TrackValues(Chain.begin(), Chain.end());
4655 
4656   bool Changed = false;
4657   // Look for profitable vectorizable trees at all offsets, starting at zero.
4658   for (unsigned i = 0, e = ChainLen; i + VF <= e; ++i) {
4659 
4660     // Check that a previous iteration of this loop did not delete the Value.
4661     if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
4662       continue;
4663 
4664     LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
4665                       << "\n");
4666     ArrayRef<Value *> Operands = Chain.slice(i, VF);
4667 
4668     R.buildTree(Operands);
4669     if (R.isTreeTinyAndNotFullyVectorizable())
4670       continue;
4671 
4672     R.computeMinimumValueSizes();
4673 
4674     int Cost = R.getTreeCost();
4675 
4676     LLVM_DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF
4677                       << "\n");
4678     if (Cost < -SLPCostThreshold) {
4679       LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
4680 
4681       using namespace ore;
4682 
4683       R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
4684                                           cast<StoreInst>(Chain[i]))
4685                        << "Stores SLP vectorized with cost " << NV("Cost", Cost)
4686                        << " and with tree size "
4687                        << NV("TreeSize", R.getTreeSize()));
4688 
4689       R.vectorizeTree();
4690 
4691       // Move to the next bundle.
4692       i += VF - 1;
4693       Changed = true;
4694     }
4695   }
4696 
4697   return Changed;
4698 }
4699 
4700 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
4701                                         BoUpSLP &R) {
4702   SetVector<StoreInst *> Heads;
4703   SmallDenseSet<StoreInst *> Tails;
4704   SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
4705 
4706   // We may run into multiple chains that merge into a single chain. We mark the
4707   // stores that we vectorized so that we don't visit the same store twice.
4708   BoUpSLP::ValueSet VectorizedStores;
4709   bool Changed = false;
4710 
4711   // Do a quadratic search on all of the given stores in reverse order and find
4712   // all of the pairs of stores that follow each other.
4713   SmallVector<unsigned, 16> IndexQueue;
4714   unsigned E = Stores.size();
4715   IndexQueue.resize(E - 1);
4716   for (unsigned I = E; I > 0; --I) {
4717     unsigned Idx = I - 1;
4718     // If a store has multiple consecutive store candidates, search Stores
4719     // array according to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
4720     // This is because usually pairing with immediate succeeding or preceding
4721     // candidate create the best chance to find slp vectorization opportunity.
4722     unsigned Offset = 1;
4723     unsigned Cnt = 0;
4724     for (unsigned J = 0; J < E - 1; ++J, ++Offset) {
4725       if (Idx >= Offset) {
4726         IndexQueue[Cnt] = Idx - Offset;
4727         ++Cnt;
4728       }
4729       if (Idx + Offset < E) {
4730         IndexQueue[Cnt] = Idx + Offset;
4731         ++Cnt;
4732       }
4733     }
4734 
4735     for (auto K : IndexQueue) {
4736       if (isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE)) {
4737         Tails.insert(Stores[Idx]);
4738         Heads.insert(Stores[K]);
4739         ConsecutiveChain[Stores[K]] = Stores[Idx];
4740         break;
4741       }
4742     }
4743   }
4744 
4745   // For stores that start but don't end a link in the chain:
4746   for (auto *SI : llvm::reverse(Heads)) {
4747     if (Tails.count(SI))
4748       continue;
4749 
4750     // We found a store instr that starts a chain. Now follow the chain and try
4751     // to vectorize it.
4752     BoUpSLP::ValueList Operands;
4753     StoreInst *I = SI;
4754     // Collect the chain into a list.
4755     while ((Tails.count(I) || Heads.count(I)) && !VectorizedStores.count(I)) {
4756       Operands.push_back(I);
4757       // Move to the next value in the chain.
4758       I = ConsecutiveChain[I];
4759     }
4760 
4761     // FIXME: Is division-by-2 the correct step? Should we assert that the
4762     // register size is a power-of-2?
4763     for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
4764          Size /= 2) {
4765       if (vectorizeStoreChain(Operands, R, Size)) {
4766         // Mark the vectorized stores so that we don't vectorize them again.
4767         VectorizedStores.insert(Operands.begin(), Operands.end());
4768         Changed = true;
4769         break;
4770       }
4771     }
4772   }
4773 
4774   return Changed;
4775 }
4776 
4777 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
4778   // Initialize the collections. We will make a single pass over the block.
4779   Stores.clear();
4780   GEPs.clear();
4781 
4782   // Visit the store and getelementptr instructions in BB and organize them in
4783   // Stores and GEPs according to the underlying objects of their pointer
4784   // operands.
4785   for (Instruction &I : *BB) {
4786     // Ignore store instructions that are volatile or have a pointer operand
4787     // that doesn't point to a scalar type.
4788     if (auto *SI = dyn_cast<StoreInst>(&I)) {
4789       if (!SI->isSimple())
4790         continue;
4791       if (!isValidElementType(SI->getValueOperand()->getType()))
4792         continue;
4793       Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
4794     }
4795 
4796     // Ignore getelementptr instructions that have more than one index, a
4797     // constant index, or a pointer operand that doesn't point to a scalar
4798     // type.
4799     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
4800       auto Idx = GEP->idx_begin()->get();
4801       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
4802         continue;
4803       if (!isValidElementType(Idx->getType()))
4804         continue;
4805       if (GEP->getType()->isVectorTy())
4806         continue;
4807       GEPs[GetUnderlyingObject(GEP->getPointerOperand(), *DL)].push_back(GEP);
4808     }
4809   }
4810 }
4811 
4812 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
4813   if (!A || !B)
4814     return false;
4815   Value *VL[] = { A, B };
4816   return tryToVectorizeList(VL, R, /*UserCost=*/0, true);
4817 }
4818 
4819 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
4820                                            int UserCost, bool AllowReorder) {
4821   if (VL.size() < 2)
4822     return false;
4823 
4824   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
4825                     << VL.size() << ".\n");
4826 
4827   // Check that all of the parts are scalar instructions of the same type,
4828   // we permit an alternate opcode via InstructionsState.
4829   InstructionsState S = getSameOpcode(VL);
4830   if (!S.Opcode)
4831     return false;
4832 
4833   Instruction *I0 = cast<Instruction>(S.OpValue);
4834   unsigned Sz = R.getVectorElementSize(I0);
4835   unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
4836   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
4837   if (MaxVF < 2) {
4838      R.getORE()->emit([&]() {
4839          return OptimizationRemarkMissed(
4840                     SV_NAME, "SmallVF", I0)
4841                 << "Cannot SLP vectorize list: vectorization factor "
4842                 << "less than 2 is not supported";
4843      });
4844      return false;
4845   }
4846 
4847   for (Value *V : VL) {
4848     Type *Ty = V->getType();
4849     if (!isValidElementType(Ty)) {
4850       // NOTE: the following will give user internal llvm type name, which may
4851       // not be useful.
4852       R.getORE()->emit([&]() {
4853         std::string type_str;
4854         llvm::raw_string_ostream rso(type_str);
4855         Ty->print(rso);
4856         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
4857                << "Cannot SLP vectorize list: type "
4858                << rso.str() + " is unsupported by vectorizer";
4859       });
4860       return false;
4861     }
4862   }
4863 
4864   bool Changed = false;
4865   bool CandidateFound = false;
4866   int MinCost = SLPCostThreshold;
4867 
4868   // Keep track of values that were deleted by vectorizing in the loop below.
4869   SmallVector<WeakTrackingVH, 8> TrackValues(VL.begin(), VL.end());
4870 
4871   unsigned NextInst = 0, MaxInst = VL.size();
4872   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
4873        VF /= 2) {
4874     // No actual vectorization should happen, if number of parts is the same as
4875     // provided vectorization factor (i.e. the scalar type is used for vector
4876     // code during codegen).
4877     auto *VecTy = VectorType::get(VL[0]->getType(), VF);
4878     if (TTI->getNumberOfParts(VecTy) == VF)
4879       continue;
4880     for (unsigned I = NextInst; I < MaxInst; ++I) {
4881       unsigned OpsWidth = 0;
4882 
4883       if (I + VF > MaxInst)
4884         OpsWidth = MaxInst - I;
4885       else
4886         OpsWidth = VF;
4887 
4888       if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
4889         break;
4890 
4891       // Check that a previous iteration of this loop did not delete the Value.
4892       if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
4893         continue;
4894 
4895       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
4896                         << "\n");
4897       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
4898 
4899       R.buildTree(Ops);
4900       Optional<ArrayRef<unsigned>> Order = R.bestOrder();
4901       // TODO: check if we can allow reordering for more cases.
4902       if (AllowReorder && Order) {
4903         // TODO: reorder tree nodes without tree rebuilding.
4904         // Conceptually, there is nothing actually preventing us from trying to
4905         // reorder a larger list. In fact, we do exactly this when vectorizing
4906         // reductions. However, at this point, we only expect to get here when
4907         // there are exactly two operations.
4908         assert(Ops.size() == 2);
4909         Value *ReorderedOps[] = {Ops[1], Ops[0]};
4910         R.buildTree(ReorderedOps, None);
4911       }
4912       if (R.isTreeTinyAndNotFullyVectorizable())
4913         continue;
4914 
4915       R.computeMinimumValueSizes();
4916       int Cost = R.getTreeCost() - UserCost;
4917       CandidateFound = true;
4918       MinCost = std::min(MinCost, Cost);
4919 
4920       if (Cost < -SLPCostThreshold) {
4921         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
4922         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
4923                                                     cast<Instruction>(Ops[0]))
4924                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
4925                                  << " and with tree size "
4926                                  << ore::NV("TreeSize", R.getTreeSize()));
4927 
4928         R.vectorizeTree();
4929         // Move to the next bundle.
4930         I += VF - 1;
4931         NextInst = I + 1;
4932         Changed = true;
4933       }
4934     }
4935   }
4936 
4937   if (!Changed && CandidateFound) {
4938     R.getORE()->emit([&]() {
4939         return OptimizationRemarkMissed(
4940                    SV_NAME, "NotBeneficial",  I0)
4941                << "List vectorization was possible but not beneficial with cost "
4942                << ore::NV("Cost", MinCost) << " >= "
4943                << ore::NV("Treshold", -SLPCostThreshold);
4944     });
4945   } else if (!Changed) {
4946     R.getORE()->emit([&]() {
4947         return OptimizationRemarkMissed(
4948                    SV_NAME, "NotPossible", I0)
4949                << "Cannot SLP vectorize list: vectorization was impossible"
4950                << " with available vectorization factors";
4951     });
4952   }
4953   return Changed;
4954 }
4955 
4956 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
4957   if (!I)
4958     return false;
4959 
4960   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
4961     return false;
4962 
4963   Value *P = I->getParent();
4964 
4965   // Vectorize in current basic block only.
4966   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
4967   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
4968   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
4969     return false;
4970 
4971   // Try to vectorize V.
4972   if (tryToVectorizePair(Op0, Op1, R))
4973     return true;
4974 
4975   auto *A = dyn_cast<BinaryOperator>(Op0);
4976   auto *B = dyn_cast<BinaryOperator>(Op1);
4977   // Try to skip B.
4978   if (B && B->hasOneUse()) {
4979     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
4980     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
4981     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
4982       return true;
4983     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
4984       return true;
4985   }
4986 
4987   // Try to skip A.
4988   if (A && A->hasOneUse()) {
4989     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
4990     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
4991     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
4992       return true;
4993     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
4994       return true;
4995   }
4996   return false;
4997 }
4998 
4999 /// Generate a shuffle mask to be used in a reduction tree.
5000 ///
5001 /// \param VecLen The length of the vector to be reduced.
5002 /// \param NumEltsToRdx The number of elements that should be reduced in the
5003 ///        vector.
5004 /// \param IsPairwise Whether the reduction is a pairwise or splitting
5005 ///        reduction. A pairwise reduction will generate a mask of
5006 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
5007 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
5008 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
5009 static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
5010                                    bool IsPairwise, bool IsLeft,
5011                                    IRBuilder<> &Builder) {
5012   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
5013 
5014   SmallVector<Constant *, 32> ShuffleMask(
5015       VecLen, UndefValue::get(Builder.getInt32Ty()));
5016 
5017   if (IsPairwise)
5018     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
5019     for (unsigned i = 0; i != NumEltsToRdx; ++i)
5020       ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
5021   else
5022     // Move the upper half of the vector to the lower half.
5023     for (unsigned i = 0; i != NumEltsToRdx; ++i)
5024       ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
5025 
5026   return ConstantVector::get(ShuffleMask);
5027 }
5028 
5029 namespace {
5030 
5031 /// Model horizontal reductions.
5032 ///
5033 /// A horizontal reduction is a tree of reduction operations (currently add and
5034 /// fadd) that has operations that can be put into a vector as its leaf.
5035 /// For example, this tree:
5036 ///
5037 /// mul mul mul mul
5038 ///  \  /    \  /
5039 ///   +       +
5040 ///    \     /
5041 ///       +
5042 /// This tree has "mul" as its reduced values and "+" as its reduction
5043 /// operations. A reduction might be feeding into a store or a binary operation
5044 /// feeding a phi.
5045 ///    ...
5046 ///    \  /
5047 ///     +
5048 ///     |
5049 ///  phi +=
5050 ///
5051 ///  Or:
5052 ///    ...
5053 ///    \  /
5054 ///     +
5055 ///     |
5056 ///   *p =
5057 ///
5058 class HorizontalReduction {
5059   using ReductionOpsType = SmallVector<Value *, 16>;
5060   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
5061   ReductionOpsListType  ReductionOps;
5062   SmallVector<Value *, 32> ReducedVals;
5063   // Use map vector to make stable output.
5064   MapVector<Instruction *, Value *> ExtraArgs;
5065 
5066   /// Kind of the reduction data.
5067   enum ReductionKind {
5068     RK_None,       /// Not a reduction.
5069     RK_Arithmetic, /// Binary reduction data.
5070     RK_Min,        /// Minimum reduction data.
5071     RK_UMin,       /// Unsigned minimum reduction data.
5072     RK_Max,        /// Maximum reduction data.
5073     RK_UMax,       /// Unsigned maximum reduction data.
5074   };
5075 
5076   /// Contains info about operation, like its opcode, left and right operands.
5077   class OperationData {
5078     /// Opcode of the instruction.
5079     unsigned Opcode = 0;
5080 
5081     /// Left operand of the reduction operation.
5082     Value *LHS = nullptr;
5083 
5084     /// Right operand of the reduction operation.
5085     Value *RHS = nullptr;
5086 
5087     /// Kind of the reduction operation.
5088     ReductionKind Kind = RK_None;
5089 
5090     /// True if float point min/max reduction has no NaNs.
5091     bool NoNaN = false;
5092 
5093     /// Checks if the reduction operation can be vectorized.
5094     bool isVectorizable() const {
5095       return LHS && RHS &&
5096              // We currently only support adds && min/max reductions.
5097              ((Kind == RK_Arithmetic &&
5098                (Opcode == Instruction::Add || Opcode == Instruction::FAdd)) ||
5099               ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
5100                (Kind == RK_Min || Kind == RK_Max)) ||
5101               (Opcode == Instruction::ICmp &&
5102                (Kind == RK_UMin || Kind == RK_UMax)));
5103     }
5104 
5105     /// Creates reduction operation with the current opcode.
5106     Value *createOp(IRBuilder<> &Builder, const Twine &Name) const {
5107       assert(isVectorizable() &&
5108              "Expected add|fadd or min/max reduction operation.");
5109       Value *Cmp;
5110       switch (Kind) {
5111       case RK_Arithmetic:
5112         return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
5113                                    Name);
5114       case RK_Min:
5115         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSLT(LHS, RHS)
5116                                           : Builder.CreateFCmpOLT(LHS, RHS);
5117         break;
5118       case RK_Max:
5119         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSGT(LHS, RHS)
5120                                           : Builder.CreateFCmpOGT(LHS, RHS);
5121         break;
5122       case RK_UMin:
5123         assert(Opcode == Instruction::ICmp && "Expected integer types.");
5124         Cmp = Builder.CreateICmpULT(LHS, RHS);
5125         break;
5126       case RK_UMax:
5127         assert(Opcode == Instruction::ICmp && "Expected integer types.");
5128         Cmp = Builder.CreateICmpUGT(LHS, RHS);
5129         break;
5130       case RK_None:
5131         llvm_unreachable("Unknown reduction operation.");
5132       }
5133       return Builder.CreateSelect(Cmp, LHS, RHS, Name);
5134     }
5135 
5136   public:
5137     explicit OperationData() = default;
5138 
5139     /// Construction for reduced values. They are identified by opcode only and
5140     /// don't have associated LHS/RHS values.
5141     explicit OperationData(Value *V) {
5142       if (auto *I = dyn_cast<Instruction>(V))
5143         Opcode = I->getOpcode();
5144     }
5145 
5146     /// Constructor for reduction operations with opcode and its left and
5147     /// right operands.
5148     OperationData(unsigned Opcode, Value *LHS, Value *RHS, ReductionKind Kind,
5149                   bool NoNaN = false)
5150         : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind), NoNaN(NoNaN) {
5151       assert(Kind != RK_None && "One of the reduction operations is expected.");
5152     }
5153 
5154     explicit operator bool() const { return Opcode; }
5155 
5156     /// Get the index of the first operand.
5157     unsigned getFirstOperandIndex() const {
5158       assert(!!*this && "The opcode is not set.");
5159       switch (Kind) {
5160       case RK_Min:
5161       case RK_UMin:
5162       case RK_Max:
5163       case RK_UMax:
5164         return 1;
5165       case RK_Arithmetic:
5166       case RK_None:
5167         break;
5168       }
5169       return 0;
5170     }
5171 
5172     /// Total number of operands in the reduction operation.
5173     unsigned getNumberOfOperands() const {
5174       assert(Kind != RK_None && !!*this && LHS && RHS &&
5175              "Expected reduction operation.");
5176       switch (Kind) {
5177       case RK_Arithmetic:
5178         return 2;
5179       case RK_Min:
5180       case RK_UMin:
5181       case RK_Max:
5182       case RK_UMax:
5183         return 3;
5184       case RK_None:
5185         break;
5186       }
5187       llvm_unreachable("Reduction kind is not set");
5188     }
5189 
5190     /// Checks if the operation has the same parent as \p P.
5191     bool hasSameParent(Instruction *I, Value *P, bool IsRedOp) const {
5192       assert(Kind != RK_None && !!*this && LHS && RHS &&
5193              "Expected reduction operation.");
5194       if (!IsRedOp)
5195         return I->getParent() == P;
5196       switch (Kind) {
5197       case RK_Arithmetic:
5198         // Arithmetic reduction operation must be used once only.
5199         return I->getParent() == P;
5200       case RK_Min:
5201       case RK_UMin:
5202       case RK_Max:
5203       case RK_UMax: {
5204         // SelectInst must be used twice while the condition op must have single
5205         // use only.
5206         auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition());
5207         return I->getParent() == P && Cmp && Cmp->getParent() == P;
5208       }
5209       case RK_None:
5210         break;
5211       }
5212       llvm_unreachable("Reduction kind is not set");
5213     }
5214     /// Expected number of uses for reduction operations/reduced values.
5215     bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const {
5216       assert(Kind != RK_None && !!*this && LHS && RHS &&
5217              "Expected reduction operation.");
5218       switch (Kind) {
5219       case RK_Arithmetic:
5220         return I->hasOneUse();
5221       case RK_Min:
5222       case RK_UMin:
5223       case RK_Max:
5224       case RK_UMax:
5225         return I->hasNUses(2) &&
5226                (!IsReductionOp ||
5227                 cast<SelectInst>(I)->getCondition()->hasOneUse());
5228       case RK_None:
5229         break;
5230       }
5231       llvm_unreachable("Reduction kind is not set");
5232     }
5233 
5234     /// Initializes the list of reduction operations.
5235     void initReductionOps(ReductionOpsListType &ReductionOps) {
5236       assert(Kind != RK_None && !!*this && LHS && RHS &&
5237              "Expected reduction operation.");
5238       switch (Kind) {
5239       case RK_Arithmetic:
5240         ReductionOps.assign(1, ReductionOpsType());
5241         break;
5242       case RK_Min:
5243       case RK_UMin:
5244       case RK_Max:
5245       case RK_UMax:
5246         ReductionOps.assign(2, ReductionOpsType());
5247         break;
5248       case RK_None:
5249         llvm_unreachable("Reduction kind is not set");
5250       }
5251     }
5252     /// Add all reduction operations for the reduction instruction \p I.
5253     void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) {
5254       assert(Kind != RK_None && !!*this && LHS && RHS &&
5255              "Expected reduction operation.");
5256       switch (Kind) {
5257       case RK_Arithmetic:
5258         ReductionOps[0].emplace_back(I);
5259         break;
5260       case RK_Min:
5261       case RK_UMin:
5262       case RK_Max:
5263       case RK_UMax:
5264         ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
5265         ReductionOps[1].emplace_back(I);
5266         break;
5267       case RK_None:
5268         llvm_unreachable("Reduction kind is not set");
5269       }
5270     }
5271 
5272     /// Checks if instruction is associative and can be vectorized.
5273     bool isAssociative(Instruction *I) const {
5274       assert(Kind != RK_None && *this && LHS && RHS &&
5275              "Expected reduction operation.");
5276       switch (Kind) {
5277       case RK_Arithmetic:
5278         return I->isAssociative();
5279       case RK_Min:
5280       case RK_Max:
5281         return Opcode == Instruction::ICmp ||
5282                cast<Instruction>(I->getOperand(0))->isFast();
5283       case RK_UMin:
5284       case RK_UMax:
5285         assert(Opcode == Instruction::ICmp &&
5286                "Only integer compare operation is expected.");
5287         return true;
5288       case RK_None:
5289         break;
5290       }
5291       llvm_unreachable("Reduction kind is not set");
5292     }
5293 
5294     /// Checks if the reduction operation can be vectorized.
5295     bool isVectorizable(Instruction *I) const {
5296       return isVectorizable() && isAssociative(I);
5297     }
5298 
5299     /// Checks if two operation data are both a reduction op or both a reduced
5300     /// value.
5301     bool operator==(const OperationData &OD) {
5302       assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&
5303              "One of the comparing operations is incorrect.");
5304       return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
5305     }
5306     bool operator!=(const OperationData &OD) { return !(*this == OD); }
5307     void clear() {
5308       Opcode = 0;
5309       LHS = nullptr;
5310       RHS = nullptr;
5311       Kind = RK_None;
5312       NoNaN = false;
5313     }
5314 
5315     /// Get the opcode of the reduction operation.
5316     unsigned getOpcode() const {
5317       assert(isVectorizable() && "Expected vectorizable operation.");
5318       return Opcode;
5319     }
5320 
5321     /// Get kind of reduction data.
5322     ReductionKind getKind() const { return Kind; }
5323     Value *getLHS() const { return LHS; }
5324     Value *getRHS() const { return RHS; }
5325     Type *getConditionType() const {
5326       switch (Kind) {
5327       case RK_Arithmetic:
5328         return nullptr;
5329       case RK_Min:
5330       case RK_Max:
5331       case RK_UMin:
5332       case RK_UMax:
5333         return CmpInst::makeCmpResultType(LHS->getType());
5334       case RK_None:
5335         break;
5336       }
5337       llvm_unreachable("Reduction kind is not set");
5338     }
5339 
5340     /// Creates reduction operation with the current opcode with the IR flags
5341     /// from \p ReductionOps.
5342     Value *createOp(IRBuilder<> &Builder, const Twine &Name,
5343                     const ReductionOpsListType &ReductionOps) const {
5344       assert(isVectorizable() &&
5345              "Expected add|fadd or min/max reduction operation.");
5346       auto *Op = createOp(Builder, Name);
5347       switch (Kind) {
5348       case RK_Arithmetic:
5349         propagateIRFlags(Op, ReductionOps[0]);
5350         return Op;
5351       case RK_Min:
5352       case RK_Max:
5353       case RK_UMin:
5354       case RK_UMax:
5355         if (auto *SI = dyn_cast<SelectInst>(Op))
5356           propagateIRFlags(SI->getCondition(), ReductionOps[0]);
5357         propagateIRFlags(Op, ReductionOps[1]);
5358         return Op;
5359       case RK_None:
5360         break;
5361       }
5362       llvm_unreachable("Unknown reduction operation.");
5363     }
5364     /// Creates reduction operation with the current opcode with the IR flags
5365     /// from \p I.
5366     Value *createOp(IRBuilder<> &Builder, const Twine &Name,
5367                     Instruction *I) const {
5368       assert(isVectorizable() &&
5369              "Expected add|fadd or min/max reduction operation.");
5370       auto *Op = createOp(Builder, Name);
5371       switch (Kind) {
5372       case RK_Arithmetic:
5373         propagateIRFlags(Op, I);
5374         return Op;
5375       case RK_Min:
5376       case RK_Max:
5377       case RK_UMin:
5378       case RK_UMax:
5379         if (auto *SI = dyn_cast<SelectInst>(Op)) {
5380           propagateIRFlags(SI->getCondition(),
5381                            cast<SelectInst>(I)->getCondition());
5382         }
5383         propagateIRFlags(Op, I);
5384         return Op;
5385       case RK_None:
5386         break;
5387       }
5388       llvm_unreachable("Unknown reduction operation.");
5389     }
5390 
5391     TargetTransformInfo::ReductionFlags getFlags() const {
5392       TargetTransformInfo::ReductionFlags Flags;
5393       Flags.NoNaN = NoNaN;
5394       switch (Kind) {
5395       case RK_Arithmetic:
5396         break;
5397       case RK_Min:
5398         Flags.IsSigned = Opcode == Instruction::ICmp;
5399         Flags.IsMaxOp = false;
5400         break;
5401       case RK_Max:
5402         Flags.IsSigned = Opcode == Instruction::ICmp;
5403         Flags.IsMaxOp = true;
5404         break;
5405       case RK_UMin:
5406         Flags.IsSigned = false;
5407         Flags.IsMaxOp = false;
5408         break;
5409       case RK_UMax:
5410         Flags.IsSigned = false;
5411         Flags.IsMaxOp = true;
5412         break;
5413       case RK_None:
5414         llvm_unreachable("Reduction kind is not set");
5415       }
5416       return Flags;
5417     }
5418   };
5419 
5420   Instruction *ReductionRoot = nullptr;
5421 
5422   /// The operation data of the reduction operation.
5423   OperationData ReductionData;
5424 
5425   /// The operation data of the values we perform a reduction on.
5426   OperationData ReducedValueData;
5427 
5428   /// Should we model this reduction as a pairwise reduction tree or a tree that
5429   /// splits the vector in halves and adds those halves.
5430   bool IsPairwiseReduction = false;
5431 
5432   /// Checks if the ParentStackElem.first should be marked as a reduction
5433   /// operation with an extra argument or as extra argument itself.
5434   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
5435                     Value *ExtraArg) {
5436     if (ExtraArgs.count(ParentStackElem.first)) {
5437       ExtraArgs[ParentStackElem.first] = nullptr;
5438       // We ran into something like:
5439       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
5440       // The whole ParentStackElem.first should be considered as an extra value
5441       // in this case.
5442       // Do not perform analysis of remaining operands of ParentStackElem.first
5443       // instruction, this whole instruction is an extra argument.
5444       ParentStackElem.second = ParentStackElem.first->getNumOperands();
5445     } else {
5446       // We ran into something like:
5447       // ParentStackElem.first += ... + ExtraArg + ...
5448       ExtraArgs[ParentStackElem.first] = ExtraArg;
5449     }
5450   }
5451 
5452   static OperationData getOperationData(Value *V) {
5453     if (!V)
5454       return OperationData();
5455 
5456     Value *LHS;
5457     Value *RHS;
5458     if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(V)) {
5459       return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS,
5460                            RK_Arithmetic);
5461     }
5462     if (auto *Select = dyn_cast<SelectInst>(V)) {
5463       // Look for a min/max pattern.
5464       if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
5465         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
5466       } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
5467         return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
5468       } else if (m_OrdFMin(m_Value(LHS), m_Value(RHS)).match(Select) ||
5469                  m_UnordFMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
5470         return OperationData(
5471             Instruction::FCmp, LHS, RHS, RK_Min,
5472             cast<Instruction>(Select->getCondition())->hasNoNaNs());
5473       } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
5474         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
5475       } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
5476         return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
5477       } else if (m_OrdFMax(m_Value(LHS), m_Value(RHS)).match(Select) ||
5478                  m_UnordFMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
5479         return OperationData(
5480             Instruction::FCmp, LHS, RHS, RK_Max,
5481             cast<Instruction>(Select->getCondition())->hasNoNaNs());
5482       }
5483     }
5484     return OperationData(V);
5485   }
5486 
5487 public:
5488   HorizontalReduction() = default;
5489 
5490   /// Try to find a reduction tree.
5491   bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
5492     assert((!Phi || is_contained(Phi->operands(), B)) &&
5493            "Thi phi needs to use the binary operator");
5494 
5495     ReductionData = getOperationData(B);
5496 
5497     // We could have a initial reductions that is not an add.
5498     //  r *= v1 + v2 + v3 + v4
5499     // In such a case start looking for a tree rooted in the first '+'.
5500     if (Phi) {
5501       if (ReductionData.getLHS() == Phi) {
5502         Phi = nullptr;
5503         B = dyn_cast<Instruction>(ReductionData.getRHS());
5504         ReductionData = getOperationData(B);
5505       } else if (ReductionData.getRHS() == Phi) {
5506         Phi = nullptr;
5507         B = dyn_cast<Instruction>(ReductionData.getLHS());
5508         ReductionData = getOperationData(B);
5509       }
5510     }
5511 
5512     if (!ReductionData.isVectorizable(B))
5513       return false;
5514 
5515     Type *Ty = B->getType();
5516     if (!isValidElementType(Ty))
5517       return false;
5518 
5519     ReducedValueData.clear();
5520     ReductionRoot = B;
5521 
5522     // Post order traverse the reduction tree starting at B. We only handle true
5523     // trees containing only binary operators.
5524     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
5525     Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
5526     ReductionData.initReductionOps(ReductionOps);
5527     while (!Stack.empty()) {
5528       Instruction *TreeN = Stack.back().first;
5529       unsigned EdgeToVist = Stack.back().second++;
5530       OperationData OpData = getOperationData(TreeN);
5531       bool IsReducedValue = OpData != ReductionData;
5532 
5533       // Postorder vist.
5534       if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
5535         if (IsReducedValue)
5536           ReducedVals.push_back(TreeN);
5537         else {
5538           auto I = ExtraArgs.find(TreeN);
5539           if (I != ExtraArgs.end() && !I->second) {
5540             // Check if TreeN is an extra argument of its parent operation.
5541             if (Stack.size() <= 1) {
5542               // TreeN can't be an extra argument as it is a root reduction
5543               // operation.
5544               return false;
5545             }
5546             // Yes, TreeN is an extra argument, do not add it to a list of
5547             // reduction operations.
5548             // Stack[Stack.size() - 2] always points to the parent operation.
5549             markExtraArg(Stack[Stack.size() - 2], TreeN);
5550             ExtraArgs.erase(TreeN);
5551           } else
5552             ReductionData.addReductionOps(TreeN, ReductionOps);
5553         }
5554         // Retract.
5555         Stack.pop_back();
5556         continue;
5557       }
5558 
5559       // Visit left or right.
5560       Value *NextV = TreeN->getOperand(EdgeToVist);
5561       if (NextV != Phi) {
5562         auto *I = dyn_cast<Instruction>(NextV);
5563         OpData = getOperationData(I);
5564         // Continue analysis if the next operand is a reduction operation or
5565         // (possibly) a reduced value. If the reduced value opcode is not set,
5566         // the first met operation != reduction operation is considered as the
5567         // reduced value class.
5568         if (I && (!ReducedValueData || OpData == ReducedValueData ||
5569                   OpData == ReductionData)) {
5570           const bool IsReductionOperation = OpData == ReductionData;
5571           // Only handle trees in the current basic block.
5572           if (!ReductionData.hasSameParent(I, B->getParent(),
5573                                            IsReductionOperation)) {
5574             // I is an extra argument for TreeN (its parent operation).
5575             markExtraArg(Stack.back(), I);
5576             continue;
5577           }
5578 
5579           // Each tree node needs to have minimal number of users except for the
5580           // ultimate reduction.
5581           if (!ReductionData.hasRequiredNumberOfUses(I,
5582                                                      OpData == ReductionData) &&
5583               I != B) {
5584             // I is an extra argument for TreeN (its parent operation).
5585             markExtraArg(Stack.back(), I);
5586             continue;
5587           }
5588 
5589           if (IsReductionOperation) {
5590             // We need to be able to reassociate the reduction operations.
5591             if (!OpData.isAssociative(I)) {
5592               // I is an extra argument for TreeN (its parent operation).
5593               markExtraArg(Stack.back(), I);
5594               continue;
5595             }
5596           } else if (ReducedValueData &&
5597                      ReducedValueData != OpData) {
5598             // Make sure that the opcodes of the operations that we are going to
5599             // reduce match.
5600             // I is an extra argument for TreeN (its parent operation).
5601             markExtraArg(Stack.back(), I);
5602             continue;
5603           } else if (!ReducedValueData)
5604             ReducedValueData = OpData;
5605 
5606           Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
5607           continue;
5608         }
5609       }
5610       // NextV is an extra argument for TreeN (its parent operation).
5611       markExtraArg(Stack.back(), NextV);
5612     }
5613     return true;
5614   }
5615 
5616   /// Attempt to vectorize the tree found by
5617   /// matchAssociativeReduction.
5618   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
5619     if (ReducedVals.empty())
5620       return false;
5621 
5622     // If there is a sufficient number of reduction values, reduce
5623     // to a nearby power-of-2. Can safely generate oversized
5624     // vectors and rely on the backend to split them to legal sizes.
5625     unsigned NumReducedVals = ReducedVals.size();
5626     if (NumReducedVals < 4)
5627       return false;
5628 
5629     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
5630 
5631     Value *VectorizedTree = nullptr;
5632     IRBuilder<> Builder(ReductionRoot);
5633     FastMathFlags Unsafe;
5634     Unsafe.setFast();
5635     Builder.setFastMathFlags(Unsafe);
5636     unsigned i = 0;
5637 
5638     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
5639     // The same extra argument may be used several time, so log each attempt
5640     // to use it.
5641     for (auto &Pair : ExtraArgs)
5642       ExternallyUsedValues[Pair.second].push_back(Pair.first);
5643     SmallVector<Value *, 16> IgnoreList;
5644     for (auto &V : ReductionOps)
5645       IgnoreList.append(V.begin(), V.end());
5646     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
5647       auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
5648       V.buildTree(VL, ExternallyUsedValues, IgnoreList);
5649       Optional<ArrayRef<unsigned>> Order = V.bestOrder();
5650       // TODO: Handle orders of size less than number of elements in the vector.
5651       if (Order && Order->size() == VL.size()) {
5652         // TODO: reorder tree nodes without tree rebuilding.
5653         SmallVector<Value *, 4> ReorderedOps(VL.size());
5654         llvm::transform(*Order, ReorderedOps.begin(),
5655                         [VL](const unsigned Idx) { return VL[Idx]; });
5656         V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
5657       }
5658       if (V.isTreeTinyAndNotFullyVectorizable())
5659         break;
5660 
5661       V.computeMinimumValueSizes();
5662 
5663       // Estimate cost.
5664       int TreeCost = V.getTreeCost();
5665       int ReductionCost = getReductionCost(TTI, ReducedVals[i], ReduxWidth);
5666       int Cost = TreeCost + ReductionCost;
5667       if (Cost >= -SLPCostThreshold) {
5668           V.getORE()->emit([&]() {
5669               return OptimizationRemarkMissed(
5670                          SV_NAME, "HorSLPNotBeneficial", cast<Instruction>(VL[0]))
5671                      << "Vectorizing horizontal reduction is possible"
5672                      << "but not beneficial with cost "
5673                      << ore::NV("Cost", Cost) << " and threshold "
5674                      << ore::NV("Threshold", -SLPCostThreshold);
5675           });
5676           break;
5677       }
5678 
5679       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
5680                         << Cost << ". (HorRdx)\n");
5681       V.getORE()->emit([&]() {
5682           return OptimizationRemark(
5683                      SV_NAME, "VectorizedHorizontalReduction", cast<Instruction>(VL[0]))
5684           << "Vectorized horizontal reduction with cost "
5685           << ore::NV("Cost", Cost) << " and with tree size "
5686           << ore::NV("TreeSize", V.getTreeSize());
5687       });
5688 
5689       // Vectorize a tree.
5690       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
5691       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
5692 
5693       // Emit a reduction.
5694       Value *ReducedSubTree =
5695           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
5696       if (VectorizedTree) {
5697         Builder.SetCurrentDebugLocation(Loc);
5698         OperationData VectReductionData(ReductionData.getOpcode(),
5699                                         VectorizedTree, ReducedSubTree,
5700                                         ReductionData.getKind());
5701         VectorizedTree =
5702             VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
5703       } else
5704         VectorizedTree = ReducedSubTree;
5705       i += ReduxWidth;
5706       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
5707     }
5708 
5709     if (VectorizedTree) {
5710       // Finish the reduction.
5711       for (; i < NumReducedVals; ++i) {
5712         auto *I = cast<Instruction>(ReducedVals[i]);
5713         Builder.SetCurrentDebugLocation(I->getDebugLoc());
5714         OperationData VectReductionData(ReductionData.getOpcode(),
5715                                         VectorizedTree, I,
5716                                         ReductionData.getKind());
5717         VectorizedTree = VectReductionData.createOp(Builder, "", ReductionOps);
5718       }
5719       for (auto &Pair : ExternallyUsedValues) {
5720         assert(!Pair.second.empty() &&
5721                "At least one DebugLoc must be inserted");
5722         // Add each externally used value to the final reduction.
5723         for (auto *I : Pair.second) {
5724           Builder.SetCurrentDebugLocation(I->getDebugLoc());
5725           OperationData VectReductionData(ReductionData.getOpcode(),
5726                                           VectorizedTree, Pair.first,
5727                                           ReductionData.getKind());
5728           VectorizedTree = VectReductionData.createOp(Builder, "op.extra", I);
5729         }
5730       }
5731       // Update users.
5732       ReductionRoot->replaceAllUsesWith(VectorizedTree);
5733     }
5734     return VectorizedTree != nullptr;
5735   }
5736 
5737   unsigned numReductionValues() const {
5738     return ReducedVals.size();
5739   }
5740 
5741 private:
5742   /// Calculate the cost of a reduction.
5743   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
5744                        unsigned ReduxWidth) {
5745     Type *ScalarTy = FirstReducedVal->getType();
5746     Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
5747 
5748     int PairwiseRdxCost;
5749     int SplittingRdxCost;
5750     switch (ReductionData.getKind()) {
5751     case RK_Arithmetic:
5752       PairwiseRdxCost =
5753           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
5754                                           /*IsPairwiseForm=*/true);
5755       SplittingRdxCost =
5756           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
5757                                           /*IsPairwiseForm=*/false);
5758       break;
5759     case RK_Min:
5760     case RK_Max:
5761     case RK_UMin:
5762     case RK_UMax: {
5763       Type *VecCondTy = CmpInst::makeCmpResultType(VecTy);
5764       bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
5765                         ReductionData.getKind() == RK_UMax;
5766       PairwiseRdxCost =
5767           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
5768                                       /*IsPairwiseForm=*/true, IsUnsigned);
5769       SplittingRdxCost =
5770           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
5771                                       /*IsPairwiseForm=*/false, IsUnsigned);
5772       break;
5773     }
5774     case RK_None:
5775       llvm_unreachable("Expected arithmetic or min/max reduction operation");
5776     }
5777 
5778     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
5779     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
5780 
5781     int ScalarReduxCost;
5782     switch (ReductionData.getKind()) {
5783     case RK_Arithmetic:
5784       ScalarReduxCost =
5785           TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
5786       break;
5787     case RK_Min:
5788     case RK_Max:
5789     case RK_UMin:
5790     case RK_UMax:
5791       ScalarReduxCost =
5792           TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
5793           TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
5794                                   CmpInst::makeCmpResultType(ScalarTy));
5795       break;
5796     case RK_None:
5797       llvm_unreachable("Expected arithmetic or min/max reduction operation");
5798     }
5799     ScalarReduxCost *= (ReduxWidth - 1);
5800 
5801     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
5802                       << " for reduction that starts with " << *FirstReducedVal
5803                       << " (It is a "
5804                       << (IsPairwiseReduction ? "pairwise" : "splitting")
5805                       << " reduction)\n");
5806 
5807     return VecReduxCost - ScalarReduxCost;
5808   }
5809 
5810   /// Emit a horizontal reduction of the vectorized value.
5811   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
5812                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
5813     assert(VectorizedValue && "Need to have a vectorized tree node");
5814     assert(isPowerOf2_32(ReduxWidth) &&
5815            "We only handle power-of-two reductions for now");
5816 
5817     if (!IsPairwiseReduction)
5818       return createSimpleTargetReduction(
5819           Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
5820           ReductionData.getFlags(), ReductionOps.back());
5821 
5822     Value *TmpVec = VectorizedValue;
5823     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
5824       Value *LeftMask =
5825           createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
5826       Value *RightMask =
5827           createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
5828 
5829       Value *LeftShuf = Builder.CreateShuffleVector(
5830           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
5831       Value *RightShuf = Builder.CreateShuffleVector(
5832           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
5833           "rdx.shuf.r");
5834       OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
5835                                       RightShuf, ReductionData.getKind());
5836       TmpVec = VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
5837     }
5838 
5839     // The result is in the first element of the vector.
5840     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
5841   }
5842 };
5843 
5844 } // end anonymous namespace
5845 
5846 /// Recognize construction of vectors like
5847 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
5848 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
5849 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
5850 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
5851 ///  starting from the last insertelement instruction.
5852 ///
5853 /// Returns true if it matches
5854 static bool findBuildVector(InsertElementInst *LastInsertElem,
5855                             TargetTransformInfo *TTI,
5856                             SmallVectorImpl<Value *> &BuildVectorOpds,
5857                             int &UserCost) {
5858   UserCost = 0;
5859   Value *V = nullptr;
5860   do {
5861     if (auto *CI = dyn_cast<ConstantInt>(LastInsertElem->getOperand(2))) {
5862       UserCost += TTI->getVectorInstrCost(Instruction::InsertElement,
5863                                           LastInsertElem->getType(),
5864                                           CI->getZExtValue());
5865     }
5866     BuildVectorOpds.push_back(LastInsertElem->getOperand(1));
5867     V = LastInsertElem->getOperand(0);
5868     if (isa<UndefValue>(V))
5869       break;
5870     LastInsertElem = dyn_cast<InsertElementInst>(V);
5871     if (!LastInsertElem || !LastInsertElem->hasOneUse())
5872       return false;
5873   } while (true);
5874   std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
5875   return true;
5876 }
5877 
5878 /// Like findBuildVector, but looks for construction of aggregate.
5879 ///
5880 /// \return true if it matches.
5881 static bool findBuildAggregate(InsertValueInst *IV,
5882                                SmallVectorImpl<Value *> &BuildVectorOpds) {
5883   Value *V;
5884   do {
5885     BuildVectorOpds.push_back(IV->getInsertedValueOperand());
5886     V = IV->getAggregateOperand();
5887     if (isa<UndefValue>(V))
5888       break;
5889     IV = dyn_cast<InsertValueInst>(V);
5890     if (!IV || !IV->hasOneUse())
5891       return false;
5892   } while (true);
5893   std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
5894   return true;
5895 }
5896 
5897 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
5898   return V->getType() < V2->getType();
5899 }
5900 
5901 /// Try and get a reduction value from a phi node.
5902 ///
5903 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
5904 /// if they come from either \p ParentBB or a containing loop latch.
5905 ///
5906 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
5907 /// if not possible.
5908 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
5909                                 BasicBlock *ParentBB, LoopInfo *LI) {
5910   // There are situations where the reduction value is not dominated by the
5911   // reduction phi. Vectorizing such cases has been reported to cause
5912   // miscompiles. See PR25787.
5913   auto DominatedReduxValue = [&](Value *R) {
5914     return isa<Instruction>(R) &&
5915            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
5916   };
5917 
5918   Value *Rdx = nullptr;
5919 
5920   // Return the incoming value if it comes from the same BB as the phi node.
5921   if (P->getIncomingBlock(0) == ParentBB) {
5922     Rdx = P->getIncomingValue(0);
5923   } else if (P->getIncomingBlock(1) == ParentBB) {
5924     Rdx = P->getIncomingValue(1);
5925   }
5926 
5927   if (Rdx && DominatedReduxValue(Rdx))
5928     return Rdx;
5929 
5930   // Otherwise, check whether we have a loop latch to look at.
5931   Loop *BBL = LI->getLoopFor(ParentBB);
5932   if (!BBL)
5933     return nullptr;
5934   BasicBlock *BBLatch = BBL->getLoopLatch();
5935   if (!BBLatch)
5936     return nullptr;
5937 
5938   // There is a loop latch, return the incoming value if it comes from
5939   // that. This reduction pattern occasionally turns up.
5940   if (P->getIncomingBlock(0) == BBLatch) {
5941     Rdx = P->getIncomingValue(0);
5942   } else if (P->getIncomingBlock(1) == BBLatch) {
5943     Rdx = P->getIncomingValue(1);
5944   }
5945 
5946   if (Rdx && DominatedReduxValue(Rdx))
5947     return Rdx;
5948 
5949   return nullptr;
5950 }
5951 
5952 /// Attempt to reduce a horizontal reduction.
5953 /// If it is legal to match a horizontal reduction feeding the phi node \a P
5954 /// with reduction operators \a Root (or one of its operands) in a basic block
5955 /// \a BB, then check if it can be done. If horizontal reduction is not found
5956 /// and root instruction is a binary operation, vectorization of the operands is
5957 /// attempted.
5958 /// \returns true if a horizontal reduction was matched and reduced or operands
5959 /// of one of the binary instruction were vectorized.
5960 /// \returns false if a horizontal reduction was not matched (or not possible)
5961 /// or no vectorization of any binary operation feeding \a Root instruction was
5962 /// performed.
5963 static bool tryToVectorizeHorReductionOrInstOperands(
5964     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
5965     TargetTransformInfo *TTI,
5966     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
5967   if (!ShouldVectorizeHor)
5968     return false;
5969 
5970   if (!Root)
5971     return false;
5972 
5973   if (Root->getParent() != BB || isa<PHINode>(Root))
5974     return false;
5975   // Start analysis starting from Root instruction. If horizontal reduction is
5976   // found, try to vectorize it. If it is not a horizontal reduction or
5977   // vectorization is not possible or not effective, and currently analyzed
5978   // instruction is a binary operation, try to vectorize the operands, using
5979   // pre-order DFS traversal order. If the operands were not vectorized, repeat
5980   // the same procedure considering each operand as a possible root of the
5981   // horizontal reduction.
5982   // Interrupt the process if the Root instruction itself was vectorized or all
5983   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
5984   SmallVector<std::pair<WeakTrackingVH, unsigned>, 8> Stack(1, {Root, 0});
5985   SmallPtrSet<Value *, 8> VisitedInstrs;
5986   bool Res = false;
5987   while (!Stack.empty()) {
5988     Value *V;
5989     unsigned Level;
5990     std::tie(V, Level) = Stack.pop_back_val();
5991     if (!V)
5992       continue;
5993     auto *Inst = dyn_cast<Instruction>(V);
5994     if (!Inst)
5995       continue;
5996     auto *BI = dyn_cast<BinaryOperator>(Inst);
5997     auto *SI = dyn_cast<SelectInst>(Inst);
5998     if (BI || SI) {
5999       HorizontalReduction HorRdx;
6000       if (HorRdx.matchAssociativeReduction(P, Inst)) {
6001         if (HorRdx.tryToReduce(R, TTI)) {
6002           Res = true;
6003           // Set P to nullptr to avoid re-analysis of phi node in
6004           // matchAssociativeReduction function unless this is the root node.
6005           P = nullptr;
6006           continue;
6007         }
6008       }
6009       if (P && BI) {
6010         Inst = dyn_cast<Instruction>(BI->getOperand(0));
6011         if (Inst == P)
6012           Inst = dyn_cast<Instruction>(BI->getOperand(1));
6013         if (!Inst) {
6014           // Set P to nullptr to avoid re-analysis of phi node in
6015           // matchAssociativeReduction function unless this is the root node.
6016           P = nullptr;
6017           continue;
6018         }
6019       }
6020     }
6021     // Set P to nullptr to avoid re-analysis of phi node in
6022     // matchAssociativeReduction function unless this is the root node.
6023     P = nullptr;
6024     if (Vectorize(Inst, R)) {
6025       Res = true;
6026       continue;
6027     }
6028 
6029     // Try to vectorize operands.
6030     // Continue analysis for the instruction from the same basic block only to
6031     // save compile time.
6032     if (++Level < RecursionMaxDepth)
6033       for (auto *Op : Inst->operand_values())
6034         if (VisitedInstrs.insert(Op).second)
6035           if (auto *I = dyn_cast<Instruction>(Op))
6036             if (!isa<PHINode>(I) && I->getParent() == BB)
6037               Stack.emplace_back(Op, Level);
6038   }
6039   return Res;
6040 }
6041 
6042 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
6043                                                  BasicBlock *BB, BoUpSLP &R,
6044                                                  TargetTransformInfo *TTI) {
6045   if (!V)
6046     return false;
6047   auto *I = dyn_cast<Instruction>(V);
6048   if (!I)
6049     return false;
6050 
6051   if (!isa<BinaryOperator>(I))
6052     P = nullptr;
6053   // Try to match and vectorize a horizontal reduction.
6054   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
6055     return tryToVectorize(I, R);
6056   };
6057   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
6058                                                   ExtraVectorization);
6059 }
6060 
6061 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
6062                                                  BasicBlock *BB, BoUpSLP &R) {
6063   const DataLayout &DL = BB->getModule()->getDataLayout();
6064   if (!R.canMapToVector(IVI->getType(), DL))
6065     return false;
6066 
6067   SmallVector<Value *, 16> BuildVectorOpds;
6068   if (!findBuildAggregate(IVI, BuildVectorOpds))
6069     return false;
6070 
6071   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
6072   // Aggregate value is unlikely to be processed in vector register, we need to
6073   // extract scalars into scalar registers, so NeedExtraction is set true.
6074   return tryToVectorizeList(BuildVectorOpds, R);
6075 }
6076 
6077 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
6078                                                    BasicBlock *BB, BoUpSLP &R) {
6079   int UserCost;
6080   SmallVector<Value *, 16> BuildVectorOpds;
6081   if (!findBuildVector(IEI, TTI, BuildVectorOpds, UserCost) ||
6082       (llvm::all_of(BuildVectorOpds,
6083                     [](Value *V) { return isa<ExtractElementInst>(V); }) &&
6084        isShuffle(BuildVectorOpds)))
6085     return false;
6086 
6087   // Vectorize starting with the build vector operands ignoring the BuildVector
6088   // instructions for the purpose of scheduling and user extraction.
6089   return tryToVectorizeList(BuildVectorOpds, R, UserCost);
6090 }
6091 
6092 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
6093                                          BoUpSLP &R) {
6094   if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
6095     return true;
6096 
6097   bool OpsChanged = false;
6098   for (int Idx = 0; Idx < 2; ++Idx) {
6099     OpsChanged |=
6100         vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
6101   }
6102   return OpsChanged;
6103 }
6104 
6105 bool SLPVectorizerPass::vectorizeSimpleInstructions(
6106     SmallVectorImpl<WeakVH> &Instructions, BasicBlock *BB, BoUpSLP &R) {
6107   bool OpsChanged = false;
6108   for (auto &VH : reverse(Instructions)) {
6109     auto *I = dyn_cast_or_null<Instruction>(VH);
6110     if (!I)
6111       continue;
6112     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
6113       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
6114     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
6115       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
6116     else if (auto *CI = dyn_cast<CmpInst>(I))
6117       OpsChanged |= vectorizeCmpInst(CI, BB, R);
6118   }
6119   Instructions.clear();
6120   return OpsChanged;
6121 }
6122 
6123 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
6124   bool Changed = false;
6125   SmallVector<Value *, 4> Incoming;
6126   SmallPtrSet<Value *, 16> VisitedInstrs;
6127 
6128   bool HaveVectorizedPhiNodes = true;
6129   while (HaveVectorizedPhiNodes) {
6130     HaveVectorizedPhiNodes = false;
6131 
6132     // Collect the incoming values from the PHIs.
6133     Incoming.clear();
6134     for (Instruction &I : *BB) {
6135       PHINode *P = dyn_cast<PHINode>(&I);
6136       if (!P)
6137         break;
6138 
6139       if (!VisitedInstrs.count(P))
6140         Incoming.push_back(P);
6141     }
6142 
6143     // Sort by type.
6144     std::stable_sort(Incoming.begin(), Incoming.end(), PhiTypeSorterFunc);
6145 
6146     // Try to vectorize elements base on their type.
6147     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
6148                                            E = Incoming.end();
6149          IncIt != E;) {
6150 
6151       // Look for the next elements with the same type.
6152       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
6153       while (SameTypeIt != E &&
6154              (*SameTypeIt)->getType() == (*IncIt)->getType()) {
6155         VisitedInstrs.insert(*SameTypeIt);
6156         ++SameTypeIt;
6157       }
6158 
6159       // Try to vectorize them.
6160       unsigned NumElts = (SameTypeIt - IncIt);
6161       LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("
6162                         << NumElts << ")\n");
6163       // The order in which the phi nodes appear in the program does not matter.
6164       // So allow tryToVectorizeList to reorder them if it is beneficial. This
6165       // is done when there are exactly two elements since tryToVectorizeList
6166       // asserts that there are only two values when AllowReorder is true.
6167       bool AllowReorder = NumElts == 2;
6168       if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R,
6169                                             /*UserCost=*/0, AllowReorder)) {
6170         // Success start over because instructions might have been changed.
6171         HaveVectorizedPhiNodes = true;
6172         Changed = true;
6173         break;
6174       }
6175 
6176       // Start over at the next instruction of a different type (or the end).
6177       IncIt = SameTypeIt;
6178     }
6179   }
6180 
6181   VisitedInstrs.clear();
6182 
6183   SmallVector<WeakVH, 8> PostProcessInstructions;
6184   SmallDenseSet<Instruction *, 4> KeyNodes;
6185   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; it++) {
6186     // We may go through BB multiple times so skip the one we have checked.
6187     if (!VisitedInstrs.insert(&*it).second) {
6188       if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
6189           vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
6190         // We would like to start over since some instructions are deleted
6191         // and the iterator may become invalid value.
6192         Changed = true;
6193         it = BB->begin();
6194         e = BB->end();
6195       }
6196       continue;
6197     }
6198 
6199     if (isa<DbgInfoIntrinsic>(it))
6200       continue;
6201 
6202     // Try to vectorize reductions that use PHINodes.
6203     if (PHINode *P = dyn_cast<PHINode>(it)) {
6204       // Check that the PHI is a reduction PHI.
6205       if (P->getNumIncomingValues() != 2)
6206         return Changed;
6207 
6208       // Try to match and vectorize a horizontal reduction.
6209       if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
6210                                    TTI)) {
6211         Changed = true;
6212         it = BB->begin();
6213         e = BB->end();
6214         continue;
6215       }
6216       continue;
6217     }
6218 
6219     // Ran into an instruction without users, like terminator, or function call
6220     // with ignored return value, store. Ignore unused instructions (basing on
6221     // instruction type, except for CallInst and InvokeInst).
6222     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
6223                             isa<InvokeInst>(it))) {
6224       KeyNodes.insert(&*it);
6225       bool OpsChanged = false;
6226       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
6227         for (auto *V : it->operand_values()) {
6228           // Try to match and vectorize a horizontal reduction.
6229           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
6230         }
6231       }
6232       // Start vectorization of post-process list of instructions from the
6233       // top-tree instructions to try to vectorize as many instructions as
6234       // possible.
6235       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
6236       if (OpsChanged) {
6237         // We would like to start over since some instructions are deleted
6238         // and the iterator may become invalid value.
6239         Changed = true;
6240         it = BB->begin();
6241         e = BB->end();
6242         continue;
6243       }
6244     }
6245 
6246     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
6247         isa<InsertValueInst>(it))
6248       PostProcessInstructions.push_back(&*it);
6249 
6250   }
6251 
6252   return Changed;
6253 }
6254 
6255 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
6256   auto Changed = false;
6257   for (auto &Entry : GEPs) {
6258     // If the getelementptr list has fewer than two elements, there's nothing
6259     // to do.
6260     if (Entry.second.size() < 2)
6261       continue;
6262 
6263     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
6264                       << Entry.second.size() << ".\n");
6265 
6266     // We process the getelementptr list in chunks of 16 (like we do for
6267     // stores) to minimize compile-time.
6268     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
6269       auto Len = std::min<unsigned>(BE - BI, 16);
6270       auto GEPList = makeArrayRef(&Entry.second[BI], Len);
6271 
6272       // Initialize a set a candidate getelementptrs. Note that we use a
6273       // SetVector here to preserve program order. If the index computations
6274       // are vectorizable and begin with loads, we want to minimize the chance
6275       // of having to reorder them later.
6276       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
6277 
6278       // Some of the candidates may have already been vectorized after we
6279       // initially collected them. If so, the WeakTrackingVHs will have
6280       // nullified the
6281       // values, so remove them from the set of candidates.
6282       Candidates.remove(nullptr);
6283 
6284       // Remove from the set of candidates all pairs of getelementptrs with
6285       // constant differences. Such getelementptrs are likely not good
6286       // candidates for vectorization in a bottom-up phase since one can be
6287       // computed from the other. We also ensure all candidate getelementptr
6288       // indices are unique.
6289       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
6290         auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
6291         if (!Candidates.count(GEPI))
6292           continue;
6293         auto *SCEVI = SE->getSCEV(GEPList[I]);
6294         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
6295           auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
6296           auto *SCEVJ = SE->getSCEV(GEPList[J]);
6297           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
6298             Candidates.remove(GEPList[I]);
6299             Candidates.remove(GEPList[J]);
6300           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
6301             Candidates.remove(GEPList[J]);
6302           }
6303         }
6304       }
6305 
6306       // We break out of the above computation as soon as we know there are
6307       // fewer than two candidates remaining.
6308       if (Candidates.size() < 2)
6309         continue;
6310 
6311       // Add the single, non-constant index of each candidate to the bundle. We
6312       // ensured the indices met these constraints when we originally collected
6313       // the getelementptrs.
6314       SmallVector<Value *, 16> Bundle(Candidates.size());
6315       auto BundleIndex = 0u;
6316       for (auto *V : Candidates) {
6317         auto *GEP = cast<GetElementPtrInst>(V);
6318         auto *GEPIdx = GEP->idx_begin()->get();
6319         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
6320         Bundle[BundleIndex++] = GEPIdx;
6321       }
6322 
6323       // Try and vectorize the indices. We are currently only interested in
6324       // gather-like cases of the form:
6325       //
6326       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
6327       //
6328       // where the loads of "a", the loads of "b", and the subtractions can be
6329       // performed in parallel. It's likely that detecting this pattern in a
6330       // bottom-up phase will be simpler and less costly than building a
6331       // full-blown top-down phase beginning at the consecutive loads.
6332       Changed |= tryToVectorizeList(Bundle, R);
6333     }
6334   }
6335   return Changed;
6336 }
6337 
6338 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
6339   bool Changed = false;
6340   // Attempt to sort and vectorize each of the store-groups.
6341   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
6342        ++it) {
6343     if (it->second.size() < 2)
6344       continue;
6345 
6346     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
6347                       << it->second.size() << ".\n");
6348 
6349     // Process the stores in chunks of 16.
6350     // TODO: The limit of 16 inhibits greater vectorization factors.
6351     //       For example, AVX2 supports v32i8. Increasing this limit, however,
6352     //       may cause a significant compile-time increase.
6353     for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI+=16) {
6354       unsigned Len = std::min<unsigned>(CE - CI, 16);
6355       Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
6356     }
6357   }
6358   return Changed;
6359 }
6360 
6361 char SLPVectorizer::ID = 0;
6362 
6363 static const char lv_name[] = "SLP Vectorizer";
6364 
6365 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
6366 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
6367 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
6368 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
6369 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
6370 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
6371 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
6372 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
6373 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
6374 
6375 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
6376