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