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