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