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