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