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