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-constant.
3698   Value *ZextLoad = Root;
3699   while (!isa<ConstantExpr>(ZextLoad) &&
3700          (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
3701           match(ZextLoad, m_Shl(m_Value(), m_Constant()))))
3702     ZextLoad = cast<BinaryOperator>(ZextLoad)->getOperand(0);
3703 
3704   // Check if the input is an extended load of the required or/shift expression.
3705   Value *LoadPtr;
3706   if (ZextLoad == Root || !match(ZextLoad, m_ZExt(m_Load(m_Value(LoadPtr)))))
3707     return false;
3708 
3709   // Require that the total load bit width is a legal integer type.
3710   // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
3711   // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
3712   Type *SrcTy = LoadPtr->getType()->getPointerElementType();
3713   unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
3714   if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
3715     return false;
3716 
3717   // Everything matched - assume that we can fold the whole sequence using
3718   // load combining.
3719   LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
3720              << *(cast<Instruction>(Root)) << "\n");
3721 
3722   return true;
3723 }
3724 
3725 bool BoUpSLP::isLoadCombineReductionCandidate(unsigned RdxOpcode) const {
3726   if (RdxOpcode != Instruction::Or)
3727     return false;
3728 
3729   unsigned NumElts = VectorizableTree[0]->Scalars.size();
3730   Value *FirstReduced = VectorizableTree[0]->Scalars[0];
3731   return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI);
3732 }
3733 
3734 bool BoUpSLP::isLoadCombineCandidate() const {
3735   // Peek through a final sequence of stores and check if all operations are
3736   // likely to be load-combined.
3737   unsigned NumElts = VectorizableTree[0]->Scalars.size();
3738   for (Value *Scalar : VectorizableTree[0]->Scalars) {
3739     Value *X;
3740     if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
3741         !isLoadCombineCandidateImpl(X, NumElts, TTI))
3742       return false;
3743   }
3744   return true;
3745 }
3746 
3747 bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() const {
3748   // We can vectorize the tree if its size is greater than or equal to the
3749   // minimum size specified by the MinTreeSize command line option.
3750   if (VectorizableTree.size() >= MinTreeSize)
3751     return false;
3752 
3753   // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
3754   // can vectorize it if we can prove it fully vectorizable.
3755   if (isFullyVectorizableTinyTree())
3756     return false;
3757 
3758   assert(VectorizableTree.empty()
3759              ? ExternalUses.empty()
3760              : true && "We shouldn't have any external users");
3761 
3762   // Otherwise, we can't vectorize the tree. It is both tiny and not fully
3763   // vectorizable.
3764   return true;
3765 }
3766 
3767 int BoUpSLP::getSpillCost() const {
3768   // Walk from the bottom of the tree to the top, tracking which values are
3769   // live. When we see a call instruction that is not part of our tree,
3770   // query TTI to see if there is a cost to keeping values live over it
3771   // (for example, if spills and fills are required).
3772   unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
3773   int Cost = 0;
3774 
3775   SmallPtrSet<Instruction*, 4> LiveValues;
3776   Instruction *PrevInst = nullptr;
3777 
3778   // The entries in VectorizableTree are not necessarily ordered by their
3779   // position in basic blocks. Collect them and order them by dominance so later
3780   // instructions are guaranteed to be visited first. For instructions in
3781   // different basic blocks, we only scan to the beginning of the block, so
3782   // their order does not matter, as long as all instructions in a basic block
3783   // are grouped together. Using dominance ensures a deterministic order.
3784   SmallVector<Instruction *, 16> OrderedScalars;
3785   for (const auto &TEPtr : VectorizableTree) {
3786     Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
3787     if (!Inst)
3788       continue;
3789     OrderedScalars.push_back(Inst);
3790   }
3791   llvm::stable_sort(OrderedScalars, [this](Instruction *A, Instruction *B) {
3792     return DT->dominates(B, A);
3793   });
3794 
3795   for (Instruction *Inst : OrderedScalars) {
3796     if (!PrevInst) {
3797       PrevInst = Inst;
3798       continue;
3799     }
3800 
3801     // Update LiveValues.
3802     LiveValues.erase(PrevInst);
3803     for (auto &J : PrevInst->operands()) {
3804       if (isa<Instruction>(&*J) && getTreeEntry(&*J))
3805         LiveValues.insert(cast<Instruction>(&*J));
3806     }
3807 
3808     LLVM_DEBUG({
3809       dbgs() << "SLP: #LV: " << LiveValues.size();
3810       for (auto *X : LiveValues)
3811         dbgs() << " " << X->getName();
3812       dbgs() << ", Looking at ";
3813       Inst->dump();
3814     });
3815 
3816     // Now find the sequence of instructions between PrevInst and Inst.
3817     unsigned NumCalls = 0;
3818     BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
3819                                  PrevInstIt =
3820                                      PrevInst->getIterator().getReverse();
3821     while (InstIt != PrevInstIt) {
3822       if (PrevInstIt == PrevInst->getParent()->rend()) {
3823         PrevInstIt = Inst->getParent()->rbegin();
3824         continue;
3825       }
3826 
3827       // Debug information does not impact spill cost.
3828       if ((isa<CallInst>(&*PrevInstIt) &&
3829            !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
3830           &*PrevInstIt != PrevInst)
3831         NumCalls++;
3832 
3833       ++PrevInstIt;
3834     }
3835 
3836     if (NumCalls) {
3837       SmallVector<Type*, 4> V;
3838       for (auto *II : LiveValues)
3839         V.push_back(FixedVectorType::get(II->getType(), BundleWidth));
3840       Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
3841     }
3842 
3843     PrevInst = Inst;
3844   }
3845 
3846   return Cost;
3847 }
3848 
3849 int BoUpSLP::getTreeCost() {
3850   int Cost = 0;
3851   LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
3852                     << VectorizableTree.size() << ".\n");
3853 
3854   unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
3855 
3856   for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
3857     TreeEntry &TE = *VectorizableTree[I].get();
3858 
3859     // We create duplicate tree entries for gather sequences that have multiple
3860     // uses. However, we should not compute the cost of duplicate sequences.
3861     // For example, if we have a build vector (i.e., insertelement sequence)
3862     // that is used by more than one vector instruction, we only need to
3863     // compute the cost of the insertelement instructions once. The redundant
3864     // instructions will be eliminated by CSE.
3865     //
3866     // We should consider not creating duplicate tree entries for gather
3867     // sequences, and instead add additional edges to the tree representing
3868     // their uses. Since such an approach results in fewer total entries,
3869     // existing heuristics based on tree size may yield different results.
3870     //
3871     if (TE.State == TreeEntry::NeedToGather &&
3872         std::any_of(std::next(VectorizableTree.begin(), I + 1),
3873                     VectorizableTree.end(),
3874                     [TE](const std::unique_ptr<TreeEntry> &EntryPtr) {
3875                       return EntryPtr->State == TreeEntry::NeedToGather &&
3876                              EntryPtr->isSame(TE.Scalars);
3877                     }))
3878       continue;
3879 
3880     int C = getEntryCost(&TE);
3881     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
3882                       << " for bundle that starts with " << *TE.Scalars[0]
3883                       << ".\n");
3884     Cost += C;
3885   }
3886 
3887   SmallPtrSet<Value *, 16> ExtractCostCalculated;
3888   int ExtractCost = 0;
3889   for (ExternalUser &EU : ExternalUses) {
3890     // We only add extract cost once for the same scalar.
3891     if (!ExtractCostCalculated.insert(EU.Scalar).second)
3892       continue;
3893 
3894     // Uses by ephemeral values are free (because the ephemeral value will be
3895     // removed prior to code generation, and so the extraction will be
3896     // removed as well).
3897     if (EphValues.count(EU.User))
3898       continue;
3899 
3900     // If we plan to rewrite the tree in a smaller type, we will need to sign
3901     // extend the extracted value back to the original type. Here, we account
3902     // for the extract and the added cost of the sign extend if needed.
3903     auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
3904     auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
3905     if (MinBWs.count(ScalarRoot)) {
3906       auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
3907       auto Extend =
3908           MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
3909       VecTy = FixedVectorType::get(MinTy, BundleWidth);
3910       ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
3911                                                    VecTy, EU.Lane);
3912     } else {
3913       ExtractCost +=
3914           TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
3915     }
3916   }
3917 
3918   int SpillCost = getSpillCost();
3919   Cost += SpillCost + ExtractCost;
3920 
3921 #ifndef NDEBUG
3922   SmallString<256> Str;
3923   {
3924     raw_svector_ostream OS(Str);
3925     OS << "SLP: Spill Cost = " << SpillCost << ".\n"
3926        << "SLP: Extract Cost = " << ExtractCost << ".\n"
3927        << "SLP: Total Cost = " << Cost << ".\n";
3928   }
3929   LLVM_DEBUG(dbgs() << Str);
3930   if (ViewSLPTree)
3931     ViewGraph(this, "SLP" + F->getName(), false, Str);
3932 #endif
3933 
3934   return Cost;
3935 }
3936 
3937 int BoUpSLP::getGatherCost(FixedVectorType *Ty,
3938                            const DenseSet<unsigned> &ShuffledIndices) const {
3939   unsigned NumElts = Ty->getNumElements();
3940   APInt DemandedElts = APInt::getNullValue(NumElts);
3941   for (unsigned i = 0; i < NumElts; ++i)
3942     if (!ShuffledIndices.count(i))
3943       DemandedElts.setBit(i);
3944   int Cost = TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
3945                                            /*Extract*/ false);
3946   if (!ShuffledIndices.empty())
3947     Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
3948   return Cost;
3949 }
3950 
3951 int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
3952   // Find the type of the operands in VL.
3953   Type *ScalarTy = VL[0]->getType();
3954   if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
3955     ScalarTy = SI->getValueOperand()->getType();
3956   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
3957   // Find the cost of inserting/extracting values from the vector.
3958   // Check if the same elements are inserted several times and count them as
3959   // shuffle candidates.
3960   DenseSet<unsigned> ShuffledElements;
3961   DenseSet<Value *> UniqueElements;
3962   // Iterate in reverse order to consider insert elements with the high cost.
3963   for (unsigned I = VL.size(); I > 0; --I) {
3964     unsigned Idx = I - 1;
3965     if (!UniqueElements.insert(VL[Idx]).second)
3966       ShuffledElements.insert(Idx);
3967   }
3968   return getGatherCost(VecTy, ShuffledElements);
3969 }
3970 
3971 // Perform operand reordering on the instructions in VL and return the reordered
3972 // operands in Left and Right.
3973 void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
3974                                              SmallVectorImpl<Value *> &Left,
3975                                              SmallVectorImpl<Value *> &Right,
3976                                              const DataLayout &DL,
3977                                              ScalarEvolution &SE,
3978                                              const BoUpSLP &R) {
3979   if (VL.empty())
3980     return;
3981   VLOperands Ops(VL, DL, SE, R);
3982   // Reorder the operands in place.
3983   Ops.reorder();
3984   Left = Ops.getVL(0);
3985   Right = Ops.getVL(1);
3986 }
3987 
3988 void BoUpSLP::setInsertPointAfterBundle(TreeEntry *E) {
3989   // Get the basic block this bundle is in. All instructions in the bundle
3990   // should be in this block.
3991   auto *Front = E->getMainOp();
3992   auto *BB = Front->getParent();
3993   assert(llvm::all_of(make_range(E->Scalars.begin(), E->Scalars.end()),
3994                       [=](Value *V) -> bool {
3995                         auto *I = cast<Instruction>(V);
3996                         return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
3997                       }));
3998 
3999   // The last instruction in the bundle in program order.
4000   Instruction *LastInst = nullptr;
4001 
4002   // Find the last instruction. The common case should be that BB has been
4003   // scheduled, and the last instruction is VL.back(). So we start with
4004   // VL.back() and iterate over schedule data until we reach the end of the
4005   // bundle. The end of the bundle is marked by null ScheduleData.
4006   if (BlocksSchedules.count(BB)) {
4007     auto *Bundle =
4008         BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
4009     if (Bundle && Bundle->isPartOfBundle())
4010       for (; Bundle; Bundle = Bundle->NextInBundle)
4011         if (Bundle->OpValue == Bundle->Inst)
4012           LastInst = Bundle->Inst;
4013   }
4014 
4015   // LastInst can still be null at this point if there's either not an entry
4016   // for BB in BlocksSchedules or there's no ScheduleData available for
4017   // VL.back(). This can be the case if buildTree_rec aborts for various
4018   // reasons (e.g., the maximum recursion depth is reached, the maximum region
4019   // size is reached, etc.). ScheduleData is initialized in the scheduling
4020   // "dry-run".
4021   //
4022   // If this happens, we can still find the last instruction by brute force. We
4023   // iterate forwards from Front (inclusive) until we either see all
4024   // instructions in the bundle or reach the end of the block. If Front is the
4025   // last instruction in program order, LastInst will be set to Front, and we
4026   // will visit all the remaining instructions in the block.
4027   //
4028   // One of the reasons we exit early from buildTree_rec is to place an upper
4029   // bound on compile-time. Thus, taking an additional compile-time hit here is
4030   // not ideal. However, this should be exceedingly rare since it requires that
4031   // we both exit early from buildTree_rec and that the bundle be out-of-order
4032   // (causing us to iterate all the way to the end of the block).
4033   if (!LastInst) {
4034     SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
4035     for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
4036       if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
4037         LastInst = &I;
4038       if (Bundle.empty())
4039         break;
4040     }
4041   }
4042   assert(LastInst && "Failed to find last instruction in bundle");
4043 
4044   // Set the insertion point after the last instruction in the bundle. Set the
4045   // debug location to Front.
4046   Builder.SetInsertPoint(BB, ++LastInst->getIterator());
4047   Builder.SetCurrentDebugLocation(Front->getDebugLoc());
4048 }
4049 
4050 Value *BoUpSLP::Gather(ArrayRef<Value *> VL, FixedVectorType *Ty) {
4051   Value *Vec = UndefValue::get(Ty);
4052   // Generate the 'InsertElement' instruction.
4053   for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
4054     Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
4055     if (auto *Insrt = dyn_cast<InsertElementInst>(Vec)) {
4056       GatherSeq.insert(Insrt);
4057       CSEBlocks.insert(Insrt->getParent());
4058 
4059       // Add to our 'need-to-extract' list.
4060       if (TreeEntry *E = getTreeEntry(VL[i])) {
4061         // Find which lane we need to extract.
4062         int FoundLane = -1;
4063         for (unsigned Lane = 0, LE = E->Scalars.size(); Lane != LE; ++Lane) {
4064           // Is this the lane of the scalar that we are looking for ?
4065           if (E->Scalars[Lane] == VL[i]) {
4066             FoundLane = Lane;
4067             break;
4068           }
4069         }
4070         assert(FoundLane >= 0 && "Could not find the correct lane");
4071         if (!E->ReuseShuffleIndices.empty()) {
4072           FoundLane =
4073               std::distance(E->ReuseShuffleIndices.begin(),
4074                             llvm::find(E->ReuseShuffleIndices, FoundLane));
4075         }
4076         ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
4077       }
4078     }
4079   }
4080 
4081   return Vec;
4082 }
4083 
4084 Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
4085   InstructionsState S = getSameOpcode(VL);
4086   if (S.getOpcode()) {
4087     if (TreeEntry *E = getTreeEntry(S.OpValue)) {
4088       if (E->isSame(VL)) {
4089         Value *V = vectorizeTree(E);
4090         if (VL.size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) {
4091           // We need to get the vectorized value but without shuffle.
4092           if (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
4093             V = SV->getOperand(0);
4094           } else {
4095             // Reshuffle to get only unique values.
4096             SmallVector<int, 4> UniqueIdxs;
4097             SmallSet<int, 4> UsedIdxs;
4098             for (int Idx : E->ReuseShuffleIndices)
4099               if (UsedIdxs.insert(Idx).second)
4100                 UniqueIdxs.emplace_back(Idx);
4101             V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
4102                                             UniqueIdxs);
4103           }
4104         }
4105         return V;
4106       }
4107     }
4108   }
4109 
4110   Type *ScalarTy = S.OpValue->getType();
4111   if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
4112     ScalarTy = SI->getValueOperand()->getType();
4113 
4114   // Check that every instruction appears once in this bundle.
4115   SmallVector<int, 4> ReuseShuffleIndicies;
4116   SmallVector<Value *, 4> UniqueValues;
4117   if (VL.size() > 2) {
4118     DenseMap<Value *, unsigned> UniquePositions;
4119     for (Value *V : VL) {
4120       auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4121       ReuseShuffleIndicies.emplace_back(Res.first->second);
4122       if (Res.second || isa<Constant>(V))
4123         UniqueValues.emplace_back(V);
4124     }
4125     // Do not shuffle single element or if number of unique values is not power
4126     // of 2.
4127     if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 ||
4128         !llvm::isPowerOf2_32(UniqueValues.size()))
4129       ReuseShuffleIndicies.clear();
4130     else
4131       VL = UniqueValues;
4132   }
4133   auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
4134 
4135   Value *V = Gather(VL, VecTy);
4136   if (!ReuseShuffleIndicies.empty()) {
4137     V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4138                                     ReuseShuffleIndicies, "shuffle");
4139     if (auto *I = dyn_cast<Instruction>(V)) {
4140       GatherSeq.insert(I);
4141       CSEBlocks.insert(I->getParent());
4142     }
4143   }
4144   return V;
4145 }
4146 
4147 static void inversePermutation(ArrayRef<unsigned> Indices,
4148                                SmallVectorImpl<int> &Mask) {
4149   Mask.clear();
4150   const unsigned E = Indices.size();
4151   Mask.resize(E);
4152   for (unsigned I = 0; I < E; ++I)
4153     Mask[Indices[I]] = I;
4154 }
4155 
4156 Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
4157   IRBuilder<>::InsertPointGuard Guard(Builder);
4158 
4159   if (E->VectorizedValue) {
4160     LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
4161     return E->VectorizedValue;
4162   }
4163 
4164   Instruction *VL0 = E->getMainOp();
4165   Type *ScalarTy = VL0->getType();
4166   if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
4167     ScalarTy = SI->getValueOperand()->getType();
4168   auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
4169 
4170   bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
4171 
4172   if (E->State == TreeEntry::NeedToGather) {
4173     setInsertPointAfterBundle(E);
4174     auto *V = Gather(E->Scalars, VecTy);
4175     if (NeedToShuffleReuses) {
4176       V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4177                                       E->ReuseShuffleIndices, "shuffle");
4178       if (auto *I = dyn_cast<Instruction>(V)) {
4179         GatherSeq.insert(I);
4180         CSEBlocks.insert(I->getParent());
4181       }
4182     }
4183     E->VectorizedValue = V;
4184     return V;
4185   }
4186 
4187   assert(E->State == TreeEntry::Vectorize && "Unhandled state");
4188   unsigned ShuffleOrOp =
4189       E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
4190   switch (ShuffleOrOp) {
4191     case Instruction::PHI: {
4192       auto *PH = cast<PHINode>(VL0);
4193       Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
4194       Builder.SetCurrentDebugLocation(PH->getDebugLoc());
4195       PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
4196       Value *V = NewPhi;
4197       if (NeedToShuffleReuses) {
4198         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4199                                         E->ReuseShuffleIndices, "shuffle");
4200       }
4201       E->VectorizedValue = V;
4202 
4203       // PHINodes may have multiple entries from the same block. We want to
4204       // visit every block once.
4205       SmallPtrSet<BasicBlock*, 4> VisitedBBs;
4206 
4207       for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
4208         ValueList Operands;
4209         BasicBlock *IBB = PH->getIncomingBlock(i);
4210 
4211         if (!VisitedBBs.insert(IBB).second) {
4212           NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
4213           continue;
4214         }
4215 
4216         Builder.SetInsertPoint(IBB->getTerminator());
4217         Builder.SetCurrentDebugLocation(PH->getDebugLoc());
4218         Value *Vec = vectorizeTree(E->getOperand(i));
4219         NewPhi->addIncoming(Vec, IBB);
4220       }
4221 
4222       assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
4223              "Invalid number of incoming values");
4224       return V;
4225     }
4226 
4227     case Instruction::ExtractElement: {
4228       Value *V = E->getSingleOperand(0);
4229       if (!E->ReorderIndices.empty()) {
4230         SmallVector<int, 4> Mask;
4231         inversePermutation(E->ReorderIndices, Mask);
4232         Builder.SetInsertPoint(VL0);
4233         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), Mask,
4234                                         "reorder_shuffle");
4235       }
4236       if (NeedToShuffleReuses) {
4237         // TODO: Merge this shuffle with the ReorderShuffleMask.
4238         if (E->ReorderIndices.empty())
4239           Builder.SetInsertPoint(VL0);
4240         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4241                                         E->ReuseShuffleIndices, "shuffle");
4242       }
4243       E->VectorizedValue = V;
4244       return V;
4245     }
4246     case Instruction::ExtractValue: {
4247       LoadInst *LI = cast<LoadInst>(E->getSingleOperand(0));
4248       Builder.SetInsertPoint(LI);
4249       PointerType *PtrTy =
4250           PointerType::get(VecTy, LI->getPointerAddressSpace());
4251       Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
4252       LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
4253       Value *NewV = propagateMetadata(V, E->Scalars);
4254       if (!E->ReorderIndices.empty()) {
4255         SmallVector<int, 4> Mask;
4256         inversePermutation(E->ReorderIndices, Mask);
4257         NewV = Builder.CreateShuffleVector(NewV, UndefValue::get(VecTy), Mask,
4258                                            "reorder_shuffle");
4259       }
4260       if (NeedToShuffleReuses) {
4261         // TODO: Merge this shuffle with the ReorderShuffleMask.
4262         NewV = Builder.CreateShuffleVector(NewV, UndefValue::get(VecTy),
4263                                            E->ReuseShuffleIndices, "shuffle");
4264       }
4265       E->VectorizedValue = NewV;
4266       return NewV;
4267     }
4268     case Instruction::ZExt:
4269     case Instruction::SExt:
4270     case Instruction::FPToUI:
4271     case Instruction::FPToSI:
4272     case Instruction::FPExt:
4273     case Instruction::PtrToInt:
4274     case Instruction::IntToPtr:
4275     case Instruction::SIToFP:
4276     case Instruction::UIToFP:
4277     case Instruction::Trunc:
4278     case Instruction::FPTrunc:
4279     case Instruction::BitCast: {
4280       setInsertPointAfterBundle(E);
4281 
4282       Value *InVec = vectorizeTree(E->getOperand(0));
4283 
4284       if (E->VectorizedValue) {
4285         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4286         return E->VectorizedValue;
4287       }
4288 
4289       auto *CI = cast<CastInst>(VL0);
4290       Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
4291       if (NeedToShuffleReuses) {
4292         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4293                                         E->ReuseShuffleIndices, "shuffle");
4294       }
4295       E->VectorizedValue = V;
4296       ++NumVectorInstructions;
4297       return V;
4298     }
4299     case Instruction::FCmp:
4300     case Instruction::ICmp: {
4301       setInsertPointAfterBundle(E);
4302 
4303       Value *L = vectorizeTree(E->getOperand(0));
4304       Value *R = vectorizeTree(E->getOperand(1));
4305 
4306       if (E->VectorizedValue) {
4307         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4308         return E->VectorizedValue;
4309       }
4310 
4311       CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
4312       Value *V = Builder.CreateCmp(P0, L, R);
4313       propagateIRFlags(V, E->Scalars, VL0);
4314       if (NeedToShuffleReuses) {
4315         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4316                                         E->ReuseShuffleIndices, "shuffle");
4317       }
4318       E->VectorizedValue = V;
4319       ++NumVectorInstructions;
4320       return V;
4321     }
4322     case Instruction::Select: {
4323       setInsertPointAfterBundle(E);
4324 
4325       Value *Cond = vectorizeTree(E->getOperand(0));
4326       Value *True = vectorizeTree(E->getOperand(1));
4327       Value *False = vectorizeTree(E->getOperand(2));
4328 
4329       if (E->VectorizedValue) {
4330         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4331         return E->VectorizedValue;
4332       }
4333 
4334       Value *V = Builder.CreateSelect(Cond, True, False);
4335       if (NeedToShuffleReuses) {
4336         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4337                                         E->ReuseShuffleIndices, "shuffle");
4338       }
4339       E->VectorizedValue = V;
4340       ++NumVectorInstructions;
4341       return V;
4342     }
4343     case Instruction::FNeg: {
4344       setInsertPointAfterBundle(E);
4345 
4346       Value *Op = vectorizeTree(E->getOperand(0));
4347 
4348       if (E->VectorizedValue) {
4349         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4350         return E->VectorizedValue;
4351       }
4352 
4353       Value *V = Builder.CreateUnOp(
4354           static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
4355       propagateIRFlags(V, E->Scalars, VL0);
4356       if (auto *I = dyn_cast<Instruction>(V))
4357         V = propagateMetadata(I, E->Scalars);
4358 
4359       if (NeedToShuffleReuses) {
4360         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4361                                         E->ReuseShuffleIndices, "shuffle");
4362       }
4363       E->VectorizedValue = V;
4364       ++NumVectorInstructions;
4365 
4366       return V;
4367     }
4368     case Instruction::Add:
4369     case Instruction::FAdd:
4370     case Instruction::Sub:
4371     case Instruction::FSub:
4372     case Instruction::Mul:
4373     case Instruction::FMul:
4374     case Instruction::UDiv:
4375     case Instruction::SDiv:
4376     case Instruction::FDiv:
4377     case Instruction::URem:
4378     case Instruction::SRem:
4379     case Instruction::FRem:
4380     case Instruction::Shl:
4381     case Instruction::LShr:
4382     case Instruction::AShr:
4383     case Instruction::And:
4384     case Instruction::Or:
4385     case Instruction::Xor: {
4386       setInsertPointAfterBundle(E);
4387 
4388       Value *LHS = vectorizeTree(E->getOperand(0));
4389       Value *RHS = vectorizeTree(E->getOperand(1));
4390 
4391       if (E->VectorizedValue) {
4392         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4393         return E->VectorizedValue;
4394       }
4395 
4396       Value *V = Builder.CreateBinOp(
4397           static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
4398           RHS);
4399       propagateIRFlags(V, E->Scalars, VL0);
4400       if (auto *I = dyn_cast<Instruction>(V))
4401         V = propagateMetadata(I, E->Scalars);
4402 
4403       if (NeedToShuffleReuses) {
4404         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4405                                         E->ReuseShuffleIndices, "shuffle");
4406       }
4407       E->VectorizedValue = V;
4408       ++NumVectorInstructions;
4409 
4410       return V;
4411     }
4412     case Instruction::Load: {
4413       // Loads are inserted at the head of the tree because we don't want to
4414       // sink them all the way down past store instructions.
4415       bool IsReorder = E->updateStateIfReorder();
4416       if (IsReorder)
4417         VL0 = E->getMainOp();
4418       setInsertPointAfterBundle(E);
4419 
4420       LoadInst *LI = cast<LoadInst>(VL0);
4421       unsigned AS = LI->getPointerAddressSpace();
4422 
4423       Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
4424                                             VecTy->getPointerTo(AS));
4425 
4426       // The pointer operand uses an in-tree scalar so we add the new BitCast to
4427       // ExternalUses list to make sure that an extract will be generated in the
4428       // future.
4429       Value *PO = LI->getPointerOperand();
4430       if (getTreeEntry(PO))
4431         ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
4432 
4433       LI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
4434       Value *V = propagateMetadata(LI, E->Scalars);
4435       if (IsReorder) {
4436         SmallVector<int, 4> Mask;
4437         inversePermutation(E->ReorderIndices, Mask);
4438         V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
4439                                         Mask, "reorder_shuffle");
4440       }
4441       if (NeedToShuffleReuses) {
4442         // TODO: Merge this shuffle with the ReorderShuffleMask.
4443         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4444                                         E->ReuseShuffleIndices, "shuffle");
4445       }
4446       E->VectorizedValue = V;
4447       ++NumVectorInstructions;
4448       return V;
4449     }
4450     case Instruction::Store: {
4451       bool IsReorder = !E->ReorderIndices.empty();
4452       auto *SI = cast<StoreInst>(
4453           IsReorder ? E->Scalars[E->ReorderIndices.front()] : VL0);
4454       unsigned AS = SI->getPointerAddressSpace();
4455 
4456       setInsertPointAfterBundle(E);
4457 
4458       Value *VecValue = vectorizeTree(E->getOperand(0));
4459       if (IsReorder) {
4460         SmallVector<int, 4> Mask(E->ReorderIndices.begin(),
4461                                  E->ReorderIndices.end());
4462         VecValue = Builder.CreateShuffleVector(
4463             VecValue, UndefValue::get(VecValue->getType()), Mask,
4464             "reorder_shuffle");
4465       }
4466       Value *ScalarPtr = SI->getPointerOperand();
4467       Value *VecPtr = Builder.CreateBitCast(
4468           ScalarPtr, VecValue->getType()->getPointerTo(AS));
4469       StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
4470                                                  SI->getAlign());
4471 
4472       // The pointer operand uses an in-tree scalar, so add the new BitCast to
4473       // ExternalUses to make sure that an extract will be generated in the
4474       // future.
4475       if (getTreeEntry(ScalarPtr))
4476         ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
4477 
4478       Value *V = propagateMetadata(ST, E->Scalars);
4479       if (NeedToShuffleReuses) {
4480         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4481                                         E->ReuseShuffleIndices, "shuffle");
4482       }
4483       E->VectorizedValue = V;
4484       ++NumVectorInstructions;
4485       return V;
4486     }
4487     case Instruction::GetElementPtr: {
4488       setInsertPointAfterBundle(E);
4489 
4490       Value *Op0 = vectorizeTree(E->getOperand(0));
4491 
4492       std::vector<Value *> OpVecs;
4493       for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
4494            ++j) {
4495         ValueList &VL = E->getOperand(j);
4496         // Need to cast all elements to the same type before vectorization to
4497         // avoid crash.
4498         Type *VL0Ty = VL0->getOperand(j)->getType();
4499         Type *Ty = llvm::all_of(
4500                        VL, [VL0Ty](Value *V) { return VL0Ty == V->getType(); })
4501                        ? VL0Ty
4502                        : DL->getIndexType(cast<GetElementPtrInst>(VL0)
4503                                               ->getPointerOperandType()
4504                                               ->getScalarType());
4505         for (Value *&V : VL) {
4506           auto *CI = cast<ConstantInt>(V);
4507           V = ConstantExpr::getIntegerCast(CI, Ty,
4508                                            CI->getValue().isSignBitSet());
4509         }
4510         Value *OpVec = vectorizeTree(VL);
4511         OpVecs.push_back(OpVec);
4512       }
4513 
4514       Value *V = Builder.CreateGEP(
4515           cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
4516       if (Instruction *I = dyn_cast<Instruction>(V))
4517         V = propagateMetadata(I, E->Scalars);
4518 
4519       if (NeedToShuffleReuses) {
4520         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4521                                         E->ReuseShuffleIndices, "shuffle");
4522       }
4523       E->VectorizedValue = V;
4524       ++NumVectorInstructions;
4525 
4526       return V;
4527     }
4528     case Instruction::Call: {
4529       CallInst *CI = cast<CallInst>(VL0);
4530       setInsertPointAfterBundle(E);
4531 
4532       Intrinsic::ID IID  = Intrinsic::not_intrinsic;
4533       if (Function *FI = CI->getCalledFunction())
4534         IID = FI->getIntrinsicID();
4535 
4536       Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
4537 
4538       auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
4539       bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
4540                           VecCallCosts.first <= VecCallCosts.second;
4541 
4542       Value *ScalarArg = nullptr;
4543       std::vector<Value *> OpVecs;
4544       for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
4545         ValueList OpVL;
4546         // Some intrinsics have scalar arguments. This argument should not be
4547         // vectorized.
4548         if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
4549           CallInst *CEI = cast<CallInst>(VL0);
4550           ScalarArg = CEI->getArgOperand(j);
4551           OpVecs.push_back(CEI->getArgOperand(j));
4552           continue;
4553         }
4554 
4555         Value *OpVec = vectorizeTree(E->getOperand(j));
4556         LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
4557         OpVecs.push_back(OpVec);
4558       }
4559 
4560       Function *CF;
4561       if (!UseIntrinsic) {
4562         VFShape Shape =
4563             VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
4564                                   VecTy->getNumElements())),
4565                          false /*HasGlobalPred*/);
4566         CF = VFDatabase(*CI).getVectorizedFunction(Shape);
4567       } else {
4568         Type *Tys[] = {FixedVectorType::get(CI->getType(), E->Scalars.size())};
4569         CF = Intrinsic::getDeclaration(F->getParent(), ID, Tys);
4570       }
4571 
4572       SmallVector<OperandBundleDef, 1> OpBundles;
4573       CI->getOperandBundlesAsDefs(OpBundles);
4574       Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
4575 
4576       // The scalar argument uses an in-tree scalar so we add the new vectorized
4577       // call to ExternalUses list to make sure that an extract will be
4578       // generated in the future.
4579       if (ScalarArg && getTreeEntry(ScalarArg))
4580         ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
4581 
4582       propagateIRFlags(V, E->Scalars, VL0);
4583       if (NeedToShuffleReuses) {
4584         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4585                                         E->ReuseShuffleIndices, "shuffle");
4586       }
4587       E->VectorizedValue = V;
4588       ++NumVectorInstructions;
4589       return V;
4590     }
4591     case Instruction::ShuffleVector: {
4592       assert(E->isAltShuffle() &&
4593              ((Instruction::isBinaryOp(E->getOpcode()) &&
4594                Instruction::isBinaryOp(E->getAltOpcode())) ||
4595               (Instruction::isCast(E->getOpcode()) &&
4596                Instruction::isCast(E->getAltOpcode()))) &&
4597              "Invalid Shuffle Vector Operand");
4598 
4599       Value *LHS = nullptr, *RHS = nullptr;
4600       if (Instruction::isBinaryOp(E->getOpcode())) {
4601         setInsertPointAfterBundle(E);
4602         LHS = vectorizeTree(E->getOperand(0));
4603         RHS = vectorizeTree(E->getOperand(1));
4604       } else {
4605         setInsertPointAfterBundle(E);
4606         LHS = vectorizeTree(E->getOperand(0));
4607       }
4608 
4609       if (E->VectorizedValue) {
4610         LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
4611         return E->VectorizedValue;
4612       }
4613 
4614       Value *V0, *V1;
4615       if (Instruction::isBinaryOp(E->getOpcode())) {
4616         V0 = Builder.CreateBinOp(
4617             static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
4618         V1 = Builder.CreateBinOp(
4619             static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
4620       } else {
4621         V0 = Builder.CreateCast(
4622             static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
4623         V1 = Builder.CreateCast(
4624             static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
4625       }
4626 
4627       // Create shuffle to take alternate operations from the vector.
4628       // Also, gather up main and alt scalar ops to propagate IR flags to
4629       // each vector operation.
4630       ValueList OpScalars, AltScalars;
4631       unsigned e = E->Scalars.size();
4632       SmallVector<int, 8> Mask(e);
4633       for (unsigned i = 0; i < e; ++i) {
4634         auto *OpInst = cast<Instruction>(E->Scalars[i]);
4635         assert(E->isOpcodeOrAlt(OpInst) && "Unexpected main/alternate opcode");
4636         if (OpInst->getOpcode() == E->getAltOpcode()) {
4637           Mask[i] = e + i;
4638           AltScalars.push_back(E->Scalars[i]);
4639         } else {
4640           Mask[i] = i;
4641           OpScalars.push_back(E->Scalars[i]);
4642         }
4643       }
4644 
4645       propagateIRFlags(V0, OpScalars);
4646       propagateIRFlags(V1, AltScalars);
4647 
4648       Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
4649       if (Instruction *I = dyn_cast<Instruction>(V))
4650         V = propagateMetadata(I, E->Scalars);
4651       if (NeedToShuffleReuses) {
4652         V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
4653                                         E->ReuseShuffleIndices, "shuffle");
4654       }
4655       E->VectorizedValue = V;
4656       ++NumVectorInstructions;
4657 
4658       return V;
4659     }
4660     default:
4661     llvm_unreachable("unknown inst");
4662   }
4663   return nullptr;
4664 }
4665 
4666 Value *BoUpSLP::vectorizeTree() {
4667   ExtraValueToDebugLocsMap ExternallyUsedValues;
4668   return vectorizeTree(ExternallyUsedValues);
4669 }
4670 
4671 Value *
4672 BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4673   // All blocks must be scheduled before any instructions are inserted.
4674   for (auto &BSIter : BlocksSchedules) {
4675     scheduleBlock(BSIter.second.get());
4676   }
4677 
4678   Builder.SetInsertPoint(&F->getEntryBlock().front());
4679   auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
4680 
4681   // If the vectorized tree can be rewritten in a smaller type, we truncate the
4682   // vectorized root. InstCombine will then rewrite the entire expression. We
4683   // sign extend the extracted values below.
4684   auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
4685   if (MinBWs.count(ScalarRoot)) {
4686     if (auto *I = dyn_cast<Instruction>(VectorRoot))
4687       Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
4688     auto BundleWidth = VectorizableTree[0]->Scalars.size();
4689     auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
4690     auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
4691     auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
4692     VectorizableTree[0]->VectorizedValue = Trunc;
4693   }
4694 
4695   LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
4696                     << " values .\n");
4697 
4698   // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
4699   // specified by ScalarType.
4700   auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
4701     if (!MinBWs.count(ScalarRoot))
4702       return Ex;
4703     if (MinBWs[ScalarRoot].second)
4704       return Builder.CreateSExt(Ex, ScalarType);
4705     return Builder.CreateZExt(Ex, ScalarType);
4706   };
4707 
4708   // Extract all of the elements with the external uses.
4709   for (const auto &ExternalUse : ExternalUses) {
4710     Value *Scalar = ExternalUse.Scalar;
4711     llvm::User *User = ExternalUse.User;
4712 
4713     // Skip users that we already RAUW. This happens when one instruction
4714     // has multiple uses of the same value.
4715     if (User && !is_contained(Scalar->users(), User))
4716       continue;
4717     TreeEntry *E = getTreeEntry(Scalar);
4718     assert(E && "Invalid scalar");
4719     assert(E->State == TreeEntry::Vectorize && "Extracting from a gather list");
4720 
4721     Value *Vec = E->VectorizedValue;
4722     assert(Vec && "Can't find vectorizable value");
4723 
4724     Value *Lane = Builder.getInt32(ExternalUse.Lane);
4725     // If User == nullptr, the Scalar is used as extra arg. Generate
4726     // ExtractElement instruction and update the record for this scalar in
4727     // ExternallyUsedValues.
4728     if (!User) {
4729       assert(ExternallyUsedValues.count(Scalar) &&
4730              "Scalar with nullptr as an external user must be registered in "
4731              "ExternallyUsedValues map");
4732       if (auto *VecI = dyn_cast<Instruction>(Vec)) {
4733         Builder.SetInsertPoint(VecI->getParent(),
4734                                std::next(VecI->getIterator()));
4735       } else {
4736         Builder.SetInsertPoint(&F->getEntryBlock().front());
4737       }
4738       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4739       Ex = extend(ScalarRoot, Ex, Scalar->getType());
4740       CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
4741       auto &Locs = ExternallyUsedValues[Scalar];
4742       ExternallyUsedValues.insert({Ex, Locs});
4743       ExternallyUsedValues.erase(Scalar);
4744       // Required to update internally referenced instructions.
4745       Scalar->replaceAllUsesWith(Ex);
4746       continue;
4747     }
4748 
4749     // Generate extracts for out-of-tree users.
4750     // Find the insertion point for the extractelement lane.
4751     if (auto *VecI = dyn_cast<Instruction>(Vec)) {
4752       if (PHINode *PH = dyn_cast<PHINode>(User)) {
4753         for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
4754           if (PH->getIncomingValue(i) == Scalar) {
4755             Instruction *IncomingTerminator =
4756                 PH->getIncomingBlock(i)->getTerminator();
4757             if (isa<CatchSwitchInst>(IncomingTerminator)) {
4758               Builder.SetInsertPoint(VecI->getParent(),
4759                                      std::next(VecI->getIterator()));
4760             } else {
4761               Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
4762             }
4763             Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4764             Ex = extend(ScalarRoot, Ex, Scalar->getType());
4765             CSEBlocks.insert(PH->getIncomingBlock(i));
4766             PH->setOperand(i, Ex);
4767           }
4768         }
4769       } else {
4770         Builder.SetInsertPoint(cast<Instruction>(User));
4771         Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4772         Ex = extend(ScalarRoot, Ex, Scalar->getType());
4773         CSEBlocks.insert(cast<Instruction>(User)->getParent());
4774         User->replaceUsesOfWith(Scalar, Ex);
4775       }
4776     } else {
4777       Builder.SetInsertPoint(&F->getEntryBlock().front());
4778       Value *Ex = Builder.CreateExtractElement(Vec, Lane);
4779       Ex = extend(ScalarRoot, Ex, Scalar->getType());
4780       CSEBlocks.insert(&F->getEntryBlock());
4781       User->replaceUsesOfWith(Scalar, Ex);
4782     }
4783 
4784     LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
4785   }
4786 
4787   // For each vectorized value:
4788   for (auto &TEPtr : VectorizableTree) {
4789     TreeEntry *Entry = TEPtr.get();
4790 
4791     // No need to handle users of gathered values.
4792     if (Entry->State == TreeEntry::NeedToGather)
4793       continue;
4794 
4795     assert(Entry->VectorizedValue && "Can't find vectorizable value");
4796 
4797     // For each lane:
4798     for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4799       Value *Scalar = Entry->Scalars[Lane];
4800 
4801 #ifndef NDEBUG
4802       Type *Ty = Scalar->getType();
4803       if (!Ty->isVoidTy()) {
4804         for (User *U : Scalar->users()) {
4805           LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
4806 
4807           // It is legal to delete users in the ignorelist.
4808           assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
4809                  "Deleting out-of-tree value");
4810         }
4811       }
4812 #endif
4813       LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
4814       eraseInstruction(cast<Instruction>(Scalar));
4815     }
4816   }
4817 
4818   Builder.ClearInsertionPoint();
4819   InstrElementSize.clear();
4820 
4821   return VectorizableTree[0]->VectorizedValue;
4822 }
4823 
4824 void BoUpSLP::optimizeGatherSequence() {
4825   LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
4826                     << " gather sequences instructions.\n");
4827   // LICM InsertElementInst sequences.
4828   for (Instruction *I : GatherSeq) {
4829     if (isDeleted(I))
4830       continue;
4831 
4832     // Check if this block is inside a loop.
4833     Loop *L = LI->getLoopFor(I->getParent());
4834     if (!L)
4835       continue;
4836 
4837     // Check if it has a preheader.
4838     BasicBlock *PreHeader = L->getLoopPreheader();
4839     if (!PreHeader)
4840       continue;
4841 
4842     // If the vector or the element that we insert into it are
4843     // instructions that are defined in this basic block then we can't
4844     // hoist this instruction.
4845     auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
4846     auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
4847     if (Op0 && L->contains(Op0))
4848       continue;
4849     if (Op1 && L->contains(Op1))
4850       continue;
4851 
4852     // We can hoist this instruction. Move it to the pre-header.
4853     I->moveBefore(PreHeader->getTerminator());
4854   }
4855 
4856   // Make a list of all reachable blocks in our CSE queue.
4857   SmallVector<const DomTreeNode *, 8> CSEWorkList;
4858   CSEWorkList.reserve(CSEBlocks.size());
4859   for (BasicBlock *BB : CSEBlocks)
4860     if (DomTreeNode *N = DT->getNode(BB)) {
4861       assert(DT->isReachableFromEntry(N));
4862       CSEWorkList.push_back(N);
4863     }
4864 
4865   // Sort blocks by domination. This ensures we visit a block after all blocks
4866   // dominating it are visited.
4867   llvm::stable_sort(CSEWorkList,
4868                     [this](const DomTreeNode *A, const DomTreeNode *B) {
4869                       return DT->properlyDominates(A, B);
4870                     });
4871 
4872   // Perform O(N^2) search over the gather sequences and merge identical
4873   // instructions. TODO: We can further optimize this scan if we split the
4874   // instructions into different buckets based on the insert lane.
4875   SmallVector<Instruction *, 16> Visited;
4876   for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
4877     assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
4878            "Worklist not sorted properly!");
4879     BasicBlock *BB = (*I)->getBlock();
4880     // For all instructions in blocks containing gather sequences:
4881     for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
4882       Instruction *In = &*it++;
4883       if (isDeleted(In))
4884         continue;
4885       if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
4886         continue;
4887 
4888       // Check if we can replace this instruction with any of the
4889       // visited instructions.
4890       for (Instruction *v : Visited) {
4891         if (In->isIdenticalTo(v) &&
4892             DT->dominates(v->getParent(), In->getParent())) {
4893           In->replaceAllUsesWith(v);
4894           eraseInstruction(In);
4895           In = nullptr;
4896           break;
4897         }
4898       }
4899       if (In) {
4900         assert(!is_contained(Visited, In));
4901         Visited.push_back(In);
4902       }
4903     }
4904   }
4905   CSEBlocks.clear();
4906   GatherSeq.clear();
4907 }
4908 
4909 // Groups the instructions to a bundle (which is then a single scheduling entity)
4910 // and schedules instructions until the bundle gets ready.
4911 Optional<BoUpSLP::ScheduleData *>
4912 BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
4913                                             const InstructionsState &S) {
4914   if (isa<PHINode>(S.OpValue))
4915     return nullptr;
4916 
4917   // Initialize the instruction bundle.
4918   Instruction *OldScheduleEnd = ScheduleEnd;
4919   ScheduleData *PrevInBundle = nullptr;
4920   ScheduleData *Bundle = nullptr;
4921   bool ReSchedule = false;
4922   LLVM_DEBUG(dbgs() << "SLP:  bundle: " << *S.OpValue << "\n");
4923 
4924   // Make sure that the scheduling region contains all
4925   // instructions of the bundle.
4926   for (Value *V : VL) {
4927     if (!extendSchedulingRegion(V, S))
4928       return None;
4929   }
4930 
4931   for (Value *V : VL) {
4932     ScheduleData *BundleMember = getScheduleData(V);
4933     assert(BundleMember &&
4934            "no ScheduleData for bundle member (maybe not in same basic block)");
4935     if (BundleMember->IsScheduled) {
4936       // A bundle member was scheduled as single instruction before and now
4937       // needs to be scheduled as part of the bundle. We just get rid of the
4938       // existing schedule.
4939       LLVM_DEBUG(dbgs() << "SLP:  reset schedule because " << *BundleMember
4940                         << " was already scheduled\n");
4941       ReSchedule = true;
4942     }
4943     assert(BundleMember->isSchedulingEntity() &&
4944            "bundle member already part of other bundle");
4945     if (PrevInBundle) {
4946       PrevInBundle->NextInBundle = BundleMember;
4947     } else {
4948       Bundle = BundleMember;
4949     }
4950     BundleMember->UnscheduledDepsInBundle = 0;
4951     Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
4952 
4953     // Group the instructions to a bundle.
4954     BundleMember->FirstInBundle = Bundle;
4955     PrevInBundle = BundleMember;
4956   }
4957   if (ScheduleEnd != OldScheduleEnd) {
4958     // The scheduling region got new instructions at the lower end (or it is a
4959     // new region for the first bundle). This makes it necessary to
4960     // recalculate all dependencies.
4961     // It is seldom that this needs to be done a second time after adding the
4962     // initial bundle to the region.
4963     for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
4964       doForAllOpcodes(I, [](ScheduleData *SD) {
4965         SD->clearDependencies();
4966       });
4967     }
4968     ReSchedule = true;
4969   }
4970   if (ReSchedule) {
4971     resetSchedule();
4972     initialFillReadyList(ReadyInsts);
4973   }
4974   assert(Bundle && "Failed to find schedule bundle");
4975 
4976   LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
4977                     << BB->getName() << "\n");
4978 
4979   calculateDependencies(Bundle, true, SLP);
4980 
4981   // Now try to schedule the new bundle. As soon as the bundle is "ready" it
4982   // means that there are no cyclic dependencies and we can schedule it.
4983   // Note that's important that we don't "schedule" the bundle yet (see
4984   // cancelScheduling).
4985   while (!Bundle->isReady() && !ReadyInsts.empty()) {
4986 
4987     ScheduleData *pickedSD = ReadyInsts.back();
4988     ReadyInsts.pop_back();
4989 
4990     if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
4991       schedule(pickedSD, ReadyInsts);
4992     }
4993   }
4994   if (!Bundle->isReady()) {
4995     cancelScheduling(VL, S.OpValue);
4996     return None;
4997   }
4998   return Bundle;
4999 }
5000 
5001 void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
5002                                                 Value *OpValue) {
5003   if (isa<PHINode>(OpValue))
5004     return;
5005 
5006   ScheduleData *Bundle = getScheduleData(OpValue);
5007   LLVM_DEBUG(dbgs() << "SLP:  cancel scheduling of " << *Bundle << "\n");
5008   assert(!Bundle->IsScheduled &&
5009          "Can't cancel bundle which is already scheduled");
5010   assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
5011          "tried to unbundle something which is not a bundle");
5012 
5013   // Un-bundle: make single instructions out of the bundle.
5014   ScheduleData *BundleMember = Bundle;
5015   while (BundleMember) {
5016     assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
5017     BundleMember->FirstInBundle = BundleMember;
5018     ScheduleData *Next = BundleMember->NextInBundle;
5019     BundleMember->NextInBundle = nullptr;
5020     BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
5021     if (BundleMember->UnscheduledDepsInBundle == 0) {
5022       ReadyInsts.insert(BundleMember);
5023     }
5024     BundleMember = Next;
5025   }
5026 }
5027 
5028 BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
5029   // Allocate a new ScheduleData for the instruction.
5030   if (ChunkPos >= ChunkSize) {
5031     ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
5032     ChunkPos = 0;
5033   }
5034   return &(ScheduleDataChunks.back()[ChunkPos++]);
5035 }
5036 
5037 bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
5038                                                       const InstructionsState &S) {
5039   if (getScheduleData(V, isOneOf(S, V)))
5040     return true;
5041   Instruction *I = dyn_cast<Instruction>(V);
5042   assert(I && "bundle member must be an instruction");
5043   assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
5044   auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
5045     ScheduleData *ISD = getScheduleData(I);
5046     if (!ISD)
5047       return false;
5048     assert(isInSchedulingRegion(ISD) &&
5049            "ScheduleData not in scheduling region");
5050     ScheduleData *SD = allocateScheduleDataChunks();
5051     SD->Inst = I;
5052     SD->init(SchedulingRegionID, S.OpValue);
5053     ExtraScheduleDataMap[I][S.OpValue] = SD;
5054     return true;
5055   };
5056   if (CheckSheduleForI(I))
5057     return true;
5058   if (!ScheduleStart) {
5059     // It's the first instruction in the new region.
5060     initScheduleData(I, I->getNextNode(), nullptr, nullptr);
5061     ScheduleStart = I;
5062     ScheduleEnd = I->getNextNode();
5063     if (isOneOf(S, I) != I)
5064       CheckSheduleForI(I);
5065     assert(ScheduleEnd && "tried to vectorize a terminator?");
5066     LLVM_DEBUG(dbgs() << "SLP:  initialize schedule region to " << *I << "\n");
5067     return true;
5068   }
5069   // Search up and down at the same time, because we don't know if the new
5070   // instruction is above or below the existing scheduling region.
5071   BasicBlock::reverse_iterator UpIter =
5072       ++ScheduleStart->getIterator().getReverse();
5073   BasicBlock::reverse_iterator UpperEnd = BB->rend();
5074   BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
5075   BasicBlock::iterator LowerEnd = BB->end();
5076   while (true) {
5077     if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
5078       LLVM_DEBUG(dbgs() << "SLP:  exceeded schedule region size limit\n");
5079       return false;
5080     }
5081 
5082     if (UpIter != UpperEnd) {
5083       if (&*UpIter == I) {
5084         initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
5085         ScheduleStart = I;
5086         if (isOneOf(S, I) != I)
5087           CheckSheduleForI(I);
5088         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region start to " << *I
5089                           << "\n");
5090         return true;
5091       }
5092       ++UpIter;
5093     }
5094     if (DownIter != LowerEnd) {
5095       if (&*DownIter == I) {
5096         initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
5097                          nullptr);
5098         ScheduleEnd = I->getNextNode();
5099         if (isOneOf(S, I) != I)
5100           CheckSheduleForI(I);
5101         assert(ScheduleEnd && "tried to vectorize a terminator?");
5102         LLVM_DEBUG(dbgs() << "SLP:  extend schedule region end to " << *I
5103                           << "\n");
5104         return true;
5105       }
5106       ++DownIter;
5107     }
5108     assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
5109            "instruction not found in block");
5110   }
5111   return true;
5112 }
5113 
5114 void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
5115                                                 Instruction *ToI,
5116                                                 ScheduleData *PrevLoadStore,
5117                                                 ScheduleData *NextLoadStore) {
5118   ScheduleData *CurrentLoadStore = PrevLoadStore;
5119   for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
5120     ScheduleData *SD = ScheduleDataMap[I];
5121     if (!SD) {
5122       SD = allocateScheduleDataChunks();
5123       ScheduleDataMap[I] = SD;
5124       SD->Inst = I;
5125     }
5126     assert(!isInSchedulingRegion(SD) &&
5127            "new ScheduleData already in scheduling region");
5128     SD->init(SchedulingRegionID, I);
5129 
5130     if (I->mayReadOrWriteMemory() &&
5131         (!isa<IntrinsicInst>(I) ||
5132          cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect)) {
5133       // Update the linked list of memory accessing instructions.
5134       if (CurrentLoadStore) {
5135         CurrentLoadStore->NextLoadStore = SD;
5136       } else {
5137         FirstLoadStoreInRegion = SD;
5138       }
5139       CurrentLoadStore = SD;
5140     }
5141   }
5142   if (NextLoadStore) {
5143     if (CurrentLoadStore)
5144       CurrentLoadStore->NextLoadStore = NextLoadStore;
5145   } else {
5146     LastLoadStoreInRegion = CurrentLoadStore;
5147   }
5148 }
5149 
5150 void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
5151                                                      bool InsertInReadyList,
5152                                                      BoUpSLP *SLP) {
5153   assert(SD->isSchedulingEntity());
5154 
5155   SmallVector<ScheduleData *, 10> WorkList;
5156   WorkList.push_back(SD);
5157 
5158   while (!WorkList.empty()) {
5159     ScheduleData *SD = WorkList.back();
5160     WorkList.pop_back();
5161 
5162     ScheduleData *BundleMember = SD;
5163     while (BundleMember) {
5164       assert(isInSchedulingRegion(BundleMember));
5165       if (!BundleMember->hasValidDependencies()) {
5166 
5167         LLVM_DEBUG(dbgs() << "SLP:       update deps of " << *BundleMember
5168                           << "\n");
5169         BundleMember->Dependencies = 0;
5170         BundleMember->resetUnscheduledDeps();
5171 
5172         // Handle def-use chain dependencies.
5173         if (BundleMember->OpValue != BundleMember->Inst) {
5174           ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
5175           if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
5176             BundleMember->Dependencies++;
5177             ScheduleData *DestBundle = UseSD->FirstInBundle;
5178             if (!DestBundle->IsScheduled)
5179               BundleMember->incrementUnscheduledDeps(1);
5180             if (!DestBundle->hasValidDependencies())
5181               WorkList.push_back(DestBundle);
5182           }
5183         } else {
5184           for (User *U : BundleMember->Inst->users()) {
5185             if (isa<Instruction>(U)) {
5186               ScheduleData *UseSD = getScheduleData(U);
5187               if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
5188                 BundleMember->Dependencies++;
5189                 ScheduleData *DestBundle = UseSD->FirstInBundle;
5190                 if (!DestBundle->IsScheduled)
5191                   BundleMember->incrementUnscheduledDeps(1);
5192                 if (!DestBundle->hasValidDependencies())
5193                   WorkList.push_back(DestBundle);
5194               }
5195             } else {
5196               // I'm not sure if this can ever happen. But we need to be safe.
5197               // This lets the instruction/bundle never be scheduled and
5198               // eventually disable vectorization.
5199               BundleMember->Dependencies++;
5200               BundleMember->incrementUnscheduledDeps(1);
5201             }
5202           }
5203         }
5204 
5205         // Handle the memory dependencies.
5206         ScheduleData *DepDest = BundleMember->NextLoadStore;
5207         if (DepDest) {
5208           Instruction *SrcInst = BundleMember->Inst;
5209           MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
5210           bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
5211           unsigned numAliased = 0;
5212           unsigned DistToSrc = 1;
5213 
5214           while (DepDest) {
5215             assert(isInSchedulingRegion(DepDest));
5216 
5217             // We have two limits to reduce the complexity:
5218             // 1) AliasedCheckLimit: It's a small limit to reduce calls to
5219             //    SLP->isAliased (which is the expensive part in this loop).
5220             // 2) MaxMemDepDistance: It's for very large blocks and it aborts
5221             //    the whole loop (even if the loop is fast, it's quadratic).
5222             //    It's important for the loop break condition (see below) to
5223             //    check this limit even between two read-only instructions.
5224             if (DistToSrc >= MaxMemDepDistance ||
5225                     ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
5226                      (numAliased >= AliasedCheckLimit ||
5227                       SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
5228 
5229               // We increment the counter only if the locations are aliased
5230               // (instead of counting all alias checks). This gives a better
5231               // balance between reduced runtime and accurate dependencies.
5232               numAliased++;
5233 
5234               DepDest->MemoryDependencies.push_back(BundleMember);
5235               BundleMember->Dependencies++;
5236               ScheduleData *DestBundle = DepDest->FirstInBundle;
5237               if (!DestBundle->IsScheduled) {
5238                 BundleMember->incrementUnscheduledDeps(1);
5239               }
5240               if (!DestBundle->hasValidDependencies()) {
5241                 WorkList.push_back(DestBundle);
5242               }
5243             }
5244             DepDest = DepDest->NextLoadStore;
5245 
5246             // Example, explaining the loop break condition: Let's assume our
5247             // starting instruction is i0 and MaxMemDepDistance = 3.
5248             //
5249             //                      +--------v--v--v
5250             //             i0,i1,i2,i3,i4,i5,i6,i7,i8
5251             //             +--------^--^--^
5252             //
5253             // MaxMemDepDistance let us stop alias-checking at i3 and we add
5254             // dependencies from i0 to i3,i4,.. (even if they are not aliased).
5255             // Previously we already added dependencies from i3 to i6,i7,i8
5256             // (because of MaxMemDepDistance). As we added a dependency from
5257             // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
5258             // and we can abort this loop at i6.
5259             if (DistToSrc >= 2 * MaxMemDepDistance)
5260               break;
5261             DistToSrc++;
5262           }
5263         }
5264       }
5265       BundleMember = BundleMember->NextInBundle;
5266     }
5267     if (InsertInReadyList && SD->isReady()) {
5268       ReadyInsts.push_back(SD);
5269       LLVM_DEBUG(dbgs() << "SLP:     gets ready on update: " << *SD->Inst
5270                         << "\n");
5271     }
5272   }
5273 }
5274 
5275 void BoUpSLP::BlockScheduling::resetSchedule() {
5276   assert(ScheduleStart &&
5277          "tried to reset schedule on block which has not been scheduled");
5278   for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
5279     doForAllOpcodes(I, [&](ScheduleData *SD) {
5280       assert(isInSchedulingRegion(SD) &&
5281              "ScheduleData not in scheduling region");
5282       SD->IsScheduled = false;
5283       SD->resetUnscheduledDeps();
5284     });
5285   }
5286   ReadyInsts.clear();
5287 }
5288 
5289 void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
5290   if (!BS->ScheduleStart)
5291     return;
5292 
5293   LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
5294 
5295   BS->resetSchedule();
5296 
5297   // For the real scheduling we use a more sophisticated ready-list: it is
5298   // sorted by the original instruction location. This lets the final schedule
5299   // be as  close as possible to the original instruction order.
5300   struct ScheduleDataCompare {
5301     bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
5302       return SD2->SchedulingPriority < SD1->SchedulingPriority;
5303     }
5304   };
5305   std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
5306 
5307   // Ensure that all dependency data is updated and fill the ready-list with
5308   // initial instructions.
5309   int Idx = 0;
5310   int NumToSchedule = 0;
5311   for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
5312        I = I->getNextNode()) {
5313     BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
5314       assert(SD->isPartOfBundle() ==
5315                  (getTreeEntry(SD->Inst) != nullptr) &&
5316              "scheduler and vectorizer bundle mismatch");
5317       SD->FirstInBundle->SchedulingPriority = Idx++;
5318       if (SD->isSchedulingEntity()) {
5319         BS->calculateDependencies(SD, false, this);
5320         NumToSchedule++;
5321       }
5322     });
5323   }
5324   BS->initialFillReadyList(ReadyInsts);
5325 
5326   Instruction *LastScheduledInst = BS->ScheduleEnd;
5327 
5328   // Do the "real" scheduling.
5329   while (!ReadyInsts.empty()) {
5330     ScheduleData *picked = *ReadyInsts.begin();
5331     ReadyInsts.erase(ReadyInsts.begin());
5332 
5333     // Move the scheduled instruction(s) to their dedicated places, if not
5334     // there yet.
5335     ScheduleData *BundleMember = picked;
5336     while (BundleMember) {
5337       Instruction *pickedInst = BundleMember->Inst;
5338       if (LastScheduledInst->getNextNode() != pickedInst) {
5339         BS->BB->getInstList().remove(pickedInst);
5340         BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
5341                                      pickedInst);
5342       }
5343       LastScheduledInst = pickedInst;
5344       BundleMember = BundleMember->NextInBundle;
5345     }
5346 
5347     BS->schedule(picked, ReadyInsts);
5348     NumToSchedule--;
5349   }
5350   assert(NumToSchedule == 0 && "could not schedule all instructions");
5351 
5352   // Avoid duplicate scheduling of the block.
5353   BS->ScheduleStart = nullptr;
5354 }
5355 
5356 unsigned BoUpSLP::getVectorElementSize(Value *V) {
5357   // If V is a store, just return the width of the stored value without
5358   // traversing the expression tree. This is the common case.
5359   if (auto *Store = dyn_cast<StoreInst>(V))
5360     return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
5361 
5362   auto E = InstrElementSize.find(V);
5363   if (E != InstrElementSize.end())
5364     return E->second;
5365 
5366   // If V is not a store, we can traverse the expression tree to find loads
5367   // that feed it. The type of the loaded value may indicate a more suitable
5368   // width than V's type. We want to base the vector element size on the width
5369   // of memory operations where possible.
5370   SmallVector<Instruction *, 16> Worklist;
5371   SmallPtrSet<Instruction *, 16> Visited;
5372   if (auto *I = dyn_cast<Instruction>(V)) {
5373     Worklist.push_back(I);
5374     Visited.insert(I);
5375   }
5376 
5377   // Traverse the expression tree in bottom-up order looking for loads. If we
5378   // encounter an instruction we don't yet handle, we give up.
5379   auto MaxWidth = 0u;
5380   auto FoundUnknownInst = false;
5381   while (!Worklist.empty() && !FoundUnknownInst) {
5382     auto *I = Worklist.pop_back_val();
5383 
5384     // We should only be looking at scalar instructions here. If the current
5385     // instruction has a vector type, give up.
5386     auto *Ty = I->getType();
5387     if (isa<VectorType>(Ty))
5388       FoundUnknownInst = true;
5389 
5390     // If the current instruction is a load, update MaxWidth to reflect the
5391     // width of the loaded value.
5392     else if (isa<LoadInst>(I))
5393       MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
5394 
5395     // Otherwise, we need to visit the operands of the instruction. We only
5396     // handle the interesting cases from buildTree here. If an operand is an
5397     // instruction we haven't yet visited, we add it to the worklist.
5398     else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
5399              isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
5400       for (Use &U : I->operands())
5401         if (auto *J = dyn_cast<Instruction>(U.get()))
5402           if (Visited.insert(J).second)
5403             Worklist.push_back(J);
5404     }
5405 
5406     // If we don't yet handle the instruction, give up.
5407     else
5408       FoundUnknownInst = true;
5409   }
5410 
5411   int Width = MaxWidth;
5412   // If we didn't encounter a memory access in the expression tree, or if we
5413   // gave up for some reason, just return the width of V. Otherwise, return the
5414   // maximum width we found.
5415   if (!MaxWidth || FoundUnknownInst)
5416     Width = DL->getTypeSizeInBits(V->getType());
5417 
5418   for (Instruction *I : Visited)
5419     InstrElementSize[I] = Width;
5420 
5421   return Width;
5422 }
5423 
5424 // Determine if a value V in a vectorizable expression Expr can be demoted to a
5425 // smaller type with a truncation. We collect the values that will be demoted
5426 // in ToDemote and additional roots that require investigating in Roots.
5427 static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
5428                                   SmallVectorImpl<Value *> &ToDemote,
5429                                   SmallVectorImpl<Value *> &Roots) {
5430   // We can always demote constants.
5431   if (isa<Constant>(V)) {
5432     ToDemote.push_back(V);
5433     return true;
5434   }
5435 
5436   // If the value is not an instruction in the expression with only one use, it
5437   // cannot be demoted.
5438   auto *I = dyn_cast<Instruction>(V);
5439   if (!I || !I->hasOneUse() || !Expr.count(I))
5440     return false;
5441 
5442   switch (I->getOpcode()) {
5443 
5444   // We can always demote truncations and extensions. Since truncations can
5445   // seed additional demotion, we save the truncated value.
5446   case Instruction::Trunc:
5447     Roots.push_back(I->getOperand(0));
5448     break;
5449   case Instruction::ZExt:
5450   case Instruction::SExt:
5451     break;
5452 
5453   // We can demote certain binary operations if we can demote both of their
5454   // operands.
5455   case Instruction::Add:
5456   case Instruction::Sub:
5457   case Instruction::Mul:
5458   case Instruction::And:
5459   case Instruction::Or:
5460   case Instruction::Xor:
5461     if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
5462         !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
5463       return false;
5464     break;
5465 
5466   // We can demote selects if we can demote their true and false values.
5467   case Instruction::Select: {
5468     SelectInst *SI = cast<SelectInst>(I);
5469     if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
5470         !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
5471       return false;
5472     break;
5473   }
5474 
5475   // We can demote phis if we can demote all their incoming operands. Note that
5476   // we don't need to worry about cycles since we ensure single use above.
5477   case Instruction::PHI: {
5478     PHINode *PN = cast<PHINode>(I);
5479     for (Value *IncValue : PN->incoming_values())
5480       if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
5481         return false;
5482     break;
5483   }
5484 
5485   // Otherwise, conservatively give up.
5486   default:
5487     return false;
5488   }
5489 
5490   // Record the value that we can demote.
5491   ToDemote.push_back(V);
5492   return true;
5493 }
5494 
5495 void BoUpSLP::computeMinimumValueSizes() {
5496   // If there are no external uses, the expression tree must be rooted by a
5497   // store. We can't demote in-memory values, so there is nothing to do here.
5498   if (ExternalUses.empty())
5499     return;
5500 
5501   // We only attempt to truncate integer expressions.
5502   auto &TreeRoot = VectorizableTree[0]->Scalars;
5503   auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
5504   if (!TreeRootIT)
5505     return;
5506 
5507   // If the expression is not rooted by a store, these roots should have
5508   // external uses. We will rely on InstCombine to rewrite the expression in
5509   // the narrower type. However, InstCombine only rewrites single-use values.
5510   // This means that if a tree entry other than a root is used externally, it
5511   // must have multiple uses and InstCombine will not rewrite it. The code
5512   // below ensures that only the roots are used externally.
5513   SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
5514   for (auto &EU : ExternalUses)
5515     if (!Expr.erase(EU.Scalar))
5516       return;
5517   if (!Expr.empty())
5518     return;
5519 
5520   // Collect the scalar values of the vectorizable expression. We will use this
5521   // context to determine which values can be demoted. If we see a truncation,
5522   // we mark it as seeding another demotion.
5523   for (auto &EntryPtr : VectorizableTree)
5524     Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
5525 
5526   // Ensure the roots of the vectorizable tree don't form a cycle. They must
5527   // have a single external user that is not in the vectorizable tree.
5528   for (auto *Root : TreeRoot)
5529     if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
5530       return;
5531 
5532   // Conservatively determine if we can actually truncate the roots of the
5533   // expression. Collect the values that can be demoted in ToDemote and
5534   // additional roots that require investigating in Roots.
5535   SmallVector<Value *, 32> ToDemote;
5536   SmallVector<Value *, 4> Roots;
5537   for (auto *Root : TreeRoot)
5538     if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
5539       return;
5540 
5541   // The maximum bit width required to represent all the values that can be
5542   // demoted without loss of precision. It would be safe to truncate the roots
5543   // of the expression to this width.
5544   auto MaxBitWidth = 8u;
5545 
5546   // We first check if all the bits of the roots are demanded. If they're not,
5547   // we can truncate the roots to this narrower type.
5548   for (auto *Root : TreeRoot) {
5549     auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
5550     MaxBitWidth = std::max<unsigned>(
5551         Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
5552   }
5553 
5554   // True if the roots can be zero-extended back to their original type, rather
5555   // than sign-extended. We know that if the leading bits are not demanded, we
5556   // can safely zero-extend. So we initialize IsKnownPositive to True.
5557   bool IsKnownPositive = true;
5558 
5559   // If all the bits of the roots are demanded, we can try a little harder to
5560   // compute a narrower type. This can happen, for example, if the roots are
5561   // getelementptr indices. InstCombine promotes these indices to the pointer
5562   // width. Thus, all their bits are technically demanded even though the
5563   // address computation might be vectorized in a smaller type.
5564   //
5565   // We start by looking at each entry that can be demoted. We compute the
5566   // maximum bit width required to store the scalar by using ValueTracking to
5567   // compute the number of high-order bits we can truncate.
5568   if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
5569       llvm::all_of(TreeRoot, [](Value *R) {
5570         assert(R->hasOneUse() && "Root should have only one use!");
5571         return isa<GetElementPtrInst>(R->user_back());
5572       })) {
5573     MaxBitWidth = 8u;
5574 
5575     // Determine if the sign bit of all the roots is known to be zero. If not,
5576     // IsKnownPositive is set to False.
5577     IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
5578       KnownBits Known = computeKnownBits(R, *DL);
5579       return Known.isNonNegative();
5580     });
5581 
5582     // Determine the maximum number of bits required to store the scalar
5583     // values.
5584     for (auto *Scalar : ToDemote) {
5585       auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
5586       auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
5587       MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
5588     }
5589 
5590     // If we can't prove that the sign bit is zero, we must add one to the
5591     // maximum bit width to account for the unknown sign bit. This preserves
5592     // the existing sign bit so we can safely sign-extend the root back to the
5593     // original type. Otherwise, if we know the sign bit is zero, we will
5594     // zero-extend the root instead.
5595     //
5596     // FIXME: This is somewhat suboptimal, as there will be cases where adding
5597     //        one to the maximum bit width will yield a larger-than-necessary
5598     //        type. In general, we need to add an extra bit only if we can't
5599     //        prove that the upper bit of the original type is equal to the
5600     //        upper bit of the proposed smaller type. If these two bits are the
5601     //        same (either zero or one) we know that sign-extending from the
5602     //        smaller type will result in the same value. Here, since we can't
5603     //        yet prove this, we are just making the proposed smaller type
5604     //        larger to ensure correctness.
5605     if (!IsKnownPositive)
5606       ++MaxBitWidth;
5607   }
5608 
5609   // Round MaxBitWidth up to the next power-of-two.
5610   if (!isPowerOf2_64(MaxBitWidth))
5611     MaxBitWidth = NextPowerOf2(MaxBitWidth);
5612 
5613   // If the maximum bit width we compute is less than the with of the roots'
5614   // type, we can proceed with the narrowing. Otherwise, do nothing.
5615   if (MaxBitWidth >= TreeRootIT->getBitWidth())
5616     return;
5617 
5618   // If we can truncate the root, we must collect additional values that might
5619   // be demoted as a result. That is, those seeded by truncations we will
5620   // modify.
5621   while (!Roots.empty())
5622     collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
5623 
5624   // Finally, map the values we can demote to the maximum bit with we computed.
5625   for (auto *Scalar : ToDemote)
5626     MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
5627 }
5628 
5629 namespace {
5630 
5631 /// The SLPVectorizer Pass.
5632 struct SLPVectorizer : public FunctionPass {
5633   SLPVectorizerPass Impl;
5634 
5635   /// Pass identification, replacement for typeid
5636   static char ID;
5637 
5638   explicit SLPVectorizer() : FunctionPass(ID) {
5639     initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
5640   }
5641 
5642   bool doInitialization(Module &M) override {
5643     return false;
5644   }
5645 
5646   bool runOnFunction(Function &F) override {
5647     if (skipFunction(F))
5648       return false;
5649 
5650     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5651     auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
5652     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
5653     auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
5654     auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
5655     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5656     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5657     auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
5658     auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
5659     auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
5660 
5661     return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5662   }
5663 
5664   void getAnalysisUsage(AnalysisUsage &AU) const override {
5665     FunctionPass::getAnalysisUsage(AU);
5666     AU.addRequired<AssumptionCacheTracker>();
5667     AU.addRequired<ScalarEvolutionWrapperPass>();
5668     AU.addRequired<AAResultsWrapperPass>();
5669     AU.addRequired<TargetTransformInfoWrapperPass>();
5670     AU.addRequired<LoopInfoWrapperPass>();
5671     AU.addRequired<DominatorTreeWrapperPass>();
5672     AU.addRequired<DemandedBitsWrapperPass>();
5673     AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
5674     AU.addRequired<InjectTLIMappingsLegacy>();
5675     AU.addPreserved<LoopInfoWrapperPass>();
5676     AU.addPreserved<DominatorTreeWrapperPass>();
5677     AU.addPreserved<AAResultsWrapperPass>();
5678     AU.addPreserved<GlobalsAAWrapperPass>();
5679     AU.setPreservesCFG();
5680   }
5681 };
5682 
5683 } // end anonymous namespace
5684 
5685 PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
5686   auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
5687   auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
5688   auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
5689   auto *AA = &AM.getResult<AAManager>(F);
5690   auto *LI = &AM.getResult<LoopAnalysis>(F);
5691   auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
5692   auto *AC = &AM.getResult<AssumptionAnalysis>(F);
5693   auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
5694   auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
5695 
5696   bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
5697   if (!Changed)
5698     return PreservedAnalyses::all();
5699 
5700   PreservedAnalyses PA;
5701   PA.preserveSet<CFGAnalyses>();
5702   PA.preserve<AAManager>();
5703   PA.preserve<GlobalsAA>();
5704   return PA;
5705 }
5706 
5707 bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
5708                                 TargetTransformInfo *TTI_,
5709                                 TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
5710                                 LoopInfo *LI_, DominatorTree *DT_,
5711                                 AssumptionCache *AC_, DemandedBits *DB_,
5712                                 OptimizationRemarkEmitter *ORE_) {
5713   if (!RunSLPVectorization)
5714     return false;
5715   SE = SE_;
5716   TTI = TTI_;
5717   TLI = TLI_;
5718   AA = AA_;
5719   LI = LI_;
5720   DT = DT_;
5721   AC = AC_;
5722   DB = DB_;
5723   DL = &F.getParent()->getDataLayout();
5724 
5725   Stores.clear();
5726   GEPs.clear();
5727   bool Changed = false;
5728 
5729   // If the target claims to have no vector registers don't attempt
5730   // vectorization.
5731   if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true)))
5732     return false;
5733 
5734   // Don't vectorize when the attribute NoImplicitFloat is used.
5735   if (F.hasFnAttribute(Attribute::NoImplicitFloat))
5736     return false;
5737 
5738   LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
5739 
5740   // Use the bottom up slp vectorizer to construct chains that start with
5741   // store instructions.
5742   BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
5743 
5744   // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
5745   // delete instructions.
5746 
5747   // Scan the blocks in the function in post order.
5748   for (auto BB : post_order(&F.getEntryBlock())) {
5749     collectSeedInstructions(BB);
5750 
5751     // Vectorize trees that end at stores.
5752     if (!Stores.empty()) {
5753       LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
5754                         << " underlying objects.\n");
5755       Changed |= vectorizeStoreChains(R);
5756     }
5757 
5758     // Vectorize trees that end at reductions.
5759     Changed |= vectorizeChainsInBlock(BB, R);
5760 
5761     // Vectorize the index computations of getelementptr instructions. This
5762     // is primarily intended to catch gather-like idioms ending at
5763     // non-consecutive loads.
5764     if (!GEPs.empty()) {
5765       LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
5766                         << " underlying objects.\n");
5767       Changed |= vectorizeGEPIndices(BB, R);
5768     }
5769   }
5770 
5771   if (Changed) {
5772     R.optimizeGatherSequence();
5773     LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
5774   }
5775   return Changed;
5776 }
5777 
5778 bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
5779                                             unsigned Idx) {
5780   LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
5781                     << "\n");
5782   const unsigned Sz = R.getVectorElementSize(Chain[0]);
5783   const unsigned MinVF = R.getMinVecRegSize() / Sz;
5784   unsigned VF = Chain.size();
5785 
5786   if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
5787     return false;
5788 
5789   LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
5790                     << "\n");
5791 
5792   R.buildTree(Chain);
5793   Optional<ArrayRef<unsigned>> Order = R.bestOrder();
5794   // TODO: Handle orders of size less than number of elements in the vector.
5795   if (Order && Order->size() == Chain.size()) {
5796     // TODO: reorder tree nodes without tree rebuilding.
5797     SmallVector<Value *, 4> ReorderedOps(Chain.rbegin(), Chain.rend());
5798     llvm::transform(*Order, ReorderedOps.begin(),
5799                     [Chain](const unsigned Idx) { return Chain[Idx]; });
5800     R.buildTree(ReorderedOps);
5801   }
5802   if (R.isTreeTinyAndNotFullyVectorizable())
5803     return false;
5804   if (R.isLoadCombineCandidate())
5805     return false;
5806 
5807   R.computeMinimumValueSizes();
5808 
5809   int Cost = R.getTreeCost();
5810 
5811   LLVM_DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF << "\n");
5812   if (Cost < -SLPCostThreshold) {
5813     LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
5814 
5815     using namespace ore;
5816 
5817     R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
5818                                         cast<StoreInst>(Chain[0]))
5819                      << "Stores SLP vectorized with cost " << NV("Cost", Cost)
5820                      << " and with tree size "
5821                      << NV("TreeSize", R.getTreeSize()));
5822 
5823     R.vectorizeTree();
5824     return true;
5825   }
5826 
5827   return false;
5828 }
5829 
5830 bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
5831                                         BoUpSLP &R) {
5832   // We may run into multiple chains that merge into a single chain. We mark the
5833   // stores that we vectorized so that we don't visit the same store twice.
5834   BoUpSLP::ValueSet VectorizedStores;
5835   bool Changed = false;
5836 
5837   int E = Stores.size();
5838   SmallBitVector Tails(E, false);
5839   SmallVector<int, 16> ConsecutiveChain(E, E + 1);
5840   int MaxIter = MaxStoreLookup.getValue();
5841   int IterCnt;
5842   auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
5843                                   &ConsecutiveChain](int K, int Idx) {
5844     if (IterCnt >= MaxIter)
5845       return true;
5846     ++IterCnt;
5847     if (!isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE))
5848       return false;
5849 
5850     Tails.set(Idx);
5851     ConsecutiveChain[K] = Idx;
5852     return true;
5853   };
5854   // Do a quadratic search on all of the given stores in reverse order and find
5855   // all of the pairs of stores that follow each other.
5856   for (int Idx = E - 1; Idx >= 0; --Idx) {
5857     // If a store has multiple consecutive store candidates, search according
5858     // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
5859     // This is because usually pairing with immediate succeeding or preceding
5860     // candidate create the best chance to find slp vectorization opportunity.
5861     const int MaxLookDepth = std::max(E - Idx, Idx + 1);
5862     IterCnt = 0;
5863     for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
5864       if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
5865           (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
5866         break;
5867   }
5868 
5869   // For stores that start but don't end a link in the chain:
5870   for (int Cnt = E; Cnt > 0; --Cnt) {
5871     int I = Cnt - 1;
5872     if (ConsecutiveChain[I] == E + 1 || Tails.test(I))
5873       continue;
5874     // We found a store instr that starts a chain. Now follow the chain and try
5875     // to vectorize it.
5876     BoUpSLP::ValueList Operands;
5877     // Collect the chain into a list.
5878     while (I != E + 1 && !VectorizedStores.count(Stores[I])) {
5879       Operands.push_back(Stores[I]);
5880       // Move to the next value in the chain.
5881       I = ConsecutiveChain[I];
5882     }
5883 
5884     // If a vector register can't hold 1 element, we are done.
5885     unsigned MaxVecRegSize = R.getMaxVecRegSize();
5886     unsigned EltSize = R.getVectorElementSize(Stores[0]);
5887     if (MaxVecRegSize % EltSize != 0)
5888       continue;
5889 
5890     unsigned MaxElts = MaxVecRegSize / EltSize;
5891     // FIXME: Is division-by-2 the correct step? Should we assert that the
5892     // register size is a power-of-2?
5893     unsigned StartIdx = 0;
5894     for (unsigned Size = llvm::PowerOf2Ceil(MaxElts); Size >= 2; Size /= 2) {
5895       for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
5896         ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
5897         if (!VectorizedStores.count(Slice.front()) &&
5898             !VectorizedStores.count(Slice.back()) &&
5899             vectorizeStoreChain(Slice, R, Cnt)) {
5900           // Mark the vectorized stores so that we don't vectorize them again.
5901           VectorizedStores.insert(Slice.begin(), Slice.end());
5902           Changed = true;
5903           // If we vectorized initial block, no need to try to vectorize it
5904           // again.
5905           if (Cnt == StartIdx)
5906             StartIdx += Size;
5907           Cnt += Size;
5908           continue;
5909         }
5910         ++Cnt;
5911       }
5912       // Check if the whole array was vectorized already - exit.
5913       if (StartIdx >= Operands.size())
5914         break;
5915     }
5916   }
5917 
5918   return Changed;
5919 }
5920 
5921 void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
5922   // Initialize the collections. We will make a single pass over the block.
5923   Stores.clear();
5924   GEPs.clear();
5925 
5926   // Visit the store and getelementptr instructions in BB and organize them in
5927   // Stores and GEPs according to the underlying objects of their pointer
5928   // operands.
5929   for (Instruction &I : *BB) {
5930     // Ignore store instructions that are volatile or have a pointer operand
5931     // that doesn't point to a scalar type.
5932     if (auto *SI = dyn_cast<StoreInst>(&I)) {
5933       if (!SI->isSimple())
5934         continue;
5935       if (!isValidElementType(SI->getValueOperand()->getType()))
5936         continue;
5937       Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
5938     }
5939 
5940     // Ignore getelementptr instructions that have more than one index, a
5941     // constant index, or a pointer operand that doesn't point to a scalar
5942     // type.
5943     else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
5944       auto Idx = GEP->idx_begin()->get();
5945       if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
5946         continue;
5947       if (!isValidElementType(Idx->getType()))
5948         continue;
5949       if (GEP->getType()->isVectorTy())
5950         continue;
5951       GEPs[GEP->getPointerOperand()].push_back(GEP);
5952     }
5953   }
5954 }
5955 
5956 bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
5957   if (!A || !B)
5958     return false;
5959   Value *VL[] = {A, B};
5960   return tryToVectorizeList(VL, R, /*AllowReorder=*/true);
5961 }
5962 
5963 bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
5964                                            bool AllowReorder,
5965                                            ArrayRef<Value *> InsertUses) {
5966   if (VL.size() < 2)
5967     return false;
5968 
5969   LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
5970                     << VL.size() << ".\n");
5971 
5972   // Check that all of the parts are instructions of the same type,
5973   // we permit an alternate opcode via InstructionsState.
5974   InstructionsState S = getSameOpcode(VL);
5975   if (!S.getOpcode())
5976     return false;
5977 
5978   Instruction *I0 = cast<Instruction>(S.OpValue);
5979   // Make sure invalid types (including vector type) are rejected before
5980   // determining vectorization factor for scalar instructions.
5981   for (Value *V : VL) {
5982     Type *Ty = V->getType();
5983     if (!isValidElementType(Ty)) {
5984       // NOTE: the following will give user internal llvm type name, which may
5985       // not be useful.
5986       R.getORE()->emit([&]() {
5987         std::string type_str;
5988         llvm::raw_string_ostream rso(type_str);
5989         Ty->print(rso);
5990         return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
5991                << "Cannot SLP vectorize list: type "
5992                << rso.str() + " is unsupported by vectorizer";
5993       });
5994       return false;
5995     }
5996   }
5997 
5998   unsigned Sz = R.getVectorElementSize(I0);
5999   unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
6000   unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
6001   if (MaxVF < 2) {
6002     R.getORE()->emit([&]() {
6003       return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
6004              << "Cannot SLP vectorize list: vectorization factor "
6005              << "less than 2 is not supported";
6006     });
6007     return false;
6008   }
6009 
6010   bool Changed = false;
6011   bool CandidateFound = false;
6012   int MinCost = SLPCostThreshold;
6013 
6014   bool CompensateUseCost =
6015       !InsertUses.empty() && llvm::all_of(InsertUses, [](const Value *V) {
6016         return V && isa<InsertElementInst>(V);
6017       });
6018   assert((!CompensateUseCost || InsertUses.size() == VL.size()) &&
6019          "Each scalar expected to have an associated InsertElement user.");
6020 
6021   unsigned NextInst = 0, MaxInst = VL.size();
6022   for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
6023     // No actual vectorization should happen, if number of parts is the same as
6024     // provided vectorization factor (i.e. the scalar type is used for vector
6025     // code during codegen).
6026     auto *VecTy = FixedVectorType::get(VL[0]->getType(), VF);
6027     if (TTI->getNumberOfParts(VecTy) == VF)
6028       continue;
6029     for (unsigned I = NextInst; I < MaxInst; ++I) {
6030       unsigned OpsWidth = 0;
6031 
6032       if (I + VF > MaxInst)
6033         OpsWidth = MaxInst - I;
6034       else
6035         OpsWidth = VF;
6036 
6037       if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
6038         break;
6039 
6040       ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
6041       // Check that a previous iteration of this loop did not delete the Value.
6042       if (llvm::any_of(Ops, [&R](Value *V) {
6043             auto *I = dyn_cast<Instruction>(V);
6044             return I && R.isDeleted(I);
6045           }))
6046         continue;
6047 
6048       LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
6049                         << "\n");
6050 
6051       R.buildTree(Ops);
6052       Optional<ArrayRef<unsigned>> Order = R.bestOrder();
6053       // TODO: check if we can allow reordering for more cases.
6054       if (AllowReorder && Order) {
6055         // TODO: reorder tree nodes without tree rebuilding.
6056         // Conceptually, there is nothing actually preventing us from trying to
6057         // reorder a larger list. In fact, we do exactly this when vectorizing
6058         // reductions. However, at this point, we only expect to get here when
6059         // there are exactly two operations.
6060         assert(Ops.size() == 2);
6061         Value *ReorderedOps[] = {Ops[1], Ops[0]};
6062         R.buildTree(ReorderedOps, None);
6063       }
6064       if (R.isTreeTinyAndNotFullyVectorizable())
6065         continue;
6066 
6067       R.computeMinimumValueSizes();
6068       int Cost = R.getTreeCost();
6069       CandidateFound = true;
6070       if (CompensateUseCost) {
6071         // TODO: Use TTI's getScalarizationOverhead for sequence of inserts
6072         // rather than sum of single inserts as the latter may overestimate
6073         // cost. This work should imply improving cost estimation for extracts
6074         // that added in for external (for vectorization tree) users,i.e. that
6075         // part should also switch to same interface.
6076         // For example, the following case is projected code after SLP:
6077         //  %4 = extractelement <4 x i64> %3, i32 0
6078         //  %v0 = insertelement <4 x i64> undef, i64 %4, i32 0
6079         //  %5 = extractelement <4 x i64> %3, i32 1
6080         //  %v1 = insertelement <4 x i64> %v0, i64 %5, i32 1
6081         //  %6 = extractelement <4 x i64> %3, i32 2
6082         //  %v2 = insertelement <4 x i64> %v1, i64 %6, i32 2
6083         //  %7 = extractelement <4 x i64> %3, i32 3
6084         //  %v3 = insertelement <4 x i64> %v2, i64 %7, i32 3
6085         //
6086         // Extracts here added by SLP in order to feed users (the inserts) of
6087         // original scalars and contribute to "ExtractCost" at cost evaluation.
6088         // The inserts in turn form sequence to build an aggregate that
6089         // detected by findBuildAggregate routine.
6090         // SLP makes an assumption that such sequence will be optimized away
6091         // later (instcombine) so it tries to compensate ExctractCost with
6092         // cost of insert sequence.
6093         // Current per element cost calculation approach is not quite accurate
6094         // and tends to create bias toward favoring vectorization.
6095         // Switching to the TTI interface might help a bit.
6096         // Alternative solution could be pattern-match to detect a no-op or
6097         // shuffle.
6098         unsigned UserCost = 0;
6099         for (unsigned Lane = 0; Lane < OpsWidth; Lane++) {
6100           auto *IE = cast<InsertElementInst>(InsertUses[I + Lane]);
6101           if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2)))
6102             UserCost += TTI->getVectorInstrCost(
6103                 Instruction::InsertElement, IE->getType(), CI->getZExtValue());
6104         }
6105         LLVM_DEBUG(dbgs() << "SLP: Compensate cost of users by: " << UserCost
6106                           << ".\n");
6107         Cost -= UserCost;
6108       }
6109 
6110       MinCost = std::min(MinCost, Cost);
6111 
6112       if (Cost < -SLPCostThreshold) {
6113         LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
6114         R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
6115                                                     cast<Instruction>(Ops[0]))
6116                                  << "SLP vectorized with cost " << ore::NV("Cost", Cost)
6117                                  << " and with tree size "
6118                                  << ore::NV("TreeSize", R.getTreeSize()));
6119 
6120         R.vectorizeTree();
6121         // Move to the next bundle.
6122         I += VF - 1;
6123         NextInst = I + 1;
6124         Changed = true;
6125       }
6126     }
6127   }
6128 
6129   if (!Changed && CandidateFound) {
6130     R.getORE()->emit([&]() {
6131       return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
6132              << "List vectorization was possible but not beneficial with cost "
6133              << ore::NV("Cost", MinCost) << " >= "
6134              << ore::NV("Treshold", -SLPCostThreshold);
6135     });
6136   } else if (!Changed) {
6137     R.getORE()->emit([&]() {
6138       return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
6139              << "Cannot SLP vectorize list: vectorization was impossible"
6140              << " with available vectorization factors";
6141     });
6142   }
6143   return Changed;
6144 }
6145 
6146 bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
6147   if (!I)
6148     return false;
6149 
6150   if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
6151     return false;
6152 
6153   Value *P = I->getParent();
6154 
6155   // Vectorize in current basic block only.
6156   auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
6157   auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
6158   if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
6159     return false;
6160 
6161   // Try to vectorize V.
6162   if (tryToVectorizePair(Op0, Op1, R))
6163     return true;
6164 
6165   auto *A = dyn_cast<BinaryOperator>(Op0);
6166   auto *B = dyn_cast<BinaryOperator>(Op1);
6167   // Try to skip B.
6168   if (B && B->hasOneUse()) {
6169     auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
6170     auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
6171     if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
6172       return true;
6173     if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
6174       return true;
6175   }
6176 
6177   // Try to skip A.
6178   if (A && A->hasOneUse()) {
6179     auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
6180     auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
6181     if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
6182       return true;
6183     if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
6184       return true;
6185   }
6186   return false;
6187 }
6188 
6189 /// Generate a shuffle mask to be used in a reduction tree.
6190 ///
6191 /// \param VecLen The length of the vector to be reduced.
6192 /// \param NumEltsToRdx The number of elements that should be reduced in the
6193 ///        vector.
6194 /// \param IsPairwise Whether the reduction is a pairwise or splitting
6195 ///        reduction. A pairwise reduction will generate a mask of
6196 ///        <0,2,...> or <1,3,..> while a splitting reduction will generate
6197 ///        <2,3, undef,undef> for a vector of 4 and NumElts = 2.
6198 /// \param IsLeft True will generate a mask of even elements, odd otherwise.
6199 static SmallVector<int, 32> createRdxShuffleMask(unsigned VecLen,
6200                                                  unsigned NumEltsToRdx,
6201                                                  bool IsPairwise, bool IsLeft) {
6202   assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
6203 
6204   SmallVector<int, 32> ShuffleMask(VecLen, -1);
6205 
6206   if (IsPairwise)
6207     // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
6208     for (unsigned i = 0; i != NumEltsToRdx; ++i)
6209       ShuffleMask[i] = 2 * i + !IsLeft;
6210   else
6211     // Move the upper half of the vector to the lower half.
6212     for (unsigned i = 0; i != NumEltsToRdx; ++i)
6213       ShuffleMask[i] = NumEltsToRdx + i;
6214 
6215   return ShuffleMask;
6216 }
6217 
6218 namespace {
6219 
6220 /// Model horizontal reductions.
6221 ///
6222 /// A horizontal reduction is a tree of reduction operations (currently add and
6223 /// fadd) that has operations that can be put into a vector as its leaf.
6224 /// For example, this tree:
6225 ///
6226 /// mul mul mul mul
6227 ///  \  /    \  /
6228 ///   +       +
6229 ///    \     /
6230 ///       +
6231 /// This tree has "mul" as its reduced values and "+" as its reduction
6232 /// operations. A reduction might be feeding into a store or a binary operation
6233 /// feeding a phi.
6234 ///    ...
6235 ///    \  /
6236 ///     +
6237 ///     |
6238 ///  phi +=
6239 ///
6240 ///  Or:
6241 ///    ...
6242 ///    \  /
6243 ///     +
6244 ///     |
6245 ///   *p =
6246 ///
6247 class HorizontalReduction {
6248   using ReductionOpsType = SmallVector<Value *, 16>;
6249   using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
6250   ReductionOpsListType  ReductionOps;
6251   SmallVector<Value *, 32> ReducedVals;
6252   // Use map vector to make stable output.
6253   MapVector<Instruction *, Value *> ExtraArgs;
6254 
6255   /// Kind of the reduction data.
6256   enum ReductionKind {
6257     RK_None,       /// Not a reduction.
6258     RK_Arithmetic, /// Binary reduction data.
6259     RK_Min,        /// Minimum reduction data.
6260     RK_UMin,       /// Unsigned minimum reduction data.
6261     RK_Max,        /// Maximum reduction data.
6262     RK_UMax,       /// Unsigned maximum reduction data.
6263   };
6264 
6265   /// Contains info about operation, like its opcode, left and right operands.
6266   class OperationData {
6267     /// Opcode of the instruction.
6268     unsigned Opcode = 0;
6269 
6270     /// Left operand of the reduction operation.
6271     Value *LHS = nullptr;
6272 
6273     /// Right operand of the reduction operation.
6274     Value *RHS = nullptr;
6275 
6276     /// Kind of the reduction operation.
6277     ReductionKind Kind = RK_None;
6278 
6279     /// True if float point min/max reduction has no NaNs.
6280     bool NoNaN = false;
6281 
6282     /// Checks if the reduction operation can be vectorized.
6283     bool isVectorizable() const {
6284       return LHS && RHS &&
6285              // We currently only support add/mul/logical && min/max reductions.
6286              ((Kind == RK_Arithmetic &&
6287                (Opcode == Instruction::Add || Opcode == Instruction::FAdd ||
6288                 Opcode == Instruction::Mul || Opcode == Instruction::FMul ||
6289                 Opcode == Instruction::And || Opcode == Instruction::Or ||
6290                 Opcode == Instruction::Xor)) ||
6291               ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
6292                (Kind == RK_Min || Kind == RK_Max)) ||
6293               (Opcode == Instruction::ICmp &&
6294                (Kind == RK_UMin || Kind == RK_UMax)));
6295     }
6296 
6297     /// Creates reduction operation with the current opcode.
6298     Value *createOp(IRBuilder<> &Builder, const Twine &Name) const {
6299       assert(isVectorizable() &&
6300              "Expected add|fadd or min/max reduction operation.");
6301       Value *Cmp = nullptr;
6302       switch (Kind) {
6303       case RK_Arithmetic:
6304         return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
6305                                    Name);
6306       case RK_Min:
6307         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSLT(LHS, RHS)
6308                                           : Builder.CreateFCmpOLT(LHS, RHS);
6309         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6310       case RK_Max:
6311         Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSGT(LHS, RHS)
6312                                           : Builder.CreateFCmpOGT(LHS, RHS);
6313         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6314       case RK_UMin:
6315         assert(Opcode == Instruction::ICmp && "Expected integer types.");
6316         Cmp = Builder.CreateICmpULT(LHS, RHS);
6317         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6318       case RK_UMax:
6319         assert(Opcode == Instruction::ICmp && "Expected integer types.");
6320         Cmp = Builder.CreateICmpUGT(LHS, RHS);
6321         return Builder.CreateSelect(Cmp, LHS, RHS, Name);
6322       case RK_None:
6323         break;
6324       }
6325       llvm_unreachable("Unknown reduction operation.");
6326     }
6327 
6328   public:
6329     explicit OperationData() = default;
6330 
6331     /// Construction for reduced values. They are identified by opcode only and
6332     /// don't have associated LHS/RHS values.
6333     explicit OperationData(Value *V) {
6334       if (auto *I = dyn_cast<Instruction>(V))
6335         Opcode = I->getOpcode();
6336     }
6337 
6338     /// Constructor for reduction operations with opcode and its left and
6339     /// right operands.
6340     OperationData(unsigned Opcode, Value *LHS, Value *RHS, ReductionKind Kind,
6341                   bool NoNaN = false)
6342         : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind), NoNaN(NoNaN) {
6343       assert(Kind != RK_None && "One of the reduction operations is expected.");
6344     }
6345 
6346     explicit operator bool() const { return Opcode; }
6347 
6348     /// Return true if this operation is any kind of minimum or maximum.
6349     bool isMinMax() const {
6350       switch (Kind) {
6351       case RK_Arithmetic:
6352         return false;
6353       case RK_Min:
6354       case RK_Max:
6355       case RK_UMin:
6356       case RK_UMax:
6357         return true;
6358       case RK_None:
6359         break;
6360       }
6361       llvm_unreachable("Reduction kind is not set");
6362     }
6363 
6364     /// Get the index of the first operand.
6365     unsigned getFirstOperandIndex() const {
6366       assert(!!*this && "The opcode is not set.");
6367       // We allow calling this before 'Kind' is set, so handle that specially.
6368       if (Kind == RK_None)
6369         return 0;
6370       return isMinMax() ? 1 : 0;
6371     }
6372 
6373     /// Total number of operands in the reduction operation.
6374     unsigned getNumberOfOperands() const {
6375       assert(Kind != RK_None && !!*this && LHS && RHS &&
6376              "Expected reduction operation.");
6377       return isMinMax() ? 3 : 2;
6378     }
6379 
6380     /// Checks if the operation has the same parent as \p P.
6381     bool hasSameParent(Instruction *I, Value *P, bool IsRedOp) const {
6382       assert(Kind != RK_None && !!*this && LHS && RHS &&
6383              "Expected reduction operation.");
6384       if (!IsRedOp)
6385         return I->getParent() == P;
6386       if (isMinMax()) {
6387         // SelectInst must be used twice while the condition op must have single
6388         // use only.
6389         auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition());
6390         return I->getParent() == P && Cmp && Cmp->getParent() == P;
6391       }
6392       // Arithmetic reduction operation must be used once only.
6393       return I->getParent() == P;
6394     }
6395 
6396     /// Expected number of uses for reduction operations/reduced values.
6397     bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const {
6398       assert(Kind != RK_None && !!*this && LHS && RHS &&
6399              "Expected reduction operation.");
6400       if (isMinMax())
6401         return I->hasNUses(2) &&
6402                (!IsReductionOp ||
6403                 cast<SelectInst>(I)->getCondition()->hasOneUse());
6404       return I->hasOneUse();
6405     }
6406 
6407     /// Initializes the list of reduction operations.
6408     void initReductionOps(ReductionOpsListType &ReductionOps) {
6409       assert(Kind != RK_None && !!*this && LHS && RHS &&
6410              "Expected reduction operation.");
6411       if (isMinMax())
6412         ReductionOps.assign(2, ReductionOpsType());
6413       else
6414         ReductionOps.assign(1, ReductionOpsType());
6415     }
6416 
6417     /// Add all reduction operations for the reduction instruction \p I.
6418     void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) {
6419       assert(Kind != RK_None && !!*this && LHS && RHS &&
6420              "Expected reduction operation.");
6421       if (isMinMax()) {
6422         ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
6423         ReductionOps[1].emplace_back(I);
6424       } else {
6425         ReductionOps[0].emplace_back(I);
6426       }
6427     }
6428 
6429     /// Checks if instruction is associative and can be vectorized.
6430     bool isAssociative(Instruction *I) const {
6431       assert(Kind != RK_None && *this && LHS && RHS &&
6432              "Expected reduction operation.");
6433       switch (Kind) {
6434       case RK_Arithmetic:
6435         return I->isAssociative();
6436       case RK_Min:
6437       case RK_Max:
6438         return Opcode == Instruction::ICmp ||
6439                cast<Instruction>(I->getOperand(0))->isFast();
6440       case RK_UMin:
6441       case RK_UMax:
6442         assert(Opcode == Instruction::ICmp &&
6443                "Only integer compare operation is expected.");
6444         return true;
6445       case RK_None:
6446         break;
6447       }
6448       llvm_unreachable("Reduction kind is not set");
6449     }
6450 
6451     /// Checks if the reduction operation can be vectorized.
6452     bool isVectorizable(Instruction *I) const {
6453       return isVectorizable() && isAssociative(I);
6454     }
6455 
6456     /// Checks if two operation data are both a reduction op or both a reduced
6457     /// value.
6458     bool operator==(const OperationData &OD) const {
6459       assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&
6460              "One of the comparing operations is incorrect.");
6461       return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
6462     }
6463     bool operator!=(const OperationData &OD) const { return !(*this == OD); }
6464     void clear() {
6465       Opcode = 0;
6466       LHS = nullptr;
6467       RHS = nullptr;
6468       Kind = RK_None;
6469       NoNaN = false;
6470     }
6471 
6472     /// Get the opcode of the reduction operation.
6473     unsigned getOpcode() const {
6474       assert(isVectorizable() && "Expected vectorizable operation.");
6475       return Opcode;
6476     }
6477 
6478     /// Get kind of reduction data.
6479     ReductionKind getKind() const { return Kind; }
6480     Value *getLHS() const { return LHS; }
6481     Value *getRHS() const { return RHS; }
6482     Type *getConditionType() const {
6483       return isMinMax() ? CmpInst::makeCmpResultType(LHS->getType()) : nullptr;
6484     }
6485 
6486     /// Creates reduction operation with the current opcode with the IR flags
6487     /// from \p ReductionOps.
6488     Value *createOp(IRBuilder<> &Builder, const Twine &Name,
6489                     const ReductionOpsListType &ReductionOps) const {
6490       assert(isVectorizable() &&
6491              "Expected add|fadd or min/max reduction operation.");
6492       auto *Op = createOp(Builder, Name);
6493       switch (Kind) {
6494       case RK_Arithmetic:
6495         propagateIRFlags(Op, ReductionOps[0]);
6496         return Op;
6497       case RK_Min:
6498       case RK_Max:
6499       case RK_UMin:
6500       case RK_UMax:
6501         if (auto *SI = dyn_cast<SelectInst>(Op))
6502           propagateIRFlags(SI->getCondition(), ReductionOps[0]);
6503         propagateIRFlags(Op, ReductionOps[1]);
6504         return Op;
6505       case RK_None:
6506         break;
6507       }
6508       llvm_unreachable("Unknown reduction operation.");
6509     }
6510     /// Creates reduction operation with the current opcode with the IR flags
6511     /// from \p I.
6512     Value *createOp(IRBuilder<> &Builder, const Twine &Name,
6513                     Instruction *I) const {
6514       assert(isVectorizable() &&
6515              "Expected add|fadd or min/max reduction operation.");
6516       auto *Op = createOp(Builder, Name);
6517       switch (Kind) {
6518       case RK_Arithmetic:
6519         propagateIRFlags(Op, I);
6520         return Op;
6521       case RK_Min:
6522       case RK_Max:
6523       case RK_UMin:
6524       case RK_UMax:
6525         if (auto *SI = dyn_cast<SelectInst>(Op)) {
6526           propagateIRFlags(SI->getCondition(),
6527                            cast<SelectInst>(I)->getCondition());
6528         }
6529         propagateIRFlags(Op, I);
6530         return Op;
6531       case RK_None:
6532         break;
6533       }
6534       llvm_unreachable("Unknown reduction operation.");
6535     }
6536 
6537     TargetTransformInfo::ReductionFlags getFlags() const {
6538       TargetTransformInfo::ReductionFlags Flags;
6539       Flags.NoNaN = NoNaN;
6540       switch (Kind) {
6541       case RK_Arithmetic:
6542         break;
6543       case RK_Min:
6544         Flags.IsSigned = Opcode == Instruction::ICmp;
6545         Flags.IsMaxOp = false;
6546         break;
6547       case RK_Max:
6548         Flags.IsSigned = Opcode == Instruction::ICmp;
6549         Flags.IsMaxOp = true;
6550         break;
6551       case RK_UMin:
6552         Flags.IsSigned = false;
6553         Flags.IsMaxOp = false;
6554         break;
6555       case RK_UMax:
6556         Flags.IsSigned = false;
6557         Flags.IsMaxOp = true;
6558         break;
6559       case RK_None:
6560         llvm_unreachable("Reduction kind is not set");
6561       }
6562       return Flags;
6563     }
6564   };
6565 
6566   WeakTrackingVH ReductionRoot;
6567 
6568   /// The operation data of the reduction operation.
6569   OperationData ReductionData;
6570 
6571   /// The operation data of the values we perform a reduction on.
6572   OperationData ReducedValueData;
6573 
6574   /// Should we model this reduction as a pairwise reduction tree or a tree that
6575   /// splits the vector in halves and adds those halves.
6576   bool IsPairwiseReduction = false;
6577 
6578   /// Checks if the ParentStackElem.first should be marked as a reduction
6579   /// operation with an extra argument or as extra argument itself.
6580   void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
6581                     Value *ExtraArg) {
6582     if (ExtraArgs.count(ParentStackElem.first)) {
6583       ExtraArgs[ParentStackElem.first] = nullptr;
6584       // We ran into something like:
6585       // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
6586       // The whole ParentStackElem.first should be considered as an extra value
6587       // in this case.
6588       // Do not perform analysis of remaining operands of ParentStackElem.first
6589       // instruction, this whole instruction is an extra argument.
6590       ParentStackElem.second = ParentStackElem.first->getNumOperands();
6591     } else {
6592       // We ran into something like:
6593       // ParentStackElem.first += ... + ExtraArg + ...
6594       ExtraArgs[ParentStackElem.first] = ExtraArg;
6595     }
6596   }
6597 
6598   static OperationData getOperationData(Value *V) {
6599     if (!V)
6600       return OperationData();
6601 
6602     Value *LHS;
6603     Value *RHS;
6604     if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(V)) {
6605       return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS,
6606                            RK_Arithmetic);
6607     }
6608     if (auto *Select = dyn_cast<SelectInst>(V)) {
6609       // Look for a min/max pattern.
6610       if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6611         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
6612       } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6613         return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
6614       } else if (m_OrdFMin(m_Value(LHS), m_Value(RHS)).match(Select) ||
6615                  m_UnordFMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
6616         return OperationData(
6617             Instruction::FCmp, LHS, RHS, RK_Min,
6618             cast<Instruction>(Select->getCondition())->hasNoNaNs());
6619       } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6620         return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
6621       } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6622         return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
6623       } else if (m_OrdFMax(m_Value(LHS), m_Value(RHS)).match(Select) ||
6624                  m_UnordFMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
6625         return OperationData(
6626             Instruction::FCmp, LHS, RHS, RK_Max,
6627             cast<Instruction>(Select->getCondition())->hasNoNaNs());
6628       } else {
6629         // Try harder: look for min/max pattern based on instructions producing
6630         // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
6631         // During the intermediate stages of SLP, it's very common to have
6632         // pattern like this (since optimizeGatherSequence is run only once
6633         // at the end):
6634         // %1 = extractelement <2 x i32> %a, i32 0
6635         // %2 = extractelement <2 x i32> %a, i32 1
6636         // %cond = icmp sgt i32 %1, %2
6637         // %3 = extractelement <2 x i32> %a, i32 0
6638         // %4 = extractelement <2 x i32> %a, i32 1
6639         // %select = select i1 %cond, i32 %3, i32 %4
6640         CmpInst::Predicate Pred;
6641         Instruction *L1;
6642         Instruction *L2;
6643 
6644         LHS = Select->getTrueValue();
6645         RHS = Select->getFalseValue();
6646         Value *Cond = Select->getCondition();
6647 
6648         // TODO: Support inverse predicates.
6649         if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
6650           if (!isa<ExtractElementInst>(RHS) ||
6651               !L2->isIdenticalTo(cast<Instruction>(RHS)))
6652             return OperationData(V);
6653         } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
6654           if (!isa<ExtractElementInst>(LHS) ||
6655               !L1->isIdenticalTo(cast<Instruction>(LHS)))
6656             return OperationData(V);
6657         } else {
6658           if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
6659             return OperationData(V);
6660           if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
6661               !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
6662               !L2->isIdenticalTo(cast<Instruction>(RHS)))
6663             return OperationData(V);
6664         }
6665         switch (Pred) {
6666         default:
6667           return OperationData(V);
6668 
6669         case CmpInst::ICMP_ULT:
6670         case CmpInst::ICMP_ULE:
6671           return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
6672 
6673         case CmpInst::ICMP_SLT:
6674         case CmpInst::ICMP_SLE:
6675           return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
6676 
6677         case CmpInst::FCMP_OLT:
6678         case CmpInst::FCMP_OLE:
6679         case CmpInst::FCMP_ULT:
6680         case CmpInst::FCMP_ULE:
6681           return OperationData(Instruction::FCmp, LHS, RHS, RK_Min,
6682                                cast<Instruction>(Cond)->hasNoNaNs());
6683 
6684         case CmpInst::ICMP_UGT:
6685         case CmpInst::ICMP_UGE:
6686           return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
6687 
6688         case CmpInst::ICMP_SGT:
6689         case CmpInst::ICMP_SGE:
6690           return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
6691 
6692         case CmpInst::FCMP_OGT:
6693         case CmpInst::FCMP_OGE:
6694         case CmpInst::FCMP_UGT:
6695         case CmpInst::FCMP_UGE:
6696           return OperationData(Instruction::FCmp, LHS, RHS, RK_Max,
6697                                cast<Instruction>(Cond)->hasNoNaNs());
6698         }
6699       }
6700     }
6701     return OperationData(V);
6702   }
6703 
6704 public:
6705   HorizontalReduction() = default;
6706 
6707   /// Try to find a reduction tree.
6708   bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
6709     assert((!Phi || is_contained(Phi->operands(), B)) &&
6710            "Thi phi needs to use the binary operator");
6711 
6712     ReductionData = getOperationData(B);
6713 
6714     // We could have a initial reductions that is not an add.
6715     //  r *= v1 + v2 + v3 + v4
6716     // In such a case start looking for a tree rooted in the first '+'.
6717     if (Phi) {
6718       if (ReductionData.getLHS() == Phi) {
6719         Phi = nullptr;
6720         B = dyn_cast<Instruction>(ReductionData.getRHS());
6721         ReductionData = getOperationData(B);
6722       } else if (ReductionData.getRHS() == Phi) {
6723         Phi = nullptr;
6724         B = dyn_cast<Instruction>(ReductionData.getLHS());
6725         ReductionData = getOperationData(B);
6726       }
6727     }
6728 
6729     if (!ReductionData.isVectorizable(B))
6730       return false;
6731 
6732     Type *Ty = B->getType();
6733     if (!isValidElementType(Ty))
6734       return false;
6735     if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy())
6736       return false;
6737 
6738     ReducedValueData.clear();
6739     ReductionRoot = B;
6740 
6741     // Post order traverse the reduction tree starting at B. We only handle true
6742     // trees containing only binary operators.
6743     SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
6744     Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
6745     ReductionData.initReductionOps(ReductionOps);
6746     while (!Stack.empty()) {
6747       Instruction *TreeN = Stack.back().first;
6748       unsigned EdgeToVist = Stack.back().second++;
6749       OperationData OpData = getOperationData(TreeN);
6750       bool IsReducedValue = OpData != ReductionData;
6751 
6752       // Postorder vist.
6753       if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
6754         if (IsReducedValue)
6755           ReducedVals.push_back(TreeN);
6756         else {
6757           auto I = ExtraArgs.find(TreeN);
6758           if (I != ExtraArgs.end() && !I->second) {
6759             // Check if TreeN is an extra argument of its parent operation.
6760             if (Stack.size() <= 1) {
6761               // TreeN can't be an extra argument as it is a root reduction
6762               // operation.
6763               return false;
6764             }
6765             // Yes, TreeN is an extra argument, do not add it to a list of
6766             // reduction operations.
6767             // Stack[Stack.size() - 2] always points to the parent operation.
6768             markExtraArg(Stack[Stack.size() - 2], TreeN);
6769             ExtraArgs.erase(TreeN);
6770           } else
6771             ReductionData.addReductionOps(TreeN, ReductionOps);
6772         }
6773         // Retract.
6774         Stack.pop_back();
6775         continue;
6776       }
6777 
6778       // Visit left or right.
6779       Value *NextV = TreeN->getOperand(EdgeToVist);
6780       if (NextV != Phi) {
6781         auto *I = dyn_cast<Instruction>(NextV);
6782         OpData = getOperationData(I);
6783         // Continue analysis if the next operand is a reduction operation or
6784         // (possibly) a reduced value. If the reduced value opcode is not set,
6785         // the first met operation != reduction operation is considered as the
6786         // reduced value class.
6787         if (I && (!ReducedValueData || OpData == ReducedValueData ||
6788                   OpData == ReductionData)) {
6789           const bool IsReductionOperation = OpData == ReductionData;
6790           // Only handle trees in the current basic block.
6791           if (!ReductionData.hasSameParent(I, B->getParent(),
6792                                            IsReductionOperation)) {
6793             // I is an extra argument for TreeN (its parent operation).
6794             markExtraArg(Stack.back(), I);
6795             continue;
6796           }
6797 
6798           // Each tree node needs to have minimal number of users except for the
6799           // ultimate reduction.
6800           if (!ReductionData.hasRequiredNumberOfUses(I,
6801                                                      OpData == ReductionData) &&
6802               I != B) {
6803             // I is an extra argument for TreeN (its parent operation).
6804             markExtraArg(Stack.back(), I);
6805             continue;
6806           }
6807 
6808           if (IsReductionOperation) {
6809             // We need to be able to reassociate the reduction operations.
6810             if (!OpData.isAssociative(I)) {
6811               // I is an extra argument for TreeN (its parent operation).
6812               markExtraArg(Stack.back(), I);
6813               continue;
6814             }
6815           } else if (ReducedValueData &&
6816                      ReducedValueData != OpData) {
6817             // Make sure that the opcodes of the operations that we are going to
6818             // reduce match.
6819             // I is an extra argument for TreeN (its parent operation).
6820             markExtraArg(Stack.back(), I);
6821             continue;
6822           } else if (!ReducedValueData)
6823             ReducedValueData = OpData;
6824 
6825           Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
6826           continue;
6827         }
6828       }
6829       // NextV is an extra argument for TreeN (its parent operation).
6830       markExtraArg(Stack.back(), NextV);
6831     }
6832     return true;
6833   }
6834 
6835   /// Attempt to vectorize the tree found by
6836   /// matchAssociativeReduction.
6837   bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
6838     if (ReducedVals.empty())
6839       return false;
6840 
6841     // If there is a sufficient number of reduction values, reduce
6842     // to a nearby power-of-2. Can safely generate oversized
6843     // vectors and rely on the backend to split them to legal sizes.
6844     unsigned NumReducedVals = ReducedVals.size();
6845     if (NumReducedVals < 4)
6846       return false;
6847 
6848     unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
6849 
6850     Value *VectorizedTree = nullptr;
6851 
6852     // FIXME: Fast-math-flags should be set based on the instructions in the
6853     //        reduction (not all of 'fast' are required).
6854     IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
6855     FastMathFlags Unsafe;
6856     Unsafe.setFast();
6857     Builder.setFastMathFlags(Unsafe);
6858     unsigned i = 0;
6859 
6860     BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
6861     // The same extra argument may be used several time, so log each attempt
6862     // to use it.
6863     for (auto &Pair : ExtraArgs) {
6864       assert(Pair.first && "DebugLoc must be set.");
6865       ExternallyUsedValues[Pair.second].push_back(Pair.first);
6866     }
6867 
6868     // The compare instruction of a min/max is the insertion point for new
6869     // instructions and may be replaced with a new compare instruction.
6870     auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
6871       assert(isa<SelectInst>(RdxRootInst) &&
6872              "Expected min/max reduction to have select root instruction");
6873       Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
6874       assert(isa<Instruction>(ScalarCond) &&
6875              "Expected min/max reduction to have compare condition");
6876       return cast<Instruction>(ScalarCond);
6877     };
6878 
6879     // The reduction root is used as the insertion point for new instructions,
6880     // so set it as externally used to prevent it from being deleted.
6881     ExternallyUsedValues[ReductionRoot];
6882     SmallVector<Value *, 16> IgnoreList;
6883     for (auto &V : ReductionOps)
6884       IgnoreList.append(V.begin(), V.end());
6885     while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
6886       auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
6887       V.buildTree(VL, ExternallyUsedValues, IgnoreList);
6888       Optional<ArrayRef<unsigned>> Order = V.bestOrder();
6889       // TODO: Handle orders of size less than number of elements in the vector.
6890       if (Order && Order->size() == VL.size()) {
6891         // TODO: reorder tree nodes without tree rebuilding.
6892         SmallVector<Value *, 4> ReorderedOps(VL.size());
6893         llvm::transform(*Order, ReorderedOps.begin(),
6894                         [VL](const unsigned Idx) { return VL[Idx]; });
6895         V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
6896       }
6897       if (V.isTreeTinyAndNotFullyVectorizable())
6898         break;
6899       if (V.isLoadCombineReductionCandidate(ReductionData.getOpcode()))
6900         break;
6901 
6902       V.computeMinimumValueSizes();
6903 
6904       // Estimate cost.
6905       int TreeCost = V.getTreeCost();
6906       int ReductionCost = getReductionCost(TTI, ReducedVals[i], ReduxWidth);
6907       int Cost = TreeCost + ReductionCost;
6908       if (Cost >= -SLPCostThreshold) {
6909           V.getORE()->emit([&]() {
6910               return OptimizationRemarkMissed(
6911                          SV_NAME, "HorSLPNotBeneficial", cast<Instruction>(VL[0]))
6912                      << "Vectorizing horizontal reduction is possible"
6913                      << "but not beneficial with cost "
6914                      << ore::NV("Cost", Cost) << " and threshold "
6915                      << ore::NV("Threshold", -SLPCostThreshold);
6916           });
6917           break;
6918       }
6919 
6920       LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
6921                         << Cost << ". (HorRdx)\n");
6922       V.getORE()->emit([&]() {
6923           return OptimizationRemark(
6924                      SV_NAME, "VectorizedHorizontalReduction", cast<Instruction>(VL[0]))
6925           << "Vectorized horizontal reduction with cost "
6926           << ore::NV("Cost", Cost) << " and with tree size "
6927           << ore::NV("TreeSize", V.getTreeSize());
6928       });
6929 
6930       // Vectorize a tree.
6931       DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
6932       Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
6933 
6934       // Emit a reduction. For min/max, the root is a select, but the insertion
6935       // point is the compare condition of that select.
6936       Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
6937       if (ReductionData.isMinMax())
6938         Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
6939       else
6940         Builder.SetInsertPoint(RdxRootInst);
6941 
6942       Value *ReducedSubTree =
6943           emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
6944       if (VectorizedTree) {
6945         Builder.SetCurrentDebugLocation(Loc);
6946         OperationData VectReductionData(ReductionData.getOpcode(),
6947                                         VectorizedTree, ReducedSubTree,
6948                                         ReductionData.getKind());
6949         VectorizedTree =
6950             VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
6951       } else
6952         VectorizedTree = ReducedSubTree;
6953       i += ReduxWidth;
6954       ReduxWidth = PowerOf2Floor(NumReducedVals - i);
6955     }
6956 
6957     if (VectorizedTree) {
6958       // Finish the reduction.
6959       for (; i < NumReducedVals; ++i) {
6960         auto *I = cast<Instruction>(ReducedVals[i]);
6961         Builder.SetCurrentDebugLocation(I->getDebugLoc());
6962         OperationData VectReductionData(ReductionData.getOpcode(),
6963                                         VectorizedTree, I,
6964                                         ReductionData.getKind());
6965         VectorizedTree = VectReductionData.createOp(Builder, "", ReductionOps);
6966       }
6967       for (auto &Pair : ExternallyUsedValues) {
6968         // Add each externally used value to the final reduction.
6969         for (auto *I : Pair.second) {
6970           Builder.SetCurrentDebugLocation(I->getDebugLoc());
6971           OperationData VectReductionData(ReductionData.getOpcode(),
6972                                           VectorizedTree, Pair.first,
6973                                           ReductionData.getKind());
6974           VectorizedTree = VectReductionData.createOp(Builder, "op.extra", I);
6975         }
6976       }
6977 
6978       // Update users. For a min/max reduction that ends with a compare and
6979       // select, we also have to RAUW for the compare instruction feeding the
6980       // reduction root. That's because the original compare may have extra uses
6981       // besides the final select of the reduction.
6982       if (ReductionData.isMinMax()) {
6983         if (auto *VecSelect = dyn_cast<SelectInst>(VectorizedTree)) {
6984           Instruction *ScalarCmp =
6985               getCmpForMinMaxReduction(cast<Instruction>(ReductionRoot));
6986           ScalarCmp->replaceAllUsesWith(VecSelect->getCondition());
6987         }
6988       }
6989       ReductionRoot->replaceAllUsesWith(VectorizedTree);
6990 
6991       // Mark all scalar reduction ops for deletion, they are replaced by the
6992       // vector reductions.
6993       V.eraseInstructions(IgnoreList);
6994     }
6995     return VectorizedTree != nullptr;
6996   }
6997 
6998   unsigned numReductionValues() const {
6999     return ReducedVals.size();
7000   }
7001 
7002 private:
7003   /// Calculate the cost of a reduction.
7004   int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
7005                        unsigned ReduxWidth) {
7006     Type *ScalarTy = FirstReducedVal->getType();
7007     auto *VecTy = FixedVectorType::get(ScalarTy, ReduxWidth);
7008 
7009     int PairwiseRdxCost;
7010     int SplittingRdxCost;
7011     switch (ReductionData.getKind()) {
7012     case RK_Arithmetic:
7013       PairwiseRdxCost =
7014           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
7015                                           /*IsPairwiseForm=*/true);
7016       SplittingRdxCost =
7017           TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
7018                                           /*IsPairwiseForm=*/false);
7019       break;
7020     case RK_Min:
7021     case RK_Max:
7022     case RK_UMin:
7023     case RK_UMax: {
7024       auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VecTy));
7025       bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
7026                         ReductionData.getKind() == RK_UMax;
7027       PairwiseRdxCost =
7028           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
7029                                       /*IsPairwiseForm=*/true, IsUnsigned);
7030       SplittingRdxCost =
7031           TTI->getMinMaxReductionCost(VecTy, VecCondTy,
7032                                       /*IsPairwiseForm=*/false, IsUnsigned);
7033       break;
7034     }
7035     case RK_None:
7036       llvm_unreachable("Expected arithmetic or min/max reduction operation");
7037     }
7038 
7039     IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
7040     int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
7041 
7042     int ScalarReduxCost = 0;
7043     switch (ReductionData.getKind()) {
7044     case RK_Arithmetic:
7045       ScalarReduxCost =
7046           TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
7047       break;
7048     case RK_Min:
7049     case RK_Max:
7050     case RK_UMin:
7051     case RK_UMax:
7052       ScalarReduxCost =
7053           TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
7054           TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
7055                                   CmpInst::makeCmpResultType(ScalarTy));
7056       break;
7057     case RK_None:
7058       llvm_unreachable("Expected arithmetic or min/max reduction operation");
7059     }
7060     ScalarReduxCost *= (ReduxWidth - 1);
7061 
7062     LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
7063                       << " for reduction that starts with " << *FirstReducedVal
7064                       << " (It is a "
7065                       << (IsPairwiseReduction ? "pairwise" : "splitting")
7066                       << " reduction)\n");
7067 
7068     return VecReduxCost - ScalarReduxCost;
7069   }
7070 
7071   /// Emit a horizontal reduction of the vectorized value.
7072   Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
7073                        unsigned ReduxWidth, const TargetTransformInfo *TTI) {
7074     assert(VectorizedValue && "Need to have a vectorized tree node");
7075     assert(isPowerOf2_32(ReduxWidth) &&
7076            "We only handle power-of-two reductions for now");
7077 
7078     if (!IsPairwiseReduction) {
7079       // FIXME: The builder should use an FMF guard. It should not be hard-coded
7080       //        to 'fast'.
7081       assert(Builder.getFastMathFlags().isFast() && "Expected 'fast' FMF");
7082       return createSimpleTargetReduction(
7083           Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
7084           ReductionData.getFlags(), ReductionOps.back());
7085     }
7086 
7087     Value *TmpVec = VectorizedValue;
7088     for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
7089       auto LeftMask = createRdxShuffleMask(ReduxWidth, i, true, true);
7090       auto RightMask = createRdxShuffleMask(ReduxWidth, i, true, false);
7091 
7092       Value *LeftShuf = Builder.CreateShuffleVector(
7093           TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
7094       Value *RightShuf = Builder.CreateShuffleVector(
7095           TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
7096           "rdx.shuf.r");
7097       OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
7098                                       RightShuf, ReductionData.getKind());
7099       TmpVec = VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
7100     }
7101 
7102     // The result is in the first element of the vector.
7103     return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
7104   }
7105 };
7106 
7107 } // end anonymous namespace
7108 
7109 static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
7110   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
7111     return cast<FixedVectorType>(IE->getType())->getNumElements();
7112 
7113   unsigned AggregateSize = 1;
7114   auto *IV = cast<InsertValueInst>(InsertInst);
7115   Type *CurrentType = IV->getType();
7116   do {
7117     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
7118       for (auto *Elt : ST->elements())
7119         if (Elt != ST->getElementType(0)) // check homogeneity
7120           return None;
7121       AggregateSize *= ST->getNumElements();
7122       CurrentType = ST->getElementType(0);
7123     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
7124       AggregateSize *= AT->getNumElements();
7125       CurrentType = AT->getElementType();
7126     } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
7127       AggregateSize *= VT->getNumElements();
7128       return AggregateSize;
7129     } else if (CurrentType->isSingleValueType()) {
7130       return AggregateSize;
7131     } else {
7132       return None;
7133     }
7134   } while (true);
7135 }
7136 
7137 static Optional<unsigned> getOperandIndex(Instruction *InsertInst,
7138                                           unsigned OperandOffset) {
7139   unsigned OperandIndex = OperandOffset;
7140   if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
7141     if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
7142       auto *VT = cast<FixedVectorType>(IE->getType());
7143       OperandIndex *= VT->getNumElements();
7144       OperandIndex += CI->getZExtValue();
7145       return OperandIndex;
7146     }
7147     return None;
7148   }
7149 
7150   auto *IV = cast<InsertValueInst>(InsertInst);
7151   Type *CurrentType = IV->getType();
7152   for (unsigned int Index : IV->indices()) {
7153     if (auto *ST = dyn_cast<StructType>(CurrentType)) {
7154       OperandIndex *= ST->getNumElements();
7155       CurrentType = ST->getElementType(Index);
7156     } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
7157       OperandIndex *= AT->getNumElements();
7158       CurrentType = AT->getElementType();
7159     } else {
7160       return None;
7161     }
7162     OperandIndex += Index;
7163   }
7164   return OperandIndex;
7165 }
7166 
7167 static bool findBuildAggregate_rec(Instruction *LastInsertInst,
7168                                    TargetTransformInfo *TTI,
7169                                    SmallVectorImpl<Value *> &BuildVectorOpds,
7170                                    SmallVectorImpl<Value *> &InsertElts,
7171                                    unsigned OperandOffset) {
7172   do {
7173     Value *InsertedOperand = LastInsertInst->getOperand(1);
7174     Optional<unsigned> OperandIndex =
7175         getOperandIndex(LastInsertInst, OperandOffset);
7176     if (!OperandIndex)
7177       return false;
7178     if (isa<InsertElementInst>(InsertedOperand) ||
7179         isa<InsertValueInst>(InsertedOperand)) {
7180       if (!findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
7181                                   BuildVectorOpds, InsertElts, *OperandIndex))
7182         return false;
7183     } else {
7184       BuildVectorOpds[*OperandIndex] = InsertedOperand;
7185       InsertElts[*OperandIndex] = LastInsertInst;
7186     }
7187     if (isa<UndefValue>(LastInsertInst->getOperand(0)))
7188       return true;
7189     LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
7190   } while (LastInsertInst != nullptr &&
7191            (isa<InsertValueInst>(LastInsertInst) ||
7192             isa<InsertElementInst>(LastInsertInst)) &&
7193            LastInsertInst->hasOneUse());
7194   return false;
7195 }
7196 
7197 /// Recognize construction of vectors like
7198 ///  %ra = insertelement <4 x float> undef, float %s0, i32 0
7199 ///  %rb = insertelement <4 x float> %ra, float %s1, i32 1
7200 ///  %rc = insertelement <4 x float> %rb, float %s2, i32 2
7201 ///  %rd = insertelement <4 x float> %rc, float %s3, i32 3
7202 ///  starting from the last insertelement or insertvalue instruction.
7203 ///
7204 /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
7205 /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
7206 /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
7207 ///
7208 /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
7209 ///
7210 /// \return true if it matches.
7211 static bool findBuildAggregate(Instruction *LastInsertInst,
7212                                TargetTransformInfo *TTI,
7213                                SmallVectorImpl<Value *> &BuildVectorOpds,
7214                                SmallVectorImpl<Value *> &InsertElts) {
7215 
7216   assert((isa<InsertElementInst>(LastInsertInst) ||
7217           isa<InsertValueInst>(LastInsertInst)) &&
7218          "Expected insertelement or insertvalue instruction!");
7219 
7220   assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
7221          "Expected empty result vectors!");
7222 
7223   Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
7224   if (!AggregateSize)
7225     return false;
7226   BuildVectorOpds.resize(*AggregateSize);
7227   InsertElts.resize(*AggregateSize);
7228 
7229   if (findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts,
7230                              0)) {
7231     llvm::erase_if(BuildVectorOpds,
7232                    [](const Value *V) { return V == nullptr; });
7233     llvm::erase_if(InsertElts, [](const Value *V) { return V == nullptr; });
7234     if (BuildVectorOpds.size() >= 2)
7235       return true;
7236   }
7237 
7238   return false;
7239 }
7240 
7241 static bool PhiTypeSorterFunc(Value *V, Value *V2) {
7242   return V->getType() < V2->getType();
7243 }
7244 
7245 /// Try and get a reduction value from a phi node.
7246 ///
7247 /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
7248 /// if they come from either \p ParentBB or a containing loop latch.
7249 ///
7250 /// \returns A candidate reduction value if possible, or \code nullptr \endcode
7251 /// if not possible.
7252 static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
7253                                 BasicBlock *ParentBB, LoopInfo *LI) {
7254   // There are situations where the reduction value is not dominated by the
7255   // reduction phi. Vectorizing such cases has been reported to cause
7256   // miscompiles. See PR25787.
7257   auto DominatedReduxValue = [&](Value *R) {
7258     return isa<Instruction>(R) &&
7259            DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
7260   };
7261 
7262   Value *Rdx = nullptr;
7263 
7264   // Return the incoming value if it comes from the same BB as the phi node.
7265   if (P->getIncomingBlock(0) == ParentBB) {
7266     Rdx = P->getIncomingValue(0);
7267   } else if (P->getIncomingBlock(1) == ParentBB) {
7268     Rdx = P->getIncomingValue(1);
7269   }
7270 
7271   if (Rdx && DominatedReduxValue(Rdx))
7272     return Rdx;
7273 
7274   // Otherwise, check whether we have a loop latch to look at.
7275   Loop *BBL = LI->getLoopFor(ParentBB);
7276   if (!BBL)
7277     return nullptr;
7278   BasicBlock *BBLatch = BBL->getLoopLatch();
7279   if (!BBLatch)
7280     return nullptr;
7281 
7282   // There is a loop latch, return the incoming value if it comes from
7283   // that. This reduction pattern occasionally turns up.
7284   if (P->getIncomingBlock(0) == BBLatch) {
7285     Rdx = P->getIncomingValue(0);
7286   } else if (P->getIncomingBlock(1) == BBLatch) {
7287     Rdx = P->getIncomingValue(1);
7288   }
7289 
7290   if (Rdx && DominatedReduxValue(Rdx))
7291     return Rdx;
7292 
7293   return nullptr;
7294 }
7295 
7296 /// Attempt to reduce a horizontal reduction.
7297 /// If it is legal to match a horizontal reduction feeding the phi node \a P
7298 /// with reduction operators \a Root (or one of its operands) in a basic block
7299 /// \a BB, then check if it can be done. If horizontal reduction is not found
7300 /// and root instruction is a binary operation, vectorization of the operands is
7301 /// attempted.
7302 /// \returns true if a horizontal reduction was matched and reduced or operands
7303 /// of one of the binary instruction were vectorized.
7304 /// \returns false if a horizontal reduction was not matched (or not possible)
7305 /// or no vectorization of any binary operation feeding \a Root instruction was
7306 /// performed.
7307 static bool tryToVectorizeHorReductionOrInstOperands(
7308     PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
7309     TargetTransformInfo *TTI,
7310     const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
7311   if (!ShouldVectorizeHor)
7312     return false;
7313 
7314   if (!Root)
7315     return false;
7316 
7317   if (Root->getParent() != BB || isa<PHINode>(Root))
7318     return false;
7319   // Start analysis starting from Root instruction. If horizontal reduction is
7320   // found, try to vectorize it. If it is not a horizontal reduction or
7321   // vectorization is not possible or not effective, and currently analyzed
7322   // instruction is a binary operation, try to vectorize the operands, using
7323   // pre-order DFS traversal order. If the operands were not vectorized, repeat
7324   // the same procedure considering each operand as a possible root of the
7325   // horizontal reduction.
7326   // Interrupt the process if the Root instruction itself was vectorized or all
7327   // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
7328   SmallVector<std::pair<Instruction *, unsigned>, 8> Stack(1, {Root, 0});
7329   SmallPtrSet<Value *, 8> VisitedInstrs;
7330   bool Res = false;
7331   while (!Stack.empty()) {
7332     Instruction *Inst;
7333     unsigned Level;
7334     std::tie(Inst, Level) = Stack.pop_back_val();
7335     auto *BI = dyn_cast<BinaryOperator>(Inst);
7336     auto *SI = dyn_cast<SelectInst>(Inst);
7337     if (BI || SI) {
7338       HorizontalReduction HorRdx;
7339       if (HorRdx.matchAssociativeReduction(P, Inst)) {
7340         if (HorRdx.tryToReduce(R, TTI)) {
7341           Res = true;
7342           // Set P to nullptr to avoid re-analysis of phi node in
7343           // matchAssociativeReduction function unless this is the root node.
7344           P = nullptr;
7345           continue;
7346         }
7347       }
7348       if (P && BI) {
7349         Inst = dyn_cast<Instruction>(BI->getOperand(0));
7350         if (Inst == P)
7351           Inst = dyn_cast<Instruction>(BI->getOperand(1));
7352         if (!Inst) {
7353           // Set P to nullptr to avoid re-analysis of phi node in
7354           // matchAssociativeReduction function unless this is the root node.
7355           P = nullptr;
7356           continue;
7357         }
7358       }
7359     }
7360     // Set P to nullptr to avoid re-analysis of phi node in
7361     // matchAssociativeReduction function unless this is the root node.
7362     P = nullptr;
7363     if (Vectorize(Inst, R)) {
7364       Res = true;
7365       continue;
7366     }
7367 
7368     // Try to vectorize operands.
7369     // Continue analysis for the instruction from the same basic block only to
7370     // save compile time.
7371     if (++Level < RecursionMaxDepth)
7372       for (auto *Op : Inst->operand_values())
7373         if (VisitedInstrs.insert(Op).second)
7374           if (auto *I = dyn_cast<Instruction>(Op))
7375             if (!isa<PHINode>(I) && !R.isDeleted(I) && I->getParent() == BB)
7376               Stack.emplace_back(I, Level);
7377   }
7378   return Res;
7379 }
7380 
7381 bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
7382                                                  BasicBlock *BB, BoUpSLP &R,
7383                                                  TargetTransformInfo *TTI) {
7384   if (!V)
7385     return false;
7386   auto *I = dyn_cast<Instruction>(V);
7387   if (!I)
7388     return false;
7389 
7390   if (!isa<BinaryOperator>(I))
7391     P = nullptr;
7392   // Try to match and vectorize a horizontal reduction.
7393   auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
7394     return tryToVectorize(I, R);
7395   };
7396   return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
7397                                                   ExtraVectorization);
7398 }
7399 
7400 bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
7401                                                  BasicBlock *BB, BoUpSLP &R) {
7402   const DataLayout &DL = BB->getModule()->getDataLayout();
7403   if (!R.canMapToVector(IVI->getType(), DL))
7404     return false;
7405 
7406   SmallVector<Value *, 16> BuildVectorOpds;
7407   SmallVector<Value *, 16> BuildVectorInsts;
7408   if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
7409     return false;
7410 
7411   LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
7412   // Aggregate value is unlikely to be processed in vector register, we need to
7413   // extract scalars into scalar registers, so NeedExtraction is set true.
7414   return tryToVectorizeList(BuildVectorOpds, R, /*AllowReorder=*/false,
7415                             BuildVectorInsts);
7416 }
7417 
7418 bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
7419                                                    BasicBlock *BB, BoUpSLP &R) {
7420   SmallVector<Value *, 16> BuildVectorInsts;
7421   SmallVector<Value *, 16> BuildVectorOpds;
7422   if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
7423       (llvm::all_of(BuildVectorOpds,
7424                     [](Value *V) { return isa<ExtractElementInst>(V); }) &&
7425        isShuffle(BuildVectorOpds)))
7426     return false;
7427 
7428   // Vectorize starting with the build vector operands ignoring the BuildVector
7429   // instructions for the purpose of scheduling and user extraction.
7430   return tryToVectorizeList(BuildVectorOpds, R, /*AllowReorder=*/false,
7431                             BuildVectorInsts);
7432 }
7433 
7434 bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
7435                                          BoUpSLP &R) {
7436   if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
7437     return true;
7438 
7439   bool OpsChanged = false;
7440   for (int Idx = 0; Idx < 2; ++Idx) {
7441     OpsChanged |=
7442         vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
7443   }
7444   return OpsChanged;
7445 }
7446 
7447 bool SLPVectorizerPass::vectorizeSimpleInstructions(
7448     SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R) {
7449   bool OpsChanged = false;
7450   for (auto *I : reverse(Instructions)) {
7451     if (R.isDeleted(I))
7452       continue;
7453     if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
7454       OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
7455     else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
7456       OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
7457     else if (auto *CI = dyn_cast<CmpInst>(I))
7458       OpsChanged |= vectorizeCmpInst(CI, BB, R);
7459   }
7460   Instructions.clear();
7461   return OpsChanged;
7462 }
7463 
7464 bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
7465   bool Changed = false;
7466   SmallVector<Value *, 4> Incoming;
7467   SmallPtrSet<Value *, 16> VisitedInstrs;
7468   unsigned MaxVecRegSize = R.getMaxVecRegSize();
7469 
7470   bool HaveVectorizedPhiNodes = true;
7471   while (HaveVectorizedPhiNodes) {
7472     HaveVectorizedPhiNodes = false;
7473 
7474     // Collect the incoming values from the PHIs.
7475     Incoming.clear();
7476     for (Instruction &I : *BB) {
7477       PHINode *P = dyn_cast<PHINode>(&I);
7478       if (!P)
7479         break;
7480 
7481       if (!VisitedInstrs.count(P) && !R.isDeleted(P))
7482         Incoming.push_back(P);
7483     }
7484 
7485     // Sort by type.
7486     llvm::stable_sort(Incoming, PhiTypeSorterFunc);
7487 
7488     // Try to vectorize elements base on their type.
7489     for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
7490                                            E = Incoming.end();
7491          IncIt != E;) {
7492 
7493       // Look for the next elements with the same type.
7494       SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
7495       Type *EltTy = (*IncIt)->getType();
7496 
7497       assert(EltTy->isSized() &&
7498              "Instructions should all be sized at this point");
7499       TypeSize EltTS = DL->getTypeSizeInBits(EltTy);
7500       if (EltTS.isScalable()) {
7501         // For now, just ignore vectorizing scalable types.
7502         ++IncIt;
7503         continue;
7504       }
7505 
7506       unsigned EltSize = EltTS.getFixedSize();
7507       unsigned MaxNumElts = MaxVecRegSize / EltSize;
7508       if (MaxNumElts < 2) {
7509         ++IncIt;
7510         continue;
7511       }
7512 
7513       while (SameTypeIt != E &&
7514              (*SameTypeIt)->getType() == EltTy &&
7515              static_cast<unsigned>(SameTypeIt - IncIt) < MaxNumElts) {
7516         VisitedInstrs.insert(*SameTypeIt);
7517         ++SameTypeIt;
7518       }
7519 
7520       // Try to vectorize them.
7521       unsigned NumElts = (SameTypeIt - IncIt);
7522       LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("
7523                         << NumElts << ")\n");
7524       // The order in which the phi nodes appear in the program does not matter.
7525       // So allow tryToVectorizeList to reorder them if it is beneficial. This
7526       // is done when there are exactly two elements since tryToVectorizeList
7527       // asserts that there are only two values when AllowReorder is true.
7528       bool AllowReorder = NumElts == 2;
7529       if (NumElts > 1 &&
7530           tryToVectorizeList(makeArrayRef(IncIt, NumElts), R, AllowReorder)) {
7531         // Success start over because instructions might have been changed.
7532         HaveVectorizedPhiNodes = true;
7533         Changed = true;
7534         break;
7535       }
7536 
7537       // Start over at the next instruction of a different type (or the end).
7538       IncIt = SameTypeIt;
7539     }
7540   }
7541 
7542   VisitedInstrs.clear();
7543 
7544   SmallVector<Instruction *, 8> PostProcessInstructions;
7545   SmallDenseSet<Instruction *, 4> KeyNodes;
7546   for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
7547     // Skip instructions marked for the deletion.
7548     if (R.isDeleted(&*it))
7549       continue;
7550     // We may go through BB multiple times so skip the one we have checked.
7551     if (!VisitedInstrs.insert(&*it).second) {
7552       if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
7553           vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
7554         // We would like to start over since some instructions are deleted
7555         // and the iterator may become invalid value.
7556         Changed = true;
7557         it = BB->begin();
7558         e = BB->end();
7559       }
7560       continue;
7561     }
7562 
7563     if (isa<DbgInfoIntrinsic>(it))
7564       continue;
7565 
7566     // Try to vectorize reductions that use PHINodes.
7567     if (PHINode *P = dyn_cast<PHINode>(it)) {
7568       // Check that the PHI is a reduction PHI.
7569       if (P->getNumIncomingValues() != 2)
7570         return Changed;
7571 
7572       // Try to match and vectorize a horizontal reduction.
7573       if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
7574                                    TTI)) {
7575         Changed = true;
7576         it = BB->begin();
7577         e = BB->end();
7578         continue;
7579       }
7580       continue;
7581     }
7582 
7583     // Ran into an instruction without users, like terminator, or function call
7584     // with ignored return value, store. Ignore unused instructions (basing on
7585     // instruction type, except for CallInst and InvokeInst).
7586     if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
7587                             isa<InvokeInst>(it))) {
7588       KeyNodes.insert(&*it);
7589       bool OpsChanged = false;
7590       if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
7591         for (auto *V : it->operand_values()) {
7592           // Try to match and vectorize a horizontal reduction.
7593           OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
7594         }
7595       }
7596       // Start vectorization of post-process list of instructions from the
7597       // top-tree instructions to try to vectorize as many instructions as
7598       // possible.
7599       OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
7600       if (OpsChanged) {
7601         // We would like to start over since some instructions are deleted
7602         // and the iterator may become invalid value.
7603         Changed = true;
7604         it = BB->begin();
7605         e = BB->end();
7606         continue;
7607       }
7608     }
7609 
7610     if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
7611         isa<InsertValueInst>(it))
7612       PostProcessInstructions.push_back(&*it);
7613   }
7614 
7615   return Changed;
7616 }
7617 
7618 bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
7619   auto Changed = false;
7620   for (auto &Entry : GEPs) {
7621     // If the getelementptr list has fewer than two elements, there's nothing
7622     // to do.
7623     if (Entry.second.size() < 2)
7624       continue;
7625 
7626     LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
7627                       << Entry.second.size() << ".\n");
7628 
7629     // Process the GEP list in chunks suitable for the target's supported
7630     // vector size. If a vector register can't hold 1 element, we are done. We
7631     // are trying to vectorize the index computations, so the maximum number of
7632     // elements is based on the size of the index expression, rather than the
7633     // size of the GEP itself (the target's pointer size).
7634     unsigned MaxVecRegSize = R.getMaxVecRegSize();
7635     unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
7636     if (MaxVecRegSize < EltSize)
7637       continue;
7638 
7639     unsigned MaxElts = MaxVecRegSize / EltSize;
7640     for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
7641       auto Len = std::min<unsigned>(BE - BI, MaxElts);
7642       auto GEPList = makeArrayRef(&Entry.second[BI], Len);
7643 
7644       // Initialize a set a candidate getelementptrs. Note that we use a
7645       // SetVector here to preserve program order. If the index computations
7646       // are vectorizable and begin with loads, we want to minimize the chance
7647       // of having to reorder them later.
7648       SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
7649 
7650       // Some of the candidates may have already been vectorized after we
7651       // initially collected them. If so, they are marked as deleted, so remove
7652       // them from the set of candidates.
7653       Candidates.remove_if(
7654           [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
7655 
7656       // Remove from the set of candidates all pairs of getelementptrs with
7657       // constant differences. Such getelementptrs are likely not good
7658       // candidates for vectorization in a bottom-up phase since one can be
7659       // computed from the other. We also ensure all candidate getelementptr
7660       // indices are unique.
7661       for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
7662         auto *GEPI = GEPList[I];
7663         if (!Candidates.count(GEPI))
7664           continue;
7665         auto *SCEVI = SE->getSCEV(GEPList[I]);
7666         for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
7667           auto *GEPJ = GEPList[J];
7668           auto *SCEVJ = SE->getSCEV(GEPList[J]);
7669           if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
7670             Candidates.remove(GEPI);
7671             Candidates.remove(GEPJ);
7672           } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
7673             Candidates.remove(GEPJ);
7674           }
7675         }
7676       }
7677 
7678       // We break out of the above computation as soon as we know there are
7679       // fewer than two candidates remaining.
7680       if (Candidates.size() < 2)
7681         continue;
7682 
7683       // Add the single, non-constant index of each candidate to the bundle. We
7684       // ensured the indices met these constraints when we originally collected
7685       // the getelementptrs.
7686       SmallVector<Value *, 16> Bundle(Candidates.size());
7687       auto BundleIndex = 0u;
7688       for (auto *V : Candidates) {
7689         auto *GEP = cast<GetElementPtrInst>(V);
7690         auto *GEPIdx = GEP->idx_begin()->get();
7691         assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
7692         Bundle[BundleIndex++] = GEPIdx;
7693       }
7694 
7695       // Try and vectorize the indices. We are currently only interested in
7696       // gather-like cases of the form:
7697       //
7698       // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
7699       //
7700       // where the loads of "a", the loads of "b", and the subtractions can be
7701       // performed in parallel. It's likely that detecting this pattern in a
7702       // bottom-up phase will be simpler and less costly than building a
7703       // full-blown top-down phase beginning at the consecutive loads.
7704       Changed |= tryToVectorizeList(Bundle, R);
7705     }
7706   }
7707   return Changed;
7708 }
7709 
7710 bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
7711   bool Changed = false;
7712   // Attempt to sort and vectorize each of the store-groups.
7713   for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
7714        ++it) {
7715     if (it->second.size() < 2)
7716       continue;
7717 
7718     LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
7719                       << it->second.size() << ".\n");
7720 
7721     Changed |= vectorizeStores(it->second, R);
7722   }
7723   return Changed;
7724 }
7725 
7726 char SLPVectorizer::ID = 0;
7727 
7728 static const char lv_name[] = "SLP Vectorizer";
7729 
7730 INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
7731 INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
7732 INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
7733 INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
7734 INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
7735 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
7736 INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
7737 INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
7738 INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
7739 INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
7740 
7741 Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }
7742