OSDN Git Service

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