LLVM 17.0.0git
SLPVectorizer.cpp
Go to the documentation of this file.
1//===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This pass implements the Bottom Up SLP vectorizer. It detects consecutive
10// stores that can be put together into vector-stores. Next, it attempts to
11// construct vectorizable tree using the use-def chains. If a profitable tree
12// was found, the SLP vectorizer performs vectorization on the tree.
13//
14// The pass is inspired by the work described in the paper:
15// "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
16//
17//===----------------------------------------------------------------------===//
18
20#include "llvm/ADT/DenseMap.h"
21#include "llvm/ADT/DenseSet.h"
24#include "llvm/ADT/STLExtras.h"
26#include "llvm/ADT/SetVector.h"
29#include "llvm/ADT/SmallSet.h"
31#include "llvm/ADT/Statistic.h"
32#include "llvm/ADT/iterator.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"
56#include "llvm/IR/Dominators.h"
57#include "llvm/IR/Function.h"
58#include "llvm/IR/IRBuilder.h"
59#include "llvm/IR/InstrTypes.h"
60#include "llvm/IR/Instruction.h"
63#include "llvm/IR/Intrinsics.h"
64#include "llvm/IR/Module.h"
65#include "llvm/IR/Operator.h"
67#include "llvm/IR/Type.h"
68#include "llvm/IR/Use.h"
69#include "llvm/IR/User.h"
70#include "llvm/IR/Value.h"
71#include "llvm/IR/ValueHandle.h"
72#ifdef EXPENSIVE_CHECKS
73#include "llvm/IR/Verifier.h"
74#endif
75#include "llvm/Pass.h"
80#include "llvm/Support/Debug.h"
91#include <algorithm>
92#include <cassert>
93#include <cstdint>
94#include <iterator>
95#include <memory>
96#include <optional>
97#include <set>
98#include <string>
99#include <tuple>
100#include <utility>
101#include <vector>
102
103using namespace llvm;
104using namespace llvm::PatternMatch;
105using namespace slpvectorizer;
106
107#define SV_NAME "slp-vectorizer"
108#define DEBUG_TYPE "SLP"
109
110STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
111
113 cl::desc("Run the SLP vectorization passes"));
114
115static cl::opt<int>
117 cl::desc("Only vectorize if you gain more than this "
118 "number "));
119
120static cl::opt<bool>
121ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
122 cl::desc("Attempt to vectorize horizontal reductions"));
123
125 "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
126 cl::desc(
127 "Attempt to vectorize horizontal reductions feeding into a store"));
128
129static cl::opt<int>
131 cl::desc("Attempt to vectorize for this register size in bits"));
132
135 cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
136
137static cl::opt<int>
138MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
139 cl::desc("Maximum depth of the lookup for consecutive stores."));
140
141/// Limits the size of scheduling regions in a block.
142/// It avoid long compile times for _very_ large blocks where vector
143/// instructions are spread over a wide range.
144/// This limit is way higher than needed by real-world functions.
145static cl::opt<int>
146ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
147 cl::desc("Limit the size of the SLP scheduling region per block"));
148
150 "slp-min-reg-size", cl::init(128), cl::Hidden,
151 cl::desc("Attempt to vectorize for this register size in bits"));
152
154 "slp-recursion-max-depth", cl::init(12), cl::Hidden,
155 cl::desc("Limit the recursion depth when building a vectorizable tree"));
156
158 "slp-min-tree-size", cl::init(3), cl::Hidden,
159 cl::desc("Only vectorize small trees if they are fully vectorizable"));
160
161// The maximum depth that the look-ahead score heuristic will explore.
162// The higher this value, the higher the compilation time overhead.
164 "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
165 cl::desc("The maximum look-ahead depth for operand reordering scores"));
166
167// The maximum depth that the look-ahead score heuristic will explore
168// when it probing among candidates for vectorization tree roots.
169// The higher this value, the higher the compilation time overhead but unlike
170// similar limit for operands ordering this is less frequently used, hence
171// impact of higher value is less noticeable.
173 "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden,
174 cl::desc("The maximum look-ahead depth for searching best rooting option"));
175
176static cl::opt<bool>
177 ViewSLPTree("view-slp-tree", cl::Hidden,
178 cl::desc("Display the SLP trees with Graphviz"));
179
180// Limit the number of alias checks. The limit is chosen so that
181// it has no negative effect on the llvm benchmarks.
182static const unsigned AliasedCheckLimit = 10;
183
184// Another limit for the alias checks: The maximum distance between load/store
185// instructions where alias checks are done.
186// This limit is useful for very large basic blocks.
187static const unsigned MaxMemDepDistance = 160;
188
189/// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
190/// regions to be handled.
191static const int MinScheduleRegionSize = 16;
192
193/// Predicate for the element types that the SLP vectorizer supports.
194///
195/// The most important thing to filter here are types which are invalid in LLVM
196/// vectors. We also filter target specific types which have absolutely no
197/// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
198/// avoids spending time checking the cost model and realizing that they will
199/// be inevitably scalarized.
200static bool isValidElementType(Type *Ty) {
201 return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
202 !Ty->isPPC_FP128Ty();
203}
204
205/// \returns True if the value is a constant (but not globals/constant
206/// expressions).
207static bool isConstant(Value *V) {
208 return isa<Constant>(V) && !isa<ConstantExpr, GlobalValue>(V);
209}
210
211/// Checks if \p V is one of vector-like instructions, i.e. undef,
212/// insertelement/extractelement with constant indices for fixed vector type or
213/// extractvalue instruction.
215 if (!isa<InsertElementInst, ExtractElementInst>(V) &&
216 !isa<ExtractValueInst, UndefValue>(V))
217 return false;
218 auto *I = dyn_cast<Instruction>(V);
219 if (!I || isa<ExtractValueInst>(I))
220 return true;
221 if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
222 return false;
223 if (isa<ExtractElementInst>(I))
224 return isConstant(I->getOperand(1));
225 assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
226 return isConstant(I->getOperand(2));
227}
228
229/// \returns true if all of the instructions in \p VL are in the same block or
230/// false otherwise.
232 Instruction *I0 = dyn_cast<Instruction>(VL[0]);
233 if (!I0)
234 return false;
236 return true;
237
238 BasicBlock *BB = I0->getParent();
239 for (int I = 1, E = VL.size(); I < E; I++) {
240 auto *II = dyn_cast<Instruction>(VL[I]);
241 if (!II)
242 return false;
243
244 if (BB != II->getParent())
245 return false;
246 }
247 return true;
248}
249
250/// \returns True if all of the values in \p VL are constants (but not
251/// globals/constant expressions).
253 // Constant expressions and globals can't be vectorized like normal integer/FP
254 // constants.
255 return all_of(VL, isConstant);
256}
257
258/// \returns True if all of the values in \p VL are identical or some of them
259/// are UndefValue.
260static bool isSplat(ArrayRef<Value *> VL) {
261 Value *FirstNonUndef = nullptr;
262 for (Value *V : VL) {
263 if (isa<UndefValue>(V))
264 continue;
265 if (!FirstNonUndef) {
266 FirstNonUndef = V;
267 continue;
268 }
269 if (V != FirstNonUndef)
270 return false;
271 }
272 return FirstNonUndef != nullptr;
273}
274
275/// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
277 if (auto *Cmp = dyn_cast<CmpInst>(I))
278 return Cmp->isCommutative();
279 if (auto *BO = dyn_cast<BinaryOperator>(I))
280 return BO->isCommutative();
281 // TODO: This should check for generic Instruction::isCommutative(), but
282 // we need to confirm that the caller code correctly handles Intrinsics
283 // for example (does not have 2 operands).
284 return false;
285}
286
287/// \returns inserting index of InsertElement or InsertValue instruction,
288/// using Offset as base offset for index.
289static std::optional<unsigned> getInsertIndex(const Value *InsertInst,
290 unsigned Offset = 0) {
291 int Index = Offset;
292 if (const auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
293 const auto *VT = dyn_cast<FixedVectorType>(IE->getType());
294 if (!VT)
295 return std::nullopt;
296 const auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2));
297 if (!CI)
298 return std::nullopt;
299 if (CI->getValue().uge(VT->getNumElements()))
300 return std::nullopt;
301 Index *= VT->getNumElements();
302 Index += CI->getZExtValue();
303 return Index;
304 }
305
306 const auto *IV = cast<InsertValueInst>(InsertInst);
307 Type *CurrentType = IV->getType();
308 for (unsigned I : IV->indices()) {
309 if (const auto *ST = dyn_cast<StructType>(CurrentType)) {
310 Index *= ST->getNumElements();
311 CurrentType = ST->getElementType(I);
312 } else if (const auto *AT = dyn_cast<ArrayType>(CurrentType)) {
313 Index *= AT->getNumElements();
314 CurrentType = AT->getElementType();
315 } else {
316 return std::nullopt;
317 }
318 Index += I;
319 }
320 return Index;
321}
322
323namespace {
324/// Specifies the way the mask should be analyzed for undefs/poisonous elements
325/// in the shuffle mask.
326enum class UseMask {
327 FirstArg, ///< The mask is expected to be for permutation of 1-2 vectors,
328 ///< check for the mask elements for the first argument (mask
329 ///< indices are in range [0:VF)).
330 SecondArg, ///< The mask is expected to be for permutation of 2 vectors, check
331 ///< for the mask elements for the second argument (mask indices
332 ///< are in range [VF:2*VF))
333 UndefsAsMask ///< Consider undef mask elements (-1) as placeholders for
334 ///< future shuffle elements and mark them as ones as being used
335 ///< in future. Non-undef elements are considered as unused since
336 ///< they're already marked as used in the mask.
337};
338} // namespace
339
340/// Prepares a use bitset for the given mask either for the first argument or
341/// for the second.
343 UseMask MaskArg) {
344 SmallBitVector UseMask(VF, true);
345 for (auto P : enumerate(Mask)) {
346 if (P.value() == UndefMaskElem) {
347 if (MaskArg == UseMask::UndefsAsMask)
348 UseMask.reset(P.index());
349 continue;
350 }
351 if (MaskArg == UseMask::FirstArg && P.value() < VF)
352 UseMask.reset(P.value());
353 else if (MaskArg == UseMask::SecondArg && P.value() >= VF)
354 UseMask.reset(P.value() - VF);
355 }
356 return UseMask;
357}
358
359/// Checks if the given value is actually an undefined constant vector.
360/// Also, if the \p UseMask is not empty, tries to check if the non-masked
361/// elements actually mask the insertelement buildvector, if any.
362template <bool IsPoisonOnly = false>
364 const SmallBitVector &UseMask = {}) {
365 SmallBitVector Res(UseMask.empty() ? 1 : UseMask.size(), true);
366 using T = std::conditional_t<IsPoisonOnly, PoisonValue, UndefValue>;
367 if (isa<T>(V))
368 return Res;
369 auto *VecTy = dyn_cast<FixedVectorType>(V->getType());
370 if (!VecTy)
371 return Res.reset();
372 auto *C = dyn_cast<Constant>(V);
373 if (!C) {
374 if (!UseMask.empty()) {
375 const Value *Base = V;
376 while (auto *II = dyn_cast<InsertElementInst>(Base)) {
377 if (isa<T>(II->getOperand(1)))
378 continue;
379 Base = II->getOperand(0);
380 std::optional<unsigned> Idx = getInsertIndex(II);
381 if (!Idx)
382 continue;
383 if (*Idx < UseMask.size() && !UseMask.test(*Idx))
384 Res.reset(*Idx);
385 }
386 // TODO: Add analysis for shuffles here too.
387 if (V == Base) {
388 Res.reset();
389 } else {
390 SmallBitVector SubMask(UseMask.size(), false);
391 Res &= isUndefVector<IsPoisonOnly>(Base, SubMask);
392 }
393 } else {
394 Res.reset();
395 }
396 return Res;
397 }
398 for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
399 if (Constant *Elem = C->getAggregateElement(I))
400 if (!isa<T>(Elem) &&
401 (UseMask.empty() || (I < UseMask.size() && !UseMask.test(I))))
402 Res.reset(I);
403 }
404 return Res;
405}
406
407/// Checks if the vector of instructions can be represented as a shuffle, like:
408/// %x0 = extractelement <4 x i8> %x, i32 0
409/// %x3 = extractelement <4 x i8> %x, i32 3
410/// %y1 = extractelement <4 x i8> %y, i32 1
411/// %y2 = extractelement <4 x i8> %y, i32 2
412/// %x0x0 = mul i8 %x0, %x0
413/// %x3x3 = mul i8 %x3, %x3
414/// %y1y1 = mul i8 %y1, %y1
415/// %y2y2 = mul i8 %y2, %y2
416/// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
417/// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
418/// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
419/// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
420/// ret <4 x i8> %ins4
421/// can be transformed into:
422/// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
423/// i32 6>
424/// %2 = mul <4 x i8> %1, %1
425/// ret <4 x i8> %2
426/// We convert this initially to something like:
427/// %x0 = extractelement <4 x i8> %x, i32 0
428/// %x3 = extractelement <4 x i8> %x, i32 3
429/// %y1 = extractelement <4 x i8> %y, i32 1
430/// %y2 = extractelement <4 x i8> %y, i32 2
431/// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
432/// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
433/// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
434/// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
435/// %5 = mul <4 x i8> %4, %4
436/// %6 = extractelement <4 x i8> %5, i32 0
437/// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
438/// %7 = extractelement <4 x i8> %5, i32 1
439/// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
440/// %8 = extractelement <4 x i8> %5, i32 2
441/// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
442/// %9 = extractelement <4 x i8> %5, i32 3
443/// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
444/// ret <4 x i8> %ins4
445/// InstCombiner transforms this into a shuffle and vector mul
446/// Mask will return the Shuffle Mask equivalent to the extracted elements.
447/// TODO: Can we split off and reuse the shuffle mask detection from
448/// ShuffleVectorInst/getShuffleCost?
449static std::optional<TargetTransformInfo::ShuffleKind>
451 const auto *It =
452 find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
453 if (It == VL.end())
454 return std::nullopt;
455 auto *EI0 = cast<ExtractElementInst>(*It);
456 if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
457 return std::nullopt;
458 unsigned Size =
459 cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
460 Value *Vec1 = nullptr;
461 Value *Vec2 = nullptr;
462 enum ShuffleMode { Unknown, Select, Permute };
463 ShuffleMode CommonShuffleMode = Unknown;
464 Mask.assign(VL.size(), UndefMaskElem);
465 for (unsigned I = 0, E = VL.size(); I < E; ++I) {
466 // Undef can be represented as an undef element in a vector.
467 if (isa<UndefValue>(VL[I]))
468 continue;
469 auto *EI = cast<ExtractElementInst>(VL[I]);
470 if (isa<ScalableVectorType>(EI->getVectorOperandType()))
471 return std::nullopt;
472 auto *Vec = EI->getVectorOperand();
473 // We can extractelement from undef or poison vector.
474 if (isUndefVector(Vec).all())
475 continue;
476 // All vector operands must have the same number of vector elements.
477 if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
478 return std::nullopt;
479 if (isa<UndefValue>(EI->getIndexOperand()))
480 continue;
481 auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
482 if (!Idx)
483 return std::nullopt;
484 // Undefined behavior if Idx is negative or >= Size.
485 if (Idx->getValue().uge(Size))
486 continue;
487 unsigned IntIdx = Idx->getValue().getZExtValue();
488 Mask[I] = IntIdx;
489 // For correct shuffling we have to have at most 2 different vector operands
490 // in all extractelement instructions.
491 if (!Vec1 || Vec1 == Vec) {
492 Vec1 = Vec;
493 } else if (!Vec2 || Vec2 == Vec) {
494 Vec2 = Vec;
495 Mask[I] += Size;
496 } else {
497 return std::nullopt;
498 }
499 if (CommonShuffleMode == Permute)
500 continue;
501 // If the extract index is not the same as the operation number, it is a
502 // permutation.
503 if (IntIdx != I) {
504 CommonShuffleMode = Permute;
505 continue;
506 }
507 CommonShuffleMode = Select;
508 }
509 // If we're not crossing lanes in different vectors, consider it as blending.
510 if (CommonShuffleMode == Select && Vec2)
512 // If Vec2 was never used, we have a permutation of a single vector, otherwise
513 // we have permutation of 2 vectors.
516}
517
518/// \returns True if Extract{Value,Element} instruction extracts element Idx.
519static std::optional<unsigned> getExtractIndex(Instruction *E) {
520 unsigned Opcode = E->getOpcode();
521 assert((Opcode == Instruction::ExtractElement ||
522 Opcode == Instruction::ExtractValue) &&
523 "Expected extractelement or extractvalue instruction.");
524 if (Opcode == Instruction::ExtractElement) {
525 auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
526 if (!CI)
527 return std::nullopt;
528 return CI->getZExtValue();
529 }
530 auto *EI = cast<ExtractValueInst>(E);
531 if (EI->getNumIndices() != 1)
532 return std::nullopt;
533 return *EI->idx_begin();
534}
535
536namespace {
537
538/// Main data required for vectorization of instructions.
539struct InstructionsState {
540 /// The very first instruction in the list with the main opcode.
541 Value *OpValue = nullptr;
542
543 /// The main/alternate instruction.
544 Instruction *MainOp = nullptr;
545 Instruction *AltOp = nullptr;
546
547 /// The main/alternate opcodes for the list of instructions.
548 unsigned getOpcode() const {
549 return MainOp ? MainOp->getOpcode() : 0;
550 }
551
552 unsigned getAltOpcode() const {
553 return AltOp ? AltOp->getOpcode() : 0;
554 }
555
556 /// Some of the instructions in the list have alternate opcodes.
557 bool isAltShuffle() const { return AltOp != MainOp; }
558
559 bool isOpcodeOrAlt(Instruction *I) const {
560 unsigned CheckedOpcode = I->getOpcode();
561 return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
562 }
563
564 InstructionsState() = delete;
565 InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
566 : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
567};
568
569} // end anonymous namespace
570
571/// Chooses the correct key for scheduling data. If \p Op has the same (or
572/// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
573/// OpValue.
574static Value *isOneOf(const InstructionsState &S, Value *Op) {
575 auto *I = dyn_cast<Instruction>(Op);
576 if (I && S.isOpcodeOrAlt(I))
577 return Op;
578 return S.OpValue;
579}
580
581/// \returns true if \p Opcode is allowed as part of of the main/alternate
582/// instruction for SLP vectorization.
583///
584/// Example of unsupported opcode is SDIV that can potentially cause UB if the
585/// "shuffled out" lane would result in division by zero.
586static bool isValidForAlternation(unsigned Opcode) {
587 if (Instruction::isIntDivRem(Opcode))
588 return false;
589
590 return true;
591}
592
593static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
594 const TargetLibraryInfo &TLI,
595 unsigned BaseIndex = 0);
596
597/// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
598/// compatible instructions or constants, or just some other regular values.
599static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
600 Value *Op1, const TargetLibraryInfo &TLI) {
601 return (isConstant(BaseOp0) && isConstant(Op0)) ||
602 (isConstant(BaseOp1) && isConstant(Op1)) ||
603 (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
604 !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
605 BaseOp0 == Op0 || BaseOp1 == Op1 ||
606 getSameOpcode({BaseOp0, Op0}, TLI).getOpcode() ||
607 getSameOpcode({BaseOp1, Op1}, TLI).getOpcode();
608}
609
610/// \returns true if a compare instruction \p CI has similar "look" and
611/// same predicate as \p BaseCI, "as is" or with its operands and predicate
612/// swapped, false otherwise.
613static bool isCmpSameOrSwapped(const CmpInst *BaseCI, const CmpInst *CI,
614 const TargetLibraryInfo &TLI) {
615 assert(BaseCI->getOperand(0)->getType() == CI->getOperand(0)->getType() &&
616 "Assessing comparisons of different types?");
617 CmpInst::Predicate BasePred = BaseCI->getPredicate();
618 CmpInst::Predicate Pred = CI->getPredicate();
620
621 Value *BaseOp0 = BaseCI->getOperand(0);
622 Value *BaseOp1 = BaseCI->getOperand(1);
623 Value *Op0 = CI->getOperand(0);
624 Value *Op1 = CI->getOperand(1);
625
626 return (BasePred == Pred &&
627 areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1, TLI)) ||
628 (BasePred == SwappedPred &&
629 areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0, TLI));
630}
631
632/// \returns analysis of the Instructions in \p VL described in
633/// InstructionsState, the Opcode that we suppose the whole list
634/// could be vectorized even if its structure is diverse.
635static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
636 const TargetLibraryInfo &TLI,
637 unsigned BaseIndex) {
638 // Make sure these are all Instructions.
639 if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
640 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
641
642 bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
643 bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
644 bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
645 CmpInst::Predicate BasePred =
646 IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
648 unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
649 unsigned AltOpcode = Opcode;
650 unsigned AltIndex = BaseIndex;
651
652 // Check for one alternate opcode from another BinaryOperator.
653 // TODO - generalize to support all operators (types, calls etc.).
654 auto *IBase = cast<Instruction>(VL[BaseIndex]);
655 Intrinsic::ID BaseID = 0;
656 SmallVector<VFInfo> BaseMappings;
657 if (auto *CallBase = dyn_cast<CallInst>(IBase)) {
659 BaseMappings = VFDatabase(*CallBase).getMappings(*CallBase);
660 if (!isTriviallyVectorizable(BaseID) && BaseMappings.empty())
661 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
662 }
663 for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
664 auto *I = cast<Instruction>(VL[Cnt]);
665 unsigned InstOpcode = I->getOpcode();
666 if (IsBinOp && isa<BinaryOperator>(I)) {
667 if (InstOpcode == Opcode || InstOpcode == AltOpcode)
668 continue;
669 if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
670 isValidForAlternation(Opcode)) {
671 AltOpcode = InstOpcode;
672 AltIndex = Cnt;
673 continue;
674 }
675 } else if (IsCastOp && isa<CastInst>(I)) {
676 Value *Op0 = IBase->getOperand(0);
677 Type *Ty0 = Op0->getType();
678 Value *Op1 = I->getOperand(0);
679 Type *Ty1 = Op1->getType();
680 if (Ty0 == Ty1) {
681 if (InstOpcode == Opcode || InstOpcode == AltOpcode)
682 continue;
683 if (Opcode == AltOpcode) {
685 isValidForAlternation(InstOpcode) &&
686 "Cast isn't safe for alternation, logic needs to be updated!");
687 AltOpcode = InstOpcode;
688 AltIndex = Cnt;
689 continue;
690 }
691 }
692 } else if (auto *Inst = dyn_cast<CmpInst>(VL[Cnt]); Inst && IsCmpOp) {
693 auto *BaseInst = cast<CmpInst>(VL[BaseIndex]);
694 Type *Ty0 = BaseInst->getOperand(0)->getType();
695 Type *Ty1 = Inst->getOperand(0)->getType();
696 if (Ty0 == Ty1) {
697 assert(InstOpcode == Opcode && "Expected same CmpInst opcode.");
698 // Check for compatible operands. If the corresponding operands are not
699 // compatible - need to perform alternate vectorization.
700 CmpInst::Predicate CurrentPred = Inst->getPredicate();
701 CmpInst::Predicate SwappedCurrentPred =
702 CmpInst::getSwappedPredicate(CurrentPred);
703
704 if (E == 2 &&
705 (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
706 continue;
707
708 if (isCmpSameOrSwapped(BaseInst, Inst, TLI))
709 continue;
710 auto *AltInst = cast<CmpInst>(VL[AltIndex]);
711 if (AltIndex != BaseIndex) {
712 if (isCmpSameOrSwapped(AltInst, Inst, TLI))
713 continue;
714 } else if (BasePred != CurrentPred) {
715 assert(
716 isValidForAlternation(InstOpcode) &&
717 "CmpInst isn't safe for alternation, logic needs to be updated!");
718 AltIndex = Cnt;
719 continue;
720 }
721 CmpInst::Predicate AltPred = AltInst->getPredicate();
722 if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
723 AltPred == CurrentPred || AltPred == SwappedCurrentPred)
724 continue;
725 }
726 } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) {
727 if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
728 if (Gep->getNumOperands() != 2 ||
729 Gep->getOperand(0)->getType() != IBase->getOperand(0)->getType())
730 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
731 } else if (auto *EI = dyn_cast<ExtractElementInst>(I)) {
733 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
734 } else if (auto *LI = dyn_cast<LoadInst>(I)) {
735 auto *BaseLI = cast<LoadInst>(IBase);
736 if (!LI->isSimple() || !BaseLI->isSimple())
737 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
738 } else if (auto *Call = dyn_cast<CallInst>(I)) {
739 auto *CallBase = cast<CallInst>(IBase);
740 if (Call->getCalledFunction() != CallBase->getCalledFunction())
741 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
742 if (Call->hasOperandBundles() &&
743 !std::equal(Call->op_begin() + Call->getBundleOperandsStartIndex(),
744 Call->op_begin() + Call->getBundleOperandsEndIndex(),
745 CallBase->op_begin() +
747 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
749 if (ID != BaseID)
750 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
751 if (!ID) {
753 if (Mappings.size() != BaseMappings.size() ||
754 Mappings.front().ISA != BaseMappings.front().ISA ||
755 Mappings.front().ScalarName != BaseMappings.front().ScalarName ||
756 Mappings.front().VectorName != BaseMappings.front().VectorName ||
757 Mappings.front().Shape.VF != BaseMappings.front().Shape.VF ||
758 Mappings.front().Shape.Parameters !=
759 BaseMappings.front().Shape.Parameters)
760 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
761 }
762 }
763 continue;
764 }
765 return InstructionsState(VL[BaseIndex], nullptr, nullptr);
766 }
767
768 return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
769 cast<Instruction>(VL[AltIndex]));
770}
771
772/// \returns true if all of the values in \p VL have the same type or false
773/// otherwise.
775 Type *Ty = VL[0]->getType();
776 for (int i = 1, e = VL.size(); i < e; i++)
777 if (VL[i]->getType() != Ty)
778 return false;
779
780 return true;
781}
782
783/// \returns True if in-tree use also needs extract. This refers to
784/// possible scalar operand in vectorized instruction.
785static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
786 TargetLibraryInfo *TLI) {
787 unsigned Opcode = UserInst->getOpcode();
788 switch (Opcode) {
789 case Instruction::Load: {
790 LoadInst *LI = cast<LoadInst>(UserInst);
791 return (LI->getPointerOperand() == Scalar);
792 }
793 case Instruction::Store: {
794 StoreInst *SI = cast<StoreInst>(UserInst);
795 return (SI->getPointerOperand() == Scalar);
796 }
797 case Instruction::Call: {
798 CallInst *CI = cast<CallInst>(UserInst);
800 for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
802 return (CI->getArgOperand(i) == Scalar);
803 }
804 [[fallthrough]];
805 }
806 default:
807 return false;
808 }
809}
810
811/// \returns the AA location that is being access by the instruction.
813 if (StoreInst *SI = dyn_cast<StoreInst>(I))
814 return MemoryLocation::get(SI);
815 if (LoadInst *LI = dyn_cast<LoadInst>(I))
816 return MemoryLocation::get(LI);
817 return MemoryLocation();
818}
819
820/// \returns True if the instruction is not a volatile or atomic load/store.
821static bool isSimple(Instruction *I) {
822 if (LoadInst *LI = dyn_cast<LoadInst>(I))
823 return LI->isSimple();
824 if (StoreInst *SI = dyn_cast<StoreInst>(I))
825 return SI->isSimple();
826 if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
827 return !MI->isVolatile();
828 return true;
829}
830
831/// Shuffles \p Mask in accordance with the given \p SubMask.
832static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
833 if (SubMask.empty())
834 return;
835 if (Mask.empty()) {
836 Mask.append(SubMask.begin(), SubMask.end());
837 return;
838 }
839 SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
840 int TermValue = std::min(Mask.size(), SubMask.size());
841 for (int I = 0, E = SubMask.size(); I < E; ++I) {
842 if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
843 Mask[SubMask[I]] >= TermValue)
844 continue;
845 NewMask[I] = Mask[SubMask[I]];
846 }
847 Mask.swap(NewMask);
848}
849
850/// Order may have elements assigned special value (size) which is out of
851/// bounds. Such indices only appear on places which correspond to undef values
852/// (see canReuseExtract for details) and used in order to avoid undef values
853/// have effect on operands ordering.
854/// The first loop below simply finds all unused indices and then the next loop
855/// nest assigns these indices for undef values positions.
856/// As an example below Order has two undef positions and they have assigned
857/// values 3 and 7 respectively:
858/// before: 6 9 5 4 9 2 1 0
859/// after: 6 3 5 4 7 2 1 0
861 const unsigned Sz = Order.size();
862 SmallBitVector UnusedIndices(Sz, /*t=*/true);
863 SmallBitVector MaskedIndices(Sz);
864 for (unsigned I = 0; I < Sz; ++I) {
865 if (Order[I] < Sz)
866 UnusedIndices.reset(Order[I]);
867 else
868 MaskedIndices.set(I);
869 }
870 if (MaskedIndices.none())
871 return;
872 assert(UnusedIndices.count() == MaskedIndices.count() &&
873 "Non-synced masked/available indices.");
874 int Idx = UnusedIndices.find_first();
875 int MIdx = MaskedIndices.find_first();
876 while (MIdx >= 0) {
877 assert(Idx >= 0 && "Indices must be synced.");
878 Order[MIdx] = Idx;
879 Idx = UnusedIndices.find_next(Idx);
880 MIdx = MaskedIndices.find_next(MIdx);
881 }
882}
883
884namespace llvm {
885
887 SmallVectorImpl<int> &Mask) {
888 Mask.clear();
889 const unsigned E = Indices.size();
890 Mask.resize(E, UndefMaskElem);
891 for (unsigned I = 0; I < E; ++I)
892 Mask[Indices[I]] = I;
893}
894
895/// Reorders the list of scalars in accordance with the given \p Mask.
897 ArrayRef<int> Mask) {
898 assert(!Mask.empty() && "Expected non-empty mask.");
899 SmallVector<Value *> Prev(Scalars.size(),
900 UndefValue::get(Scalars.front()->getType()));
901 Prev.swap(Scalars);
902 for (unsigned I = 0, E = Prev.size(); I < E; ++I)
903 if (Mask[I] != UndefMaskElem)
904 Scalars[Mask[I]] = Prev[I];
905}
906
907/// Checks if the provided value does not require scheduling. It does not
908/// require scheduling if this is not an instruction or it is an instruction
909/// that does not read/write memory and all operands are either not instructions
910/// or phi nodes or instructions from different blocks.
912 auto *I = dyn_cast<Instruction>(V);
913 if (!I)
914 return true;
915 return !mayHaveNonDefUseDependency(*I) &&
916 all_of(I->operands(), [I](Value *V) {
917 auto *IO = dyn_cast<Instruction>(V);
918 if (!IO)
919 return true;
920 return isa<PHINode>(IO) || IO->getParent() != I->getParent();
921 });
922}
923
924/// Checks if the provided value does not require scheduling. It does not
925/// require scheduling if this is not an instruction or it is an instruction
926/// that does not read/write memory and all users are phi nodes or instructions
927/// from the different blocks.
928static bool isUsedOutsideBlock(Value *V) {
929 auto *I = dyn_cast<Instruction>(V);
930 if (!I)
931 return true;
932 // Limits the number of uses to save compile time.
933 constexpr int UsesLimit = 8;
934 return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
935 all_of(I->users(), [I](User *U) {
936 auto *IU = dyn_cast<Instruction>(U);
937 if (!IU)
938 return true;
939 return IU->getParent() != I->getParent() || isa<PHINode>(IU);
940 });
941}
942
943/// Checks if the specified value does not require scheduling. It does not
944/// require scheduling if all operands and all users do not need to be scheduled
945/// in the current basic block.
948}
949
950/// Checks if the specified array of instructions does not require scheduling.
951/// It is so if all either instructions have operands that do not require
952/// scheduling or their users do not require scheduling since they are phis or
953/// in other basic blocks.
955 return !VL.empty() &&
957}
958
959namespace slpvectorizer {
960
961/// Bottom Up SLP Vectorizer.
962class BoUpSLP {
963 struct TreeEntry;
964 struct ScheduleData;
966
967public:
975
977 TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
980 : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
981 DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
983 // Use the vector register size specified by the target unless overridden
984 // by a command-line option.
985 // TODO: It would be better to limit the vectorization factor based on
986 // data type rather than just register size. For example, x86 AVX has
987 // 256-bit registers, but it does not support integer operations
988 // at that width (that requires AVX2).
989 if (MaxVectorRegSizeOption.getNumOccurrences())
990 MaxVecRegSize = MaxVectorRegSizeOption;
991 else
992 MaxVecRegSize =
994 .getFixedValue();
995
996 if (MinVectorRegSizeOption.getNumOccurrences())
997 MinVecRegSize = MinVectorRegSizeOption;
998 else
999 MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
1000 }
1001
1002 /// Vectorize the tree that starts with the elements in \p VL.
1003 /// Returns the vectorized root.
1005
1006 /// Vectorize the tree but with the list of externally used values \p
1007 /// ExternallyUsedValues. Values in this MapVector can be replaced but the
1008 /// generated extractvalue instructions.
1009 Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues,
1010 Instruction *ReductionRoot = nullptr);
1011
1012 /// \returns the cost incurred by unwanted spills and fills, caused by
1013 /// holding live values over call sites.
1015
1016 /// \returns the vectorization cost of the subtree that starts at \p VL.
1017 /// A negative number means that this is profitable.
1018 InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = std::nullopt);
1019
1020 /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
1021 /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
1022 void buildTree(ArrayRef<Value *> Roots,
1023 const SmallDenseSet<Value *> &UserIgnoreLst);
1024
1025 /// Construct a vectorizable tree that starts at \p Roots.
1026 void buildTree(ArrayRef<Value *> Roots);
1027
1028 /// Checks if the very first tree node is going to be vectorized.
1030 return !VectorizableTree.empty() &&
1031 VectorizableTree.front()->State == TreeEntry::Vectorize;
1032 }
1033
1034 /// Returns the main instruction for the very first node.
1036 assert(!VectorizableTree.empty() && "No tree to get the first node from");
1037 return VectorizableTree.front()->getMainOp();
1038 }
1039
1040 /// Returns whether the root node has in-tree uses.
1042 return !VectorizableTree.empty() &&
1043 !VectorizableTree.front()->UserTreeIndices.empty();
1044 }
1045
1046 /// Builds external uses of the vectorized scalars, i.e. the list of
1047 /// vectorized scalars to be extracted, their lanes and their scalar users. \p
1048 /// ExternallyUsedValues contains additional list of external uses to handle
1049 /// vectorization of reductions.
1050 void
1051 buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
1052
1053 /// Clear the internal data structures that are created by 'buildTree'.
1054 void deleteTree() {
1055 VectorizableTree.clear();
1056 ScalarToTreeEntry.clear();
1057 MustGather.clear();
1058 EntryToLastInstruction.clear();
1059 ExternalUses.clear();
1060 for (auto &Iter : BlocksSchedules) {
1061 BlockScheduling *BS = Iter.second.get();
1062 BS->clear();
1063 }
1064 MinBWs.clear();
1065 InstrElementSize.clear();
1066 UserIgnoreList = nullptr;
1067 }
1068
1069 unsigned getTreeSize() const { return VectorizableTree.size(); }
1070
1071 /// Perform LICM and CSE on the newly generated gather sequences.
1073
1074 /// Checks if the specified gather tree entry \p TE can be represented as a
1075 /// shuffled vector entry + (possibly) permutation with other gathers. It
1076 /// implements the checks only for possibly ordered scalars (Loads,
1077 /// ExtractElement, ExtractValue), which can be part of the graph.
1078 std::optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
1079
1080 /// Sort loads into increasing pointers offsets to allow greater clustering.
1081 std::optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE);
1082
1083 /// Gets reordering data for the given tree entry. If the entry is vectorized
1084 /// - just return ReorderIndices, otherwise check if the scalars can be
1085 /// reordered and return the most optimal order.
1086 /// \param TopToBottom If true, include the order of vectorized stores and
1087 /// insertelement nodes, otherwise skip them.
1088 std::optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
1089
1090 /// Reorders the current graph to the most profitable order starting from the
1091 /// root node to the leaf nodes. The best order is chosen only from the nodes
1092 /// of the same size (vectorization factor). Smaller nodes are considered
1093 /// parts of subgraph with smaller VF and they are reordered independently. We
1094 /// can make it because we still need to extend smaller nodes to the wider VF
1095 /// and we can merge reordering shuffles with the widening shuffles.
1096 void reorderTopToBottom();
1097
1098 /// Reorders the current graph to the most profitable order starting from
1099 /// leaves to the root. It allows to rotate small subgraphs and reduce the
1100 /// number of reshuffles if the leaf nodes use the same order. In this case we
1101 /// can merge the orders and just shuffle user node instead of shuffling its
1102 /// operands. Plus, even the leaf nodes have different orders, it allows to
1103 /// sink reordering in the graph closer to the root node and merge it later
1104 /// during analysis.
1105 void reorderBottomToTop(bool IgnoreReorder = false);
1106
1107 /// \return The vector element size in bits to use when vectorizing the
1108 /// expression tree ending at \p V. If V is a store, the size is the width of
1109 /// the stored value. Otherwise, the size is the width of the largest loaded
1110 /// value reaching V. This method is used by the vectorizer to calculate
1111 /// vectorization factors.
1112 unsigned getVectorElementSize(Value *V);
1113
1114 /// Compute the minimum type sizes required to represent the entries in a
1115 /// vectorizable tree.
1117
1118 // \returns maximum vector register size as set by TTI or overridden by cl::opt.
1119 unsigned getMaxVecRegSize() const {
1120 return MaxVecRegSize;
1121 }
1122
1123 // \returns minimum vector register size as set by cl::opt.
1124 unsigned getMinVecRegSize() const {
1125 return MinVecRegSize;
1126 }
1127
1128 unsigned getMinVF(unsigned Sz) const {
1129 return std::max(2U, getMinVecRegSize() / Sz);
1130 }
1131
1132 unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
1133 unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
1134 MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
1135 return MaxVF ? MaxVF : UINT_MAX;
1136 }
1137
1138 /// Check if homogeneous aggregate is isomorphic to some VectorType.
1139 /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
1140 /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
1141 /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
1142 ///
1143 /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
1144 unsigned canMapToVector(Type *T, const DataLayout &DL) const;
1145
1146 /// \returns True if the VectorizableTree is both tiny and not fully
1147 /// vectorizable. We do not vectorize such trees.
1148 bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
1149
1150 /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
1151 /// can be load combined in the backend. Load combining may not be allowed in
1152 /// the IR optimizer, so we do not want to alter the pattern. For example,
1153 /// partially transforming a scalar bswap() pattern into vector code is
1154 /// effectively impossible for the backend to undo.
1155 /// TODO: If load combining is allowed in the IR optimizer, this analysis
1156 /// may not be necessary.
1157 bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
1158
1159 /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
1160 /// can be load combined in the backend. Load combining may not be allowed in
1161 /// the IR optimizer, so we do not want to alter the pattern. For example,
1162 /// partially transforming a scalar bswap() pattern into vector code is
1163 /// effectively impossible for the backend to undo.
1164 /// TODO: If load combining is allowed in the IR optimizer, this analysis
1165 /// may not be necessary.
1166 bool isLoadCombineCandidate() const;
1167
1169
1170 /// This structure holds any data we need about the edges being traversed
1171 /// during buildTree_rec(). We keep track of:
1172 /// (i) the user TreeEntry index, and
1173 /// (ii) the index of the edge.
1174 struct EdgeInfo {
1175 EdgeInfo() = default;
1176 EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
1178 /// The user TreeEntry.
1179 TreeEntry *UserTE = nullptr;
1180 /// The operand index of the use.
1181 unsigned EdgeIdx = UINT_MAX;
1182#ifndef NDEBUG
1184 const BoUpSLP::EdgeInfo &EI) {
1185 EI.dump(OS);
1186 return OS;
1187 }
1188 /// Debug print.
1189 void dump(raw_ostream &OS) const {
1190 OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
1191 << " EdgeIdx:" << EdgeIdx << "}";
1192 }
1193 LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
1194#endif
1195 };
1196
1197 /// A helper class used for scoring candidates for two consecutive lanes.
1199 const TargetLibraryInfo &TLI;
1200 const DataLayout &DL;
1201 ScalarEvolution &SE;
1202 const BoUpSLP &R;
1203 int NumLanes; // Total number of lanes (aka vectorization factor).
1204 int MaxLevel; // The maximum recursion depth for accumulating score.
1205
1206 public:
1208 ScalarEvolution &SE, const BoUpSLP &R, int NumLanes,
1209 int MaxLevel)
1210 : TLI(TLI), DL(DL), SE(SE), R(R), NumLanes(NumLanes),
1211 MaxLevel(MaxLevel) {}
1212
1213 // The hard-coded scores listed here are not very important, though it shall
1214 // be higher for better matches to improve the resulting cost. When
1215 // computing the scores of matching one sub-tree with another, we are
1216 // basically counting the number of values that are matching. So even if all
1217 // scores are set to 1, we would still get a decent matching result.
1218 // However, sometimes we have to break ties. For example we may have to
1219 // choose between matching loads vs matching opcodes. This is what these
1220 // scores are helping us with: they provide the order of preference. Also,
1221 // this is important if the scalar is externally used or used in another
1222 // tree entry node in the different lane.
1223
1224 /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
1225 static const int ScoreConsecutiveLoads = 4;
1226 /// The same load multiple times. This should have a better score than
1227 /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
1228 /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
1229 /// a vector load and 1.0 for a broadcast.
1230 static const int ScoreSplatLoads = 3;
1231 /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
1232 static const int ScoreReversedLoads = 3;
1233 /// A load candidate for masked gather.
1234 static const int ScoreMaskedGatherCandidate = 1;
1235 /// ExtractElementInst from same vector and consecutive indexes.
1236 static const int ScoreConsecutiveExtracts = 4;
1237 /// ExtractElementInst from same vector and reversed indices.
1238 static const int ScoreReversedExtracts = 3;
1239 /// Constants.
1240 static const int ScoreConstants = 2;
1241 /// Instructions with the same opcode.
1242 static const int ScoreSameOpcode = 2;
1243 /// Instructions with alt opcodes (e.g, add + sub).
1244 static const int ScoreAltOpcodes = 1;
1245 /// Identical instructions (a.k.a. splat or broadcast).
1246 static const int ScoreSplat = 1;
1247 /// Matching with an undef is preferable to failing.
1248 static const int ScoreUndef = 1;
1249 /// Score for failing to find a decent match.
1250 static const int ScoreFail = 0;
1251 /// Score if all users are vectorized.
1252 static const int ScoreAllUserVectorized = 1;
1253
1254 /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
1255 /// \p U1 and \p U2 are the users of \p V1 and \p V2.
1256 /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
1257 /// MainAltOps.
1259 ArrayRef<Value *> MainAltOps) const {
1260 if (!isValidElementType(V1->getType()) ||
1261 !isValidElementType(V2->getType()))
1263
1264 if (V1 == V2) {
1265 if (isa<LoadInst>(V1)) {
1266 // Retruns true if the users of V1 and V2 won't need to be extracted.
1267 auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
1268 // Bail out if we have too many uses to save compilation time.
1269 static constexpr unsigned Limit = 8;
1270 if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
1271 return false;
1272
1273 auto AllUsersVectorized = [U1, U2, this](Value *V) {
1274 return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
1275 return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
1276 });
1277 };
1278 return AllUsersVectorized(V1) && AllUsersVectorized(V2);
1279 };
1280 // A broadcast of a load can be cheaper on some targets.
1281 if (R.TTI->isLegalBroadcastLoad(V1->getType(),
1282 ElementCount::getFixed(NumLanes)) &&
1283 ((int)V1->getNumUses() == NumLanes ||
1284 AllUsersAreInternal(V1, V2)))
1286 }
1288 }
1289
1290 auto *LI1 = dyn_cast<LoadInst>(V1);
1291 auto *LI2 = dyn_cast<LoadInst>(V2);
1292 if (LI1 && LI2) {
1293 if (LI1->getParent() != LI2->getParent() || !LI1->isSimple() ||
1294 !LI2->isSimple())
1296
1297 std::optional<int> Dist = getPointersDiff(
1298 LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
1299 LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
1300 if (!Dist || *Dist == 0) {
1301 if (getUnderlyingObject(LI1->getPointerOperand()) ==
1302 getUnderlyingObject(LI2->getPointerOperand()) &&
1303 R.TTI->isLegalMaskedGather(
1304 FixedVectorType::get(LI1->getType(), NumLanes),
1305 LI1->getAlign()))
1308 }
1309 // The distance is too large - still may be profitable to use masked
1310 // loads/gathers.
1311 if (std::abs(*Dist) > NumLanes / 2)
1313 // This still will detect consecutive loads, but we might have "holes"
1314 // in some cases. It is ok for non-power-2 vectorization and may produce
1315 // better results. It should not affect current vectorization.
1318 }
1319
1320 auto *C1 = dyn_cast<Constant>(V1);
1321 auto *C2 = dyn_cast<Constant>(V2);
1322 if (C1 && C2)
1324
1325 // Extracts from consecutive indexes of the same vector better score as
1326 // the extracts could be optimized away.
1327 Value *EV1;
1328 ConstantInt *Ex1Idx;
1329 if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
1330 // Undefs are always profitable for extractelements.
1331 if (isa<UndefValue>(V2))
1333 Value *EV2 = nullptr;
1334 ConstantInt *Ex2Idx = nullptr;
1335 if (match(V2,
1337 m_Undef())))) {
1338 // Undefs are always profitable for extractelements.
1339 if (!Ex2Idx)
1341 if (isUndefVector(EV2).all() && EV2->getType() == EV1->getType())
1343 if (EV2 == EV1) {
1344 int Idx1 = Ex1Idx->getZExtValue();
1345 int Idx2 = Ex2Idx->getZExtValue();
1346 int Dist = Idx2 - Idx1;
1347 // The distance is too large - still may be profitable to use
1348 // shuffles.
1349 if (std::abs(Dist) == 0)
1351 if (std::abs(Dist) > NumLanes / 2)
1355 }
1357 }
1359 }
1360
1361 auto *I1 = dyn_cast<Instruction>(V1);
1362 auto *I2 = dyn_cast<Instruction>(V2);
1363 if (I1 && I2) {
1364 if (I1->getParent() != I2->getParent())
1366 SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
1367 Ops.push_back(I1);
1368 Ops.push_back(I2);
1369 InstructionsState S = getSameOpcode(Ops, TLI);
1370 // Note: Only consider instructions with <= 2 operands to avoid
1371 // complexity explosion.
1372 if (S.getOpcode() &&
1373 (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
1374 !S.isAltShuffle()) &&
1375 all_of(Ops, [&S](Value *V) {
1376 return cast<Instruction>(V)->getNumOperands() ==
1377 S.MainOp->getNumOperands();
1378 }))
1379 return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
1381 }
1382
1383 if (isa<UndefValue>(V2))
1385
1387 }
1388
1389 /// Go through the operands of \p LHS and \p RHS recursively until
1390 /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
1391 /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
1392 /// of \p U1 and \p U2), except at the beginning of the recursion where
1393 /// these are set to nullptr.
1394 ///
1395 /// For example:
1396 /// \verbatim
1397 /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1]
1398 /// \ / \ / \ / \ /
1399 /// + + + +
1400 /// G1 G2 G3 G4
1401 /// \endverbatim
1402 /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
1403 /// each level recursively, accumulating the score. It starts from matching
1404 /// the additions at level 0, then moves on to the loads (level 1). The
1405 /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
1406 /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
1407 /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
1408 /// Please note that the order of the operands does not matter, as we
1409 /// evaluate the score of all profitable combinations of operands. In
1410 /// other words the score of G1 and G4 is the same as G1 and G2. This
1411 /// heuristic is based on ideas described in:
1412 /// Look-ahead SLP: Auto-vectorization in the presence of commutative
1413 /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
1414 /// Luís F. W. Góes
1416 Instruction *U2, int CurrLevel,
1417 ArrayRef<Value *> MainAltOps) const {
1418
1419 // Get the shallow score of V1 and V2.
1420 int ShallowScoreAtThisLevel =
1421 getShallowScore(LHS, RHS, U1, U2, MainAltOps);
1422
1423 // If reached MaxLevel,
1424 // or if V1 and V2 are not instructions,
1425 // or if they are SPLAT,
1426 // or if they are not consecutive,
1427 // or if profitable to vectorize loads or extractelements, early return
1428 // the current cost.
1429 auto *I1 = dyn_cast<Instruction>(LHS);
1430 auto *I2 = dyn_cast<Instruction>(RHS);
1431 if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
1432 ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
1433 (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
1434 (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
1435 (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
1436 ShallowScoreAtThisLevel))
1437 return ShallowScoreAtThisLevel;
1438 assert(I1 && I2 && "Should have early exited.");
1439
1440 // Contains the I2 operand indexes that got matched with I1 operands.
1441 SmallSet<unsigned, 4> Op2Used;
1442
1443 // Recursion towards the operands of I1 and I2. We are trying all possible
1444 // operand pairs, and keeping track of the best score.
1445 for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
1446 OpIdx1 != NumOperands1; ++OpIdx1) {
1447 // Try to pair op1I with the best operand of I2.
1448 int MaxTmpScore = 0;
1449 unsigned MaxOpIdx2 = 0;
1450 bool FoundBest = false;
1451 // If I2 is commutative try all combinations.
1452 unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
1453 unsigned ToIdx = isCommutative(I2)
1454 ? I2->getNumOperands()
1455 : std::min(I2->getNumOperands(), OpIdx1 + 1);
1456 assert(FromIdx <= ToIdx && "Bad index");
1457 for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
1458 // Skip operands already paired with OpIdx1.
1459 if (Op2Used.count(OpIdx2))
1460 continue;
1461 // Recursively calculate the cost at each level
1462 int TmpScore =
1463 getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
1464 I1, I2, CurrLevel + 1, std::nullopt);
1465 // Look for the best score.
1466 if (TmpScore > LookAheadHeuristics::ScoreFail &&
1467 TmpScore > MaxTmpScore) {
1468 MaxTmpScore = TmpScore;
1469 MaxOpIdx2 = OpIdx2;
1470 FoundBest = true;
1471 }
1472 }
1473 if (FoundBest) {
1474 // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
1475 Op2Used.insert(MaxOpIdx2);
1476 ShallowScoreAtThisLevel += MaxTmpScore;
1477 }
1478 }
1479 return ShallowScoreAtThisLevel;
1480 }
1481 };
1482 /// A helper data structure to hold the operands of a vector of instructions.
1483 /// This supports a fixed vector length for all operand vectors.
1485 /// For each operand we need (i) the value, and (ii) the opcode that it
1486 /// would be attached to if the expression was in a left-linearized form.
1487 /// This is required to avoid illegal operand reordering.
1488 /// For example:
1489 /// \verbatim
1490 /// 0 Op1
1491 /// |/
1492 /// Op1 Op2 Linearized + Op2
1493 /// \ / ----------> |/
1494 /// - -
1495 ///
1496 /// Op1 - Op2 (0 + Op1) - Op2
1497 /// \endverbatim
1498 ///
1499 /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
1500 ///
1501 /// Another way to think of this is to track all the operations across the
1502 /// path from the operand all the way to the root of the tree and to
1503 /// calculate the operation that corresponds to this path. For example, the
1504 /// path from Op2 to the root crosses the RHS of the '-', therefore the
1505 /// corresponding operation is a '-' (which matches the one in the
1506 /// linearized tree, as shown above).
1507 ///
1508 /// For lack of a better term, we refer to this operation as Accumulated
1509 /// Path Operation (APO).
1510 struct OperandData {
1511 OperandData() = default;
1512 OperandData(Value *V, bool APO, bool IsUsed)
1513 : V(V), APO(APO), IsUsed(IsUsed) {}
1514 /// The operand value.
1515 Value *V = nullptr;
1516 /// TreeEntries only allow a single opcode, or an alternate sequence of
1517 /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
1518 /// APO. It is set to 'true' if 'V' is attached to an inverse operation
1519 /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
1520 /// (e.g., Add/Mul)
1521 bool APO = false;
1522 /// Helper data for the reordering function.
1523 bool IsUsed = false;
1524 };
1525
1526 /// During operand reordering, we are trying to select the operand at lane
1527 /// that matches best with the operand at the neighboring lane. Our
1528 /// selection is based on the type of value we are looking for. For example,
1529 /// if the neighboring lane has a load, we need to look for a load that is
1530 /// accessing a consecutive address. These strategies are summarized in the
1531 /// 'ReorderingMode' enumerator.
1532 enum class ReorderingMode {
1533 Load, ///< Matching loads to consecutive memory addresses
1534 Opcode, ///< Matching instructions based on opcode (same or alternate)
1535 Constant, ///< Matching constants
1536 Splat, ///< Matching the same instruction multiple times (broadcast)
1537 Failed, ///< We failed to create a vectorizable group
1538 };
1539
1541
1542 /// A vector of operand vectors.
1544
1545 const TargetLibraryInfo &TLI;
1546 const DataLayout &DL;
1547 ScalarEvolution &SE;
1548 const BoUpSLP &R;
1549
1550 /// \returns the operand data at \p OpIdx and \p Lane.
1551 OperandData &getData(unsigned OpIdx, unsigned Lane) {
1552 return OpsVec[OpIdx][Lane];
1553 }
1554
1555 /// \returns the operand data at \p OpIdx and \p Lane. Const version.
1556 const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
1557 return OpsVec[OpIdx][Lane];
1558 }
1559
1560 /// Clears the used flag for all entries.
1561 void clearUsed() {
1562 for (unsigned OpIdx = 0, NumOperands = getNumOperands();
1563 OpIdx != NumOperands; ++OpIdx)
1564 for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
1565 ++Lane)
1566 OpsVec[OpIdx][Lane].IsUsed = false;
1567 }
1568
1569 /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
1570 void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
1571 std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
1572 }
1573
1574 /// \param Lane lane of the operands under analysis.
1575 /// \param OpIdx operand index in \p Lane lane we're looking the best
1576 /// candidate for.
1577 /// \param Idx operand index of the current candidate value.
1578 /// \returns The additional score due to possible broadcasting of the
1579 /// elements in the lane. It is more profitable to have power-of-2 unique
1580 /// elements in the lane, it will be vectorized with higher probability
1581 /// after removing duplicates. Currently the SLP vectorizer supports only
1582 /// vectorization of the power-of-2 number of unique scalars.
1583 int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1584 Value *IdxLaneV = getData(Idx, Lane).V;
1585 if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
1586 return 0;
1588 for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
1589 if (Ln == Lane)
1590 continue;
1591 Value *OpIdxLnV = getData(OpIdx, Ln).V;
1592 if (!isa<Instruction>(OpIdxLnV))
1593 return 0;
1594 Uniques.insert(OpIdxLnV);
1595 }
1596 int UniquesCount = Uniques.size();
1597 int UniquesCntWithIdxLaneV =
1598 Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
1599 Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1600 int UniquesCntWithOpIdxLaneV =
1601 Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
1602 if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
1603 return 0;
1604 return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
1605 UniquesCntWithOpIdxLaneV) -
1606 (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
1607 }
1608
1609 /// \param Lane lane of the operands under analysis.
1610 /// \param OpIdx operand index in \p Lane lane we're looking the best
1611 /// candidate for.
1612 /// \param Idx operand index of the current candidate value.
1613 /// \returns The additional score for the scalar which users are all
1614 /// vectorized.
1615 int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
1616 Value *IdxLaneV = getData(Idx, Lane).V;
1617 Value *OpIdxLaneV = getData(OpIdx, Lane).V;
1618 // Do not care about number of uses for vector-like instructions
1619 // (extractelement/extractvalue with constant indices), they are extracts
1620 // themselves and already externally used. Vectorization of such
1621 // instructions does not add extra extractelement instruction, just may
1622 // remove it.
1623 if (isVectorLikeInstWithConstOps(IdxLaneV) &&
1624 isVectorLikeInstWithConstOps(OpIdxLaneV))
1626 auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
1627 if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
1628 return 0;
1629 return R.areAllUsersVectorized(IdxLaneI, std::nullopt)
1631 : 0;
1632 }
1633
1634 /// Score scaling factor for fully compatible instructions but with
1635 /// different number of external uses. Allows better selection of the
1636 /// instructions with less external uses.
1637 static const int ScoreScaleFactor = 10;
1638
1639 /// \Returns the look-ahead score, which tells us how much the sub-trees
1640 /// rooted at \p LHS and \p RHS match, the more they match the higher the
1641 /// score. This helps break ties in an informed way when we cannot decide on
1642 /// the order of the operands by just considering the immediate
1643 /// predecessors.
1644 int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
1645 int Lane, unsigned OpIdx, unsigned Idx,
1646 bool &IsUsed) {
1647 LookAheadHeuristics LookAhead(TLI, DL, SE, R, getNumLanes(),
1649 // Keep track of the instruction stack as we recurse into the operands
1650 // during the look-ahead score exploration.
1651 int Score =
1652 LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
1653 /*CurrLevel=*/1, MainAltOps);
1654 if (Score) {
1655 int SplatScore = getSplatScore(Lane, OpIdx, Idx);
1656 if (Score <= -SplatScore) {
1657 // Set the minimum score for splat-like sequence to avoid setting
1658 // failed state.
1659 Score = 1;
1660 } else {
1661 Score += SplatScore;
1662 // Scale score to see the difference between different operands
1663 // and similar operands but all vectorized/not all vectorized
1664 // uses. It does not affect actual selection of the best
1665 // compatible operand in general, just allows to select the
1666 // operand with all vectorized uses.
1667 Score *= ScoreScaleFactor;
1668 Score += getExternalUseScore(Lane, OpIdx, Idx);
1669 IsUsed = true;
1670 }
1671 }
1672 return Score;
1673 }
1674
1675 /// Best defined scores per lanes between the passes. Used to choose the
1676 /// best operand (with the highest score) between the passes.
1677 /// The key - {Operand Index, Lane}.
1678 /// The value - the best score between the passes for the lane and the
1679 /// operand.
1681 BestScoresPerLanes;
1682
1683 // Search all operands in Ops[*][Lane] for the one that matches best
1684 // Ops[OpIdx][LastLane] and return its opreand index.
1685 // If no good match can be found, return std::nullopt.
1686 std::optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
1687 ArrayRef<ReorderingMode> ReorderingModes,
1688 ArrayRef<Value *> MainAltOps) {
1689 unsigned NumOperands = getNumOperands();
1690
1691 // The operand of the previous lane at OpIdx.
1692 Value *OpLastLane = getData(OpIdx, LastLane).V;
1693
1694 // Our strategy mode for OpIdx.
1695 ReorderingMode RMode = ReorderingModes[OpIdx];
1696 if (RMode == ReorderingMode::Failed)
1697 return std::nullopt;
1698
1699 // The linearized opcode of the operand at OpIdx, Lane.
1700 bool OpIdxAPO = getData(OpIdx, Lane).APO;
1701
1702 // The best operand index and its score.
1703 // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
1704 // are using the score to differentiate between the two.
1705 struct BestOpData {
1706 std::optional<unsigned> Idx;
1707 unsigned Score = 0;
1708 } BestOp;
1709 BestOp.Score =
1710 BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
1711 .first->second;
1712
1713 // Track if the operand must be marked as used. If the operand is set to
1714 // Score 1 explicitly (because of non power-of-2 unique scalars, we may
1715 // want to reestimate the operands again on the following iterations).
1716 bool IsUsed =
1717 RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
1718 // Iterate through all unused operands and look for the best.
1719 for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
1720 // Get the operand at Idx and Lane.
1721 OperandData &OpData = getData(Idx, Lane);
1722 Value *Op = OpData.V;
1723 bool OpAPO = OpData.APO;
1724
1725 // Skip already selected operands.
1726 if (OpData.IsUsed)
1727 continue;
1728
1729 // Skip if we are trying to move the operand to a position with a
1730 // different opcode in the linearized tree form. This would break the
1731 // semantics.
1732 if (OpAPO != OpIdxAPO)
1733 continue;
1734
1735 // Look for an operand that matches the current mode.
1736 switch (RMode) {
1737 case ReorderingMode::Load:
1738 case ReorderingMode::Constant:
1739 case ReorderingMode::Opcode: {
1740 bool LeftToRight = Lane > LastLane;
1741 Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
1742 Value *OpRight = (LeftToRight) ? Op : OpLastLane;
1743 int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
1744 OpIdx, Idx, IsUsed);
1745 if (Score > static_cast<int>(BestOp.Score)) {
1746 BestOp.Idx = Idx;
1747 BestOp.Score = Score;
1748 BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
1749 }
1750 break;
1751 }
1752 case ReorderingMode::Splat:
1753 if (Op == OpLastLane)
1754 BestOp.Idx = Idx;
1755 break;
1756 case ReorderingMode::Failed:
1757 llvm_unreachable("Not expected Failed reordering mode.");
1758 }
1759 }
1760
1761 if (BestOp.Idx) {
1762 getData(*BestOp.Idx, Lane).IsUsed = IsUsed;
1763 return BestOp.Idx;
1764 }
1765 // If we could not find a good match return std::nullopt.
1766 return std::nullopt;
1767 }
1768
1769 /// Helper for reorderOperandVecs.
1770 /// \returns the lane that we should start reordering from. This is the one
1771 /// which has the least number of operands that can freely move about or
1772 /// less profitable because it already has the most optimal set of operands.
1773 unsigned getBestLaneToStartReordering() const {
1774 unsigned Min = UINT_MAX;
1775 unsigned SameOpNumber = 0;
1776 // std::pair<unsigned, unsigned> is used to implement a simple voting
1777 // algorithm and choose the lane with the least number of operands that
1778 // can freely move about or less profitable because it already has the
1779 // most optimal set of operands. The first unsigned is a counter for
1780 // voting, the second unsigned is the counter of lanes with instructions
1781 // with same/alternate opcodes and same parent basic block.
1783 // Try to be closer to the original results, if we have multiple lanes
1784 // with same cost. If 2 lanes have the same cost, use the one with the
1785 // lowest index.
1786 for (int I = getNumLanes(); I > 0; --I) {
1787 unsigned Lane = I - 1;
1788 OperandsOrderData NumFreeOpsHash =
1789 getMaxNumOperandsThatCanBeReordered(Lane);
1790 // Compare the number of operands that can move and choose the one with
1791 // the least number.
1792 if (NumFreeOpsHash.NumOfAPOs < Min) {
1793 Min = NumFreeOpsHash.NumOfAPOs;
1794 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1795 HashMap.clear();
1796 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1797 } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1798 NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
1799 // Select the most optimal lane in terms of number of operands that
1800 // should be moved around.
1801 SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
1802 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1803 } else if (NumFreeOpsHash.NumOfAPOs == Min &&
1804 NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
1805 auto It = HashMap.find(NumFreeOpsHash.Hash);
1806 if (It == HashMap.end())
1807 HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
1808 else
1809 ++It->second.first;
1810 }
1811 }
1812 // Select the lane with the minimum counter.
1813 unsigned BestLane = 0;
1814 unsigned CntMin = UINT_MAX;
1815 for (const auto &Data : reverse(HashMap)) {
1816 if (Data.second.first < CntMin) {
1817 CntMin = Data.second.first;
1818 BestLane = Data.second.second;
1819 }
1820 }
1821 return BestLane;
1822 }
1823
1824 /// Data structure that helps to reorder operands.
1825 struct OperandsOrderData {
1826 /// The best number of operands with the same APOs, which can be
1827 /// reordered.
1828 unsigned NumOfAPOs = UINT_MAX;
1829 /// Number of operands with the same/alternate instruction opcode and
1830 /// parent.
1831 unsigned NumOpsWithSameOpcodeParent = 0;
1832 /// Hash for the actual operands ordering.
1833 /// Used to count operands, actually their position id and opcode
1834 /// value. It is used in the voting mechanism to find the lane with the
1835 /// least number of operands that can freely move about or less profitable
1836 /// because it already has the most optimal set of operands. Can be
1837 /// replaced with SmallVector<unsigned> instead but hash code is faster
1838 /// and requires less memory.
1839 unsigned Hash = 0;
1840 };
1841 /// \returns the maximum number of operands that are allowed to be reordered
1842 /// for \p Lane and the number of compatible instructions(with the same
1843 /// parent/opcode). This is used as a heuristic for selecting the first lane
1844 /// to start operand reordering.
1845 OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
1846 unsigned CntTrue = 0;
1847 unsigned NumOperands = getNumOperands();
1848 // Operands with the same APO can be reordered. We therefore need to count
1849 // how many of them we have for each APO, like this: Cnt[APO] = x.
1850 // Since we only have two APOs, namely true and false, we can avoid using
1851 // a map. Instead we can simply count the number of operands that
1852 // correspond to one of them (in this case the 'true' APO), and calculate
1853 // the other by subtracting it from the total number of operands.
1854 // Operands with the same instruction opcode and parent are more
1855 // profitable since we don't need to move them in many cases, with a high
1856 // probability such lane already can be vectorized effectively.
1857 bool AllUndefs = true;
1858 unsigned NumOpsWithSameOpcodeParent = 0;
1859 Instruction *OpcodeI = nullptr;
1860 BasicBlock *Parent = nullptr;
1861 unsigned Hash = 0;
1862 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1863 const OperandData &OpData = getData(OpIdx, Lane);
1864 if (OpData.APO)
1865 ++CntTrue;
1866 // Use Boyer-Moore majority voting for finding the majority opcode and
1867 // the number of times it occurs.
1868 if (auto *I = dyn_cast<Instruction>(OpData.V)) {
1869 if (!OpcodeI || !getSameOpcode({OpcodeI, I}, TLI).getOpcode() ||
1870 I->getParent() != Parent) {
1871 if (NumOpsWithSameOpcodeParent == 0) {
1872 NumOpsWithSameOpcodeParent = 1;
1873 OpcodeI = I;
1874 Parent = I->getParent();
1875 } else {
1876 --NumOpsWithSameOpcodeParent;
1877 }
1878 } else {
1879 ++NumOpsWithSameOpcodeParent;
1880 }
1881 }
1882 Hash = hash_combine(
1883 Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
1884 AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
1885 }
1886 if (AllUndefs)
1887 return {};
1888 OperandsOrderData Data;
1889 Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
1890 Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
1891 Data.Hash = Hash;
1892 return Data;
1893 }
1894
1895 /// Go through the instructions in VL and append their operands.
1896 void appendOperandsOfVL(ArrayRef<Value *> VL) {
1897 assert(!VL.empty() && "Bad VL");
1898 assert((empty() || VL.size() == getNumLanes()) &&
1899 "Expected same number of lanes");
1900 assert(isa<Instruction>(VL[0]) && "Expected instruction");
1901 unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
1902 OpsVec.resize(NumOperands);
1903 unsigned NumLanes = VL.size();
1904 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
1905 OpsVec[OpIdx].resize(NumLanes);
1906 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
1907 assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
1908 // Our tree has just 3 nodes: the root and two operands.
1909 // It is therefore trivial to get the APO. We only need to check the
1910 // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
1911 // RHS operand. The LHS operand of both add and sub is never attached
1912 // to an inversese operation in the linearized form, therefore its APO
1913 // is false. The RHS is true only if VL[Lane] is an inverse operation.
1914
1915 // Since operand reordering is performed on groups of commutative
1916 // operations or alternating sequences (e.g., +, -), we can safely
1917 // tell the inverse operations by checking commutativity.
1918 bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
1919 bool APO = (OpIdx == 0) ? false : IsInverseOperation;
1920 OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
1921 APO, false};
1922 }
1923 }
1924 }
1925
1926 /// \returns the number of operands.
1927 unsigned getNumOperands() const { return OpsVec.size(); }
1928
1929 /// \returns the number of lanes.
1930 unsigned getNumLanes() const { return OpsVec[0].size(); }
1931
1932 /// \returns the operand value at \p OpIdx and \p Lane.
1933 Value *getValue(unsigned OpIdx, unsigned Lane) const {
1934 return getData(OpIdx, Lane).V;
1935 }
1936
1937 /// \returns true if the data structure is empty.
1938 bool empty() const { return OpsVec.empty(); }
1939
1940 /// Clears the data.
1941 void clear() { OpsVec.clear(); }
1942
1943 /// \Returns true if there are enough operands identical to \p Op to fill
1944 /// the whole vector.
1945 /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
1946 bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
1947 bool OpAPO = getData(OpIdx, Lane).APO;
1948 for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
1949 if (Ln == Lane)
1950 continue;
1951 // This is set to true if we found a candidate for broadcast at Lane.
1952 bool FoundCandidate = false;
1953 for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
1954 OperandData &Data = getData(OpI, Ln);
1955 if (Data.APO != OpAPO || Data.IsUsed)
1956 continue;
1957 if (Data.V == Op) {
1958 FoundCandidate = true;
1959 Data.IsUsed = true;
1960 break;
1961 }
1962 }
1963 if (!FoundCandidate)
1964 return false;
1965 }
1966 return true;
1967 }
1968
1969 public:
1970 /// Initialize with all the operands of the instruction vector \p RootVL.
1972 const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R)
1973 : TLI(TLI), DL(DL), SE(SE), R(R) {
1974 // Append all the operands of RootVL.
1975 appendOperandsOfVL(RootVL);
1976 }
1977
1978 /// \Returns a value vector with the operands across all lanes for the
1979 /// opearnd at \p OpIdx.
1980 ValueList getVL(unsigned OpIdx) const {
1981 ValueList OpVL(OpsVec[OpIdx].size());
1982 assert(OpsVec[OpIdx].size() == getNumLanes() &&
1983 "Expected same num of lanes across all operands");
1984 for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
1985 OpVL[Lane] = OpsVec[OpIdx][Lane].V;
1986 return OpVL;
1987 }
1988
1989 // Performs operand reordering for 2 or more operands.
1990 // The original operands are in OrigOps[OpIdx][Lane].
1991 // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
1992 void reorder() {
1993 unsigned NumOperands = getNumOperands();
1994 unsigned NumLanes = getNumLanes();
1995 // Each operand has its own mode. We are using this mode to help us select
1996 // the instructions for each lane, so that they match best with the ones
1997 // we have selected so far.
1998 SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
1999
2000 // This is a greedy single-pass algorithm. We are going over each lane
2001 // once and deciding on the best order right away with no back-tracking.
2002 // However, in order to increase its effectiveness, we start with the lane
2003 // that has operands that can move the least. For example, given the
2004 // following lanes:
2005 // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd
2006 // Lane 1 : A[1] = C[1] - B[1] // Visited 1st
2007 // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd
2008 // Lane 3 : A[3] = C[3] - B[3] // Visited 4th
2009 // we will start at Lane 1, since the operands of the subtraction cannot
2010 // be reordered. Then we will visit the rest of the lanes in a circular
2011 // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
2012
2013 // Find the first lane that we will start our search from.
2014 unsigned FirstLane = getBestLaneToStartReordering();
2015
2016 // Initialize the modes.
2017 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
2018 Value *OpLane0 = getValue(OpIdx, FirstLane);
2019 // Keep track if we have instructions with all the same opcode on one
2020 // side.
2021 if (isa<LoadInst>(OpLane0))
2022 ReorderingModes[OpIdx] = ReorderingMode::Load;
2023 else if (isa<Instruction>(OpLane0)) {
2024 // Check if OpLane0 should be broadcast.
2025 if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
2026 ReorderingModes[OpIdx] = ReorderingMode::Splat;
2027 else
2028 ReorderingModes[OpIdx] = ReorderingMode::Opcode;
2029 }
2030 else if (isa<Constant>(OpLane0))
2031 ReorderingModes[OpIdx] = ReorderingMode::Constant;
2032 else if (isa<Argument>(OpLane0))
2033 // Our best hope is a Splat. It may save some cost in some cases.
2034 ReorderingModes[OpIdx] = ReorderingMode::Splat;
2035 else
2036 // NOTE: This should be unreachable.
2037 ReorderingModes[OpIdx] = ReorderingMode::Failed;
2038 }
2039
2040 // Check that we don't have same operands. No need to reorder if operands
2041 // are just perfect diamond or shuffled diamond match. Do not do it only
2042 // for possible broadcasts or non-power of 2 number of scalars (just for
2043 // now).
2044 auto &&SkipReordering = [this]() {
2045 SmallPtrSet<Value *, 4> UniqueValues;
2046 ArrayRef<OperandData> Op0 = OpsVec.front();
2047 for (const OperandData &Data : Op0)
2048 UniqueValues.insert(Data.V);
2049 for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
2050 if (any_of(Op, [&UniqueValues](const OperandData &Data) {
2051 return !UniqueValues.contains(Data.V);
2052 }))
2053 return false;
2054 }
2055 // TODO: Check if we can remove a check for non-power-2 number of
2056 // scalars after full support of non-power-2 vectorization.
2057 return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
2058 };
2059
2060 // If the initial strategy fails for any of the operand indexes, then we
2061 // perform reordering again in a second pass. This helps avoid assigning
2062 // high priority to the failed strategy, and should improve reordering for
2063 // the non-failed operand indexes.
2064 for (int Pass = 0; Pass != 2; ++Pass) {
2065 // Check if no need to reorder operands since they're are perfect or
2066 // shuffled diamond match.
2067 // Need to to do it to avoid extra external use cost counting for
2068 // shuffled matches, which may cause regressions.
2069 if (SkipReordering())
2070 break;
2071 // Skip the second pass if the first pass did not fail.
2072 bool StrategyFailed = false;
2073 // Mark all operand data as free to use.
2074 clearUsed();
2075 // We keep the original operand order for the FirstLane, so reorder the
2076 // rest of the lanes. We are visiting the nodes in a circular fashion,
2077 // using FirstLane as the center point and increasing the radius
2078 // distance.
2079 SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
2080 for (unsigned I = 0; I < NumOperands; ++I)
2081 MainAltOps[I].push_back(getData(I, FirstLane).V);
2082
2083 for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
2084 // Visit the lane on the right and then the lane on the left.
2085 for (int Direction : {+1, -1}) {
2086 int Lane = FirstLane + Direction * Distance;
2087 if (Lane < 0 || Lane >= (int)NumLanes)
2088 continue;
2089 int LastLane = Lane - Direction;
2090 assert(LastLane >= 0 && LastLane < (int)NumLanes &&
2091 "Out of bounds");
2092 // Look for a good match for each operand.
2093 for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
2094 // Search for the operand that matches SortedOps[OpIdx][Lane-1].
2095 std::optional<unsigned> BestIdx = getBestOperand(
2096 OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
2097 // By not selecting a value, we allow the operands that follow to
2098 // select a better matching value. We will get a non-null value in
2099 // the next run of getBestOperand().
2100 if (BestIdx) {
2101 // Swap the current operand with the one returned by
2102 // getBestOperand().
2103 swap(OpIdx, *BestIdx, Lane);
2104 } else {
2105 // We failed to find a best operand, set mode to 'Failed'.
2106 ReorderingModes[OpIdx] = ReorderingMode::Failed;
2107 // Enable the second pass.
2108 StrategyFailed = true;
2109 }
2110 // Try to get the alternate opcode and follow it during analysis.
2111 if (MainAltOps[OpIdx].size() != 2) {
2112 OperandData &AltOp = getData(OpIdx, Lane);
2113 InstructionsState OpS =
2114 getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V}, TLI);
2115 if (OpS.getOpcode() && OpS.isAltShuffle())
2116 MainAltOps[OpIdx].push_back(AltOp.V);
2117 }
2118 }
2119 }
2120 }
2121 // Skip second pass if the strategy did not fail.
2122 if (!StrategyFailed)
2123 break;
2124 }
2125 }
2126
2127#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
2128 LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
2129 switch (RMode) {
2130 case ReorderingMode::Load:
2131 return "Load";
2132 case ReorderingMode::Opcode:
2133 return "Opcode";
2134 case ReorderingMode::Constant:
2135 return "Constant";
2136 case ReorderingMode::Splat:
2137 return "Splat";
2138 case ReorderingMode::Failed:
2139 return "Failed";
2140 }
2141 llvm_unreachable("Unimplemented Reordering Type");
2142 }
2143
2144 LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
2145 raw_ostream &OS) {
2146 return OS << getModeStr(RMode);
2147 }
2148
2149 /// Debug print.
2150 LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
2151 printMode(RMode, dbgs());
2152 }
2153
2154 friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
2155 return printMode(RMode, OS);
2156 }
2157
2159 const unsigned Indent = 2;
2160 unsigned Cnt = 0;
2161 for (const OperandDataVec &OpDataVec : OpsVec) {
2162 OS << "Operand " << Cnt++ << "\n";
2163 for (const OperandData &OpData : OpDataVec) {
2164 OS.indent(Indent) << "{";
2165 if (Value *V = OpData.V)
2166 OS << *V;
2167 else
2168 OS << "null";
2169 OS << ", APO:" << OpData.APO << "}\n";
2170 }
2171 OS << "\n";
2172 }
2173 return OS;
2174 }
2175
2176 /// Debug print.
2177 LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
2178#endif
2179 };
2180
2181 /// Evaluate each pair in \p Candidates and return index into \p Candidates
2182 /// for a pair which have highest score deemed to have best chance to form
2183 /// root of profitable tree to vectorize. Return std::nullopt if no candidate
2184 /// scored above the LookAheadHeuristics::ScoreFail. \param Limit Lower limit
2185 /// of the cost, considered to be good enough score.
2186 std::optional<int>
2187 findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates,
2188 int Limit = LookAheadHeuristics::ScoreFail) {
2189 LookAheadHeuristics LookAhead(*TLI, *DL, *SE, *this, /*NumLanes=*/2,
2191 int BestScore = Limit;
2192 std::optional<int> Index;
2193 for (int I : seq<int>(0, Candidates.size())) {
2194 int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
2195 Candidates[I].second,
2196 /*U1=*/nullptr, /*U2=*/nullptr,
2197 /*Level=*/1, std::nullopt);
2198 if (Score > BestScore) {
2199 BestScore = Score;
2200 Index = I;
2201 }
2202 }
2203 return Index;
2204 }
2205
2206 /// Checks if the instruction is marked for deletion.
2207 bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
2208
2209 /// Removes an instruction from its block and eventually deletes it.
2210 /// It's like Instruction::eraseFromParent() except that the actual deletion
2211 /// is delayed until BoUpSLP is destructed.
2213 DeletedInstructions.insert(I);
2214 }
2215
2216 /// Checks if the instruction was already analyzed for being possible
2217 /// reduction root.
2219 return AnalyzedReductionsRoots.count(I);
2220 }
2221 /// Register given instruction as already analyzed for being possible
2222 /// reduction root.
2224 AnalyzedReductionsRoots.insert(I);
2225 }
2226 /// Checks if the provided list of reduced values was checked already for
2227 /// vectorization.
2229 return AnalyzedReductionVals.contains(hash_value(VL));
2230 }
2231 /// Adds the list of reduced values to list of already checked values for the
2232 /// vectorization.
2234 AnalyzedReductionVals.insert(hash_value(VL));
2235 }
2236 /// Clear the list of the analyzed reduction root instructions.
2238 AnalyzedReductionsRoots.clear();
2239 AnalyzedReductionVals.clear();
2240 }
2241 /// Checks if the given value is gathered in one of the nodes.
2242 bool isAnyGathered(const SmallDenseSet<Value *> &Vals) const {
2243 return any_of(MustGather, [&](Value *V) { return Vals.contains(V); });
2244 }
2245
2246 /// Check if the value is vectorized in the tree.
2247 bool isVectorized(Value *V) const { return getTreeEntry(V); }
2248
2249 ~BoUpSLP();
2250
2251private:
2252 /// Check if the operands on the edges \p Edges of the \p UserTE allows
2253 /// reordering (i.e. the operands can be reordered because they have only one
2254 /// user and reordarable).
2255 /// \param ReorderableGathers List of all gather nodes that require reordering
2256 /// (e.g., gather of extractlements or partially vectorizable loads).
2257 /// \param GatherOps List of gather operand nodes for \p UserTE that require
2258 /// reordering, subset of \p NonVectorized.
2259 bool
2260 canReorderOperands(TreeEntry *UserTE,
2261 SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
2262 ArrayRef<TreeEntry *> ReorderableGathers,
2263 SmallVectorImpl<TreeEntry *> &GatherOps);
2264
2265 /// Checks if the given \p TE is a gather node with clustered reused scalars
2266 /// and reorders it per given \p Mask.
2267 void reorderNodeWithReuses(TreeEntry &TE, ArrayRef<int> Mask) const;
2268
2269 /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2270 /// if any. If it is not vectorized (gather node), returns nullptr.
2271 TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
2272 ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
2273 TreeEntry *TE = nullptr;
2274 const auto *It = find_if(VL, [this, &TE](Value *V) {
2275 TE = getTreeEntry(V);
2276 return TE;
2277 });
2278 if (It != VL.end() && TE->isSame(VL))
2279 return TE;
2280 return nullptr;
2281 }
2282
2283 /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
2284 /// if any. If it is not vectorized (gather node), returns nullptr.
2285 const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
2286 unsigned OpIdx) const {
2287 return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
2288 const_cast<TreeEntry *>(UserTE), OpIdx);
2289 }
2290
2291 /// Checks if all users of \p I are the part of the vectorization tree.
2292 bool areAllUsersVectorized(Instruction *I,
2293 ArrayRef<Value *> VectorizedVals) const;
2294
2295 /// Return information about the vector formed for the specified index
2296 /// of a vector of (the same) instruction.
2298 unsigned OpIdx);
2299
2300 /// \returns the cost of the vectorizable entry.
2301 InstructionCost getEntryCost(const TreeEntry *E,
2302 ArrayRef<Value *> VectorizedVals);
2303
2304 /// This is the recursive part of buildTree.
2305 void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
2306 const EdgeInfo &EI);
2307
2308 /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
2309 /// be vectorized to use the original vector (or aggregate "bitcast" to a
2310 /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
2311 /// returns false, setting \p CurrentOrder to either an empty vector or a
2312 /// non-identity permutation that allows to reuse extract instructions.
2313 bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
2314 SmallVectorImpl<unsigned> &CurrentOrder) const;
2315
2316 /// Vectorize a single entry in the tree.
2317 Value *vectorizeTree(TreeEntry *E);
2318
2319 /// Vectorize a single entry in the tree, the \p Idx-th operand of the entry
2320 /// \p E.
2321 Value *vectorizeOperand(TreeEntry *E, unsigned NodeIdx);
2322
2323 /// Create a new vector from a list of scalar values. Produces a sequence
2324 /// which exploits values reused across lanes, and arranges the inserts
2325 /// for ease of later optimization.
2326 Value *createBuildVector(const TreeEntry *E);
2327
2328 /// \returns the scalarization cost for this type. Scalarization in this
2329 /// context means the creation of vectors from a group of scalars. If \p
2330 /// NeedToShuffle is true, need to add a cost of reshuffling some of the
2331 /// vector elements.
2332 InstructionCost getGatherCost(FixedVectorType *Ty,
2333 const APInt &ShuffledIndices,
2334 bool NeedToShuffle) const;
2335
2336 /// Returns the instruction in the bundle, which can be used as a base point
2337 /// for scheduling. Usually it is the last instruction in the bundle, except
2338 /// for the case when all operands are external (in this case, it is the first
2339 /// instruction in the list).
2340 Instruction &getLastInstructionInBundle(const TreeEntry *E);
2341
2342 /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
2343 /// tree entries.
2344 /// \param TE Tree entry checked for permutation.
2345 /// \param VL List of scalars (a subset of the TE scalar), checked for
2346 /// permutations.
2347 /// \returns ShuffleKind, if gathered values can be represented as shuffles of
2348 /// previous tree entries. \p Mask is filled with the shuffle mask.
2349 std::optional<TargetTransformInfo::ShuffleKind>
2350 isGatherShuffledEntry(const TreeEntry *TE, ArrayRef<Value *> VL,
2353
2354 /// \returns the scalarization cost for this list of values. Assuming that
2355 /// this subtree gets vectorized, we may need to extract the values from the
2356 /// roots. This method calculates the cost of extracting the values.
2357 InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
2358
2359 /// Set the Builder insert point to one after the last instruction in
2360 /// the bundle
2361 void setInsertPointAfterBundle(const TreeEntry *E);
2362
2363 /// \returns a vector from a collection of scalars in \p VL.
2364 Value *gather(ArrayRef<Value *> VL);
2365
2366 /// \returns whether the VectorizableTree is fully vectorizable and will
2367 /// be beneficial even the tree height is tiny.
2368 bool isFullyVectorizableTinyTree(bool ForReduction) const;
2369
2370 /// Reorder commutative or alt operands to get better probability of
2371 /// generating vectorized code.
2372 static void reorderInputsAccordingToOpcode(
2375 const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R);
2376
2377 /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the
2378 /// users of \p TE and collects the stores. It returns the map from the store
2379 /// pointers to the collected stores.
2381 collectUserStores(const BoUpSLP::TreeEntry *TE) const;
2382
2383 /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the
2384 /// stores in \p StoresVec can form a vector instruction. If so it returns true
2385 /// and populates \p ReorderIndices with the shuffle indices of the the stores
2386 /// when compared to the sorted vector.
2387 bool canFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
2388 OrdersType &ReorderIndices) const;
2389
2390 /// Iterates through the users of \p TE, looking for scalar stores that can be
2391 /// potentially vectorized in a future SLP-tree. If found, it keeps track of
2392 /// their order and builds an order index vector for each store bundle. It
2393 /// returns all these order vectors found.
2394 /// We run this after the tree has formed, otherwise we may come across user
2395 /// instructions that are not yet in the tree.
2397 findExternalStoreUsersReorderIndices(TreeEntry *TE) const;
2398
2399 struct TreeEntry {
2400 using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
2401 TreeEntry(VecTreeTy &Container) : Container(Container) {}
2402
2403 /// \returns true if the scalars in VL are equal to this entry.
2404 bool isSame(ArrayRef<Value *> VL) const {
2405 auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
2406 if (Mask.size() != VL.size() && VL.size() == Scalars.size())
2407 return std::equal(VL.begin(), VL.end(), Scalars.begin());
2408 return VL.size() == Mask.size() &&
2409 std::equal(VL.begin(), VL.end(), Mask.begin(),
2410 [Scalars](Value *V, int Idx) {
2411 return (isa<UndefValue>(V) &&
2412 Idx == UndefMaskElem) ||
2413 (Idx != UndefMaskElem && V == Scalars[Idx]);
2414 });
2415 };
2416 if (!ReorderIndices.empty()) {
2417 // TODO: implement matching if the nodes are just reordered, still can
2418 // treat the vector as the same if the list of scalars matches VL
2419 // directly, without reordering.
2421 inversePermutation(ReorderIndices, Mask);
2422 if (VL.size() == Scalars.size())
2423 return IsSame(Scalars, Mask);
2424 if (VL.size() == ReuseShuffleIndices.size()) {
2425 ::addMask(Mask, ReuseShuffleIndices);
2426 return IsSame(Scalars, Mask);
2427 }
2428 return false;
2429 }
2430 return IsSame(Scalars, ReuseShuffleIndices);
2431 }
2432
2433 bool isOperandGatherNode(const EdgeInfo &UserEI) const {
2434 return State == TreeEntry::NeedToGather &&
2435 UserTreeIndices.front().EdgeIdx == UserEI.EdgeIdx &&
2436 UserTreeIndices.front().UserTE == UserEI.UserTE;
2437 }
2438
2439 /// \returns true if current entry has same operands as \p TE.
2440 bool hasEqualOperands(const TreeEntry &TE) const {
2441 if (TE.getNumOperands() != getNumOperands())
2442 return false;
2443 SmallBitVector Used(getNumOperands());
2444 for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
2445 unsigned PrevCount = Used.count();
2446 for (unsigned K = 0; K < E; ++K) {
2447 if (Used.test(K))
2448 continue;
2449 if (getOperand(K) == TE.getOperand(I)) {
2450 Used.set(K);
2451 break;
2452 }
2453 }
2454 // Check if we actually found the matching operand.
2455 if (PrevCount == Used.count())
2456 return false;
2457 }
2458 return true;
2459 }
2460
2461 /// \return Final vectorization factor for the node. Defined by the total
2462 /// number of vectorized scalars, including those, used several times in the
2463 /// entry and counted in the \a ReuseShuffleIndices, if any.
2464 unsigned getVectorFactor() const {
2465 if (!ReuseShuffleIndices.empty())
2466 return ReuseShuffleIndices.size();
2467 return Scalars.size();
2468 };
2469
2470 /// A vector of scalars.
2471 ValueList Scalars;
2472
2473 /// The Scalars are vectorized into this value. It is initialized to Null.
2474 Value *VectorizedValue = nullptr;
2475
2476 /// Do we need to gather this sequence or vectorize it
2477 /// (either with vector instruction or with scatter/gather
2478 /// intrinsics for store/load)?
2479 enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
2480 EntryState State;
2481
2482 /// Does this sequence require some shuffling?
2483 SmallVector<int, 4> ReuseShuffleIndices;
2484
2485 /// Does this entry require reordering?
2486 SmallVector<unsigned, 4> ReorderIndices;
2487
2488 /// Points back to the VectorizableTree.
2489 ///
2490 /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
2491 /// to be a pointer and needs to be able to initialize the child iterator.
2492 /// Thus we need a reference back to the container to translate the indices
2493 /// to entries.
2494 VecTreeTy &Container;
2495
2496 /// The TreeEntry index containing the user of this entry. We can actually
2497 /// have multiple users so the data structure is not truly a tree.
2498 SmallVector<EdgeInfo, 1> UserTreeIndices;
2499
2500 /// The index of this treeEntry in VectorizableTree.
2501 int Idx = -1;
2502
2503 private:
2504 /// The operands of each instruction in each lane Operands[op_index][lane].
2505 /// Note: This helps avoid the replication of the code that performs the
2506 /// reordering of operands during buildTree_rec() and vectorizeTree().
2508
2509 /// The main/alternate instruction.
2510 Instruction *MainOp = nullptr;
2511 Instruction *AltOp = nullptr;
2512
2513 public:
2514 /// Set this bundle's \p OpIdx'th operand to \p OpVL.
2515 void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
2516 if (Operands.size() < OpIdx + 1)
2517 Operands.resize(OpIdx + 1);
2518 assert(Operands[OpIdx].empty() && "Already resized?");
2519 assert(OpVL.size() <= Scalars.size() &&
2520 "Number of operands is greater than the number of scalars.");
2521 Operands[OpIdx].resize(OpVL.size());
2522 copy(OpVL, Operands[OpIdx].begin());
2523 }
2524
2525 /// Set the operands of this bundle in their original order.
2526 void setOperandsInOrder() {
2527 assert(Operands.empty() && "Already initialized?");
2528 auto *I0 = cast<Instruction>(Scalars[0]);
2529 Operands.resize(I0->getNumOperands());
2530 unsigned NumLanes = Scalars.size();
2531 for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
2532 OpIdx != NumOperands; ++OpIdx) {
2533 Operands[OpIdx].resize(NumLanes);
2534 for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
2535 auto *I = cast<Instruction>(Scalars[Lane]);
2536 assert(I->getNumOperands() == NumOperands &&
2537 "Expected same number of operands");
2538 Operands[OpIdx][Lane] = I->getOperand(OpIdx);
2539 }
2540 }
2541 }
2542
2543 /// Reorders operands of the node to the given mask \p Mask.
2544 void reorderOperands(ArrayRef<int> Mask) {
2545 for (ValueList &Operand : Operands)
2546 reorderScalars(Operand, Mask);
2547 }
2548
2549 /// \returns the \p OpIdx operand of this TreeEntry.
2550 ValueList &getOperand(unsigned OpIdx) {
2551 assert(OpIdx < Operands.size() && "Off bounds");
2552 return Operands[OpIdx];
2553 }
2554
2555 /// \returns the \p OpIdx operand of this TreeEntry.
2556 ArrayRef<Value *> getOperand(unsigned OpIdx) const {
2557 assert(OpIdx < Operands.size() && "Off bounds");
2558 return Operands[OpIdx];
2559 }
2560
2561 /// \returns the number of operands.
2562 unsigned getNumOperands() const { return Operands.size(); }
2563
2564 /// \return the single \p OpIdx operand.
2565 Value *getSingleOperand(unsigned OpIdx) const {
2566 assert(OpIdx < Operands.size() && "Off bounds");
2567 assert(!Operands[OpIdx].empty() && "No operand available");
2568 return Operands[OpIdx][0];
2569 }
2570
2571 /// Some of the instructions in the list have alternate opcodes.
2572 bool isAltShuffle() const { return MainOp != AltOp; }
2573
2574 bool isOpcodeOrAlt(Instruction *I) const {
2575 unsigned CheckedOpcode = I->getOpcode();
2576 return (getOpcode() == CheckedOpcode ||
2577 getAltOpcode() == CheckedOpcode);
2578 }
2579
2580 /// Chooses the correct key for scheduling data. If \p Op has the same (or
2581 /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
2582 /// \p OpValue.
2583 Value *isOneOf(Value *Op) const {
2584 auto *I = dyn_cast<Instruction>(Op);
2585 if (I && isOpcodeOrAlt(I))
2586 return Op;
2587 return MainOp;
2588 }
2589
2590 void setOperations(const InstructionsState &S) {
2591 MainOp = S.MainOp;
2592 AltOp = S.AltOp;
2593 }
2594
2595 Instruction *getMainOp() const {
2596 return MainOp;
2597 }
2598
2599 Instruction *getAltOp() const {
2600 return AltOp;
2601 }
2602
2603 /// The main/alternate opcodes for the list of instructions.
2604 unsigned getOpcode() const {
2605 return MainOp ? MainOp->getOpcode() : 0;
2606 }
2607
2608 unsigned getAltOpcode() const {
2609 return AltOp ? AltOp->getOpcode() : 0;
2610 }
2611
2612 /// When ReuseReorderShuffleIndices is empty it just returns position of \p
2613 /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
2614 int findLaneForValue(Value *V) const {
2615 unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
2616 assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2617 if (!ReorderIndices.empty())
2618 FoundLane = ReorderIndices[FoundLane];
2619 assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
2620 if (!ReuseShuffleIndices.empty()) {
2621 FoundLane = std::distance(ReuseShuffleIndices.begin(),
2622 find(ReuseShuffleIndices, FoundLane));
2623 }
2624 return FoundLane;
2625 }
2626
2627#ifndef NDEBUG
2628 /// Debug printer.
2629 LLVM_DUMP_METHOD void dump() const {
2630 dbgs() << Idx << ".\n";
2631 for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
2632 dbgs() << "Operand " << OpI << ":\n";
2633 for (const Value *V : Operands[OpI])
2634 dbgs().indent(2) << *V << "\n";
2635 }
2636 dbgs() << "Scalars: \n";
2637 for (Value *V : Scalars)
2638 dbgs().indent(2) << *V << "\n";
2639 dbgs() << "State: ";
2640 switch (State) {
2641 case Vectorize:
2642 dbgs() << "Vectorize\n";
2643 break;
2644 case ScatterVectorize:
2645 dbgs() << "ScatterVectorize\n";
2646 break;
2647 case NeedToGather:
2648 dbgs() << "NeedToGather\n";
2649 break;
2650 }
2651 dbgs() << "MainOp: ";
2652 if (MainOp)
2653 dbgs() << *MainOp << "\n";
2654 else
2655 dbgs() << "NULL\n";
2656 dbgs() << "AltOp: ";
2657 if (AltOp)
2658 dbgs() << *AltOp << "\n";
2659 else
2660 dbgs() << "NULL\n";
2661 dbgs() << "VectorizedValue: ";
2662 if (VectorizedValue)
2663 dbgs() << *VectorizedValue << "\n";
2664 else
2665 dbgs() << "NULL\n";
2666 dbgs() << "ReuseShuffleIndices: ";
2667 if (ReuseShuffleIndices.empty())
2668 dbgs() << "Empty";
2669 else
2670 for (int ReuseIdx : ReuseShuffleIndices)
2671 dbgs() << ReuseIdx << ", ";
2672 dbgs() << "\n";
2673 dbgs() << "ReorderIndices: ";
2674 for (unsigned ReorderIdx : ReorderIndices)
2675 dbgs() << ReorderIdx << ", ";
2676 dbgs() << "\n";
2677 dbgs() << "UserTreeIndices: ";
2678 for (const auto &EInfo : UserTreeIndices)
2679 dbgs() << EInfo << ", ";
2680 dbgs() << "\n";
2681 }
2682#endif
2683 };
2684
2685#ifndef NDEBUG
2686 void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
2687 InstructionCost VecCost,
2688 InstructionCost ScalarCost) const {
2689 dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
2690 dbgs() << "SLP: Costs:\n";
2691 dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n";
2692 dbgs() << "SLP: VectorCost = " << VecCost << "\n";
2693 dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n";
2694 dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " <<
2695 ReuseShuffleCost + VecCost - ScalarCost << "\n";
2696 }
2697#endif
2698
2699 /// Create a new VectorizableTree entry.
2700 TreeEntry *newTreeEntry(ArrayRef<Value *> VL, std::optional<ScheduleData *> Bundle,
2701 const InstructionsState &S,
2702 const EdgeInfo &UserTreeIdx,
2703 ArrayRef<int> ReuseShuffleIndices = std::nullopt,
2704 ArrayRef<unsigned> ReorderIndices = std::nullopt) {
2705 TreeEntry::EntryState EntryState =
2706 Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
2707 return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
2708 ReuseShuffleIndices, ReorderIndices);
2709 }
2710
2711 TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
2712 TreeEntry::EntryState EntryState,
2713 std::optional<ScheduleData *> Bundle,
2714 const InstructionsState &S,
2715 const EdgeInfo &UserTreeIdx,
2716 ArrayRef<int> ReuseShuffleIndices = std::nullopt,
2717 ArrayRef<unsigned> ReorderIndices = std::nullopt) {
2718 assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
2719 (Bundle && EntryState != TreeEntry::NeedToGather)) &&
2720 "Need to vectorize gather entry?");
2721 VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
2722 TreeEntry *Last = VectorizableTree.back().get();
2723 Last->Idx = VectorizableTree.size() - 1;
2724 Last->State = EntryState;
2725 Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
2726 ReuseShuffleIndices.end());
2727 if (ReorderIndices.empty()) {
2728 Last->Scalars.assign(VL.begin(), VL.end());
2729 Last->setOperations(S);
2730 } else {
2731 // Reorder scalars and build final mask.
2732 Last->Scalars.assign(VL.size(), nullptr);
2733 transform(ReorderIndices, Last->Scalars.begin(),
2734 [VL](unsigned Idx) -> Value * {
2735 if (Idx >= VL.size())
2736 return UndefValue::get(VL.front()->getType());
2737 return VL[Idx];
2738 });
2739 InstructionsState S = getSameOpcode(Last->Scalars, *TLI);
2740 Last->setOperations(S);
2741 Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
2742 }
2743 if (Last->State != TreeEntry::NeedToGather) {
2744 for (Value *V : VL) {
2745 assert(!getTreeEntry(V) && "Scalar already in tree!");
2746 ScalarToTreeEntry[V] = Last;
2747 }
2748 // Update the scheduler bundle to point to this TreeEntry.
2749 ScheduleData *BundleMember = *Bundle;
2750 assert((BundleMember || isa<PHINode>(S.MainOp) ||
2751 isVectorLikeInstWithConstOps(S.MainOp) ||
2752 doesNotNeedToSchedule(VL)) &&
2753 "Bundle and VL out of sync");
2754 if (BundleMember) {
2755 for (Value *V : VL) {
2757 continue;
2758 assert(BundleMember && "Unexpected end of bundle.");
2759 BundleMember->TE = Last;
2760 BundleMember = BundleMember->NextInBundle;
2761 }
2762 }
2763 assert(!BundleMember && "Bundle and VL out of sync");
2764 } else {
2765 MustGather.insert(VL.begin(), VL.end());
2766 }
2767
2768 if (UserTreeIdx.UserTE)
2769 Last->UserTreeIndices.push_back(UserTreeIdx);
2770
2771 return Last;
2772 }
2773
2774 /// -- Vectorization State --
2775 /// Holds all of the tree entries.
2776 TreeEntry::VecTreeTy VectorizableTree;
2777
2778#ifndef NDEBUG
2779 /// Debug printer.
2780 LLVM_DUMP_METHOD void dumpVectorizableTree() const {
2781 for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
2782 VectorizableTree[Id]->dump();
2783 dbgs() << "\n";
2784 }
2785 }
2786#endif
2787
2788 TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
2789
2790 const TreeEntry *getTreeEntry(Value *V) const {
2791 return ScalarToTreeEntry.lookup(V);
2792 }
2793
2794 /// Maps a specific scalar to its tree entry.
2795 SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
2796
2797 /// Maps a value to the proposed vectorizable size.
2798 SmallDenseMap<Value *, unsigned> InstrElementSize;
2799
2800 /// A list of scalars that we found that we need to keep as scalars.
2801 ValueSet MustGather;
2802
2803 /// A map between the vectorized entries and the last instructions in the
2804 /// bundles. The bundles are built in use order, not in the def order of the
2805 /// instructions. So, we cannot rely directly on the last instruction in the
2806 /// bundle being the last instruction in the program order during
2807 /// vectorization process since the basic blocks are affected, need to
2808 /// pre-gather them before.
2809 DenseMap<const TreeEntry *, Instruction *> EntryToLastInstruction;
2810
2811 /// This POD struct describes one external user in the vectorized tree.
2812 struct ExternalUser {
2813 ExternalUser(Value *S, llvm::User *U, int L)
2814 : Scalar(S), User(U), Lane(L) {}
2815
2816 // Which scalar in our function.
2817 Value *Scalar;
2818
2819 // Which user that uses the scalar.
2821
2822 // Which lane does the scalar belong to.
2823 int Lane;
2824 };
2825 using UserList = SmallVector<ExternalUser, 16>;
2826
2827 /// Checks if two instructions may access the same memory.
2828 ///
2829 /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
2830 /// is invariant in the calling loop.
2831 bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
2832 Instruction *Inst2) {
2833 // First check if the result is already in the cache.
2834 AliasCacheKey key = std::make_pair(Inst1, Inst2);
2835 std::optional<bool> &result = AliasCache[key];
2836 if (result) {
2837 return *result;
2838 }
2839 bool aliased = true;
2840 if (Loc1.Ptr && isSimple(Inst1))
2841 aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
2842 // Store the result in the cache.
2843 result = aliased;
2844 return aliased;
2845 }
2846
2847 using AliasCacheKey = std::pair<Instruction *, Instruction *>;
2848
2849 /// Cache for alias results.
2850 /// TODO: consider moving this to the AliasAnalysis itself.
2852
2853 // Cache for pointerMayBeCaptured calls inside AA. This is preserved
2854 // globally through SLP because we don't perform any action which
2855 // invalidates capture results.
2856 BatchAAResults BatchAA;
2857
2858 /// Temporary store for deleted instructions. Instructions will be deleted
2859 /// eventually when the BoUpSLP is destructed. The deferral is required to
2860 /// ensure that there are no incorrect collisions in the AliasCache, which
2861 /// can happen if a new instruction is allocated at the same address as a
2862 /// previously deleted instruction.
2863 DenseSet<Instruction *> DeletedInstructions;
2864
2865 /// Set of the instruction, being analyzed already for reductions.
2866 SmallPtrSet<Instruction *, 16> AnalyzedReductionsRoots;
2867
2868 /// Set of hashes for the list of reduction values already being analyzed.
2869 DenseSet<size_t> AnalyzedReductionVals;
2870
2871 /// A list of values that need to extracted out of the tree.
2872 /// This list holds pairs of (Internal Scalar : External User). External User
2873 /// can be nullptr, it means that this Internal Scalar will be used later,
2874 /// after vectorization.
2875 UserList ExternalUses;
2876
2877 /// Values used only by @llvm.assume calls.
2879
2880 /// Holds all of the instructions that we gathered, shuffle instructions and
2881 /// extractelements.
2882 SetVector<Instruction *> GatherShuffleExtractSeq;
2883
2884 /// A list of blocks that we are going to CSE.
2885 SetVector<BasicBlock *> CSEBlocks;
2886
2887 /// Contains all scheduling relevant data for an instruction.
2888 /// A ScheduleData either represents a single instruction or a member of an
2889 /// instruction bundle (= a group of instructions which is combined into a
2890 /// vector instruction).
2891 struct ScheduleData {
2892 // The initial value for the dependency counters. It means that the
2893 // dependencies are not calculated yet.
2894 enum { InvalidDeps = -1 };
2895
2896 ScheduleData() = default;
2897
2898 void init(int BlockSchedulingRegionID, Value *OpVal) {
2899 FirstInBundle = this;
2900 NextInBundle = nullptr;
2901 NextLoadStore = nullptr;
2902 IsScheduled = false;
2903 SchedulingRegionID = BlockSchedulingRegionID;
2904 clearDependencies();
2905 OpValue = OpVal;
2906 TE = nullptr;
2907 }
2908
2909 /// Verify basic self consistency properties
2910 void verify() {
2911 if (hasValidDependencies()) {
2912 assert(UnscheduledDeps <= Dependencies && "invariant");
2913 } else {
2914 assert(UnscheduledDeps == Dependencies && "invariant");
2915 }
2916
2917 if (IsScheduled) {
2918 assert(isSchedulingEntity() &&
2919 "unexpected scheduled state");
2920 for (const ScheduleData *BundleMember = this; BundleMember;
2921 BundleMember = BundleMember->NextInBundle) {
2922 assert(BundleMember->hasValidDependencies() &&
2923 BundleMember->UnscheduledDeps == 0 &&
2924 "unexpected scheduled state");
2925 assert((BundleMember == this || !BundleMember->IsScheduled) &&
2926 "only bundle is marked scheduled");
2927 }
2928 }
2929
2930 assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
2931 "all bundle members must be in same basic block");
2932 }
2933
2934 /// Returns true if the dependency information has been calculated.
2935 /// Note that depenendency validity can vary between instructions within
2936 /// a single bundle.
2937 bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
2938
2939 /// Returns true for single instructions and for bundle representatives
2940 /// (= the head of a bundle).
2941 bool isSchedulingEntity() const { return FirstInBundle == this; }
2942
2943 /// Returns true if it represents an instruction bundle and not only a
2944 /// single instruction.
2945 bool isPartOfBundle() const {
2946 return NextInBundle != nullptr || FirstInBundle != this || TE;
2947 }
2948
2949 /// Returns true if it is ready for scheduling, i.e. it has no more
2950 /// unscheduled depending instructions/bundles.
2951 bool isReady() const {
2952 assert(isSchedulingEntity() &&
2953 "can't consider non-scheduling entity for ready list");
2954 return unscheduledDepsInBundle() == 0 && !IsScheduled;
2955 }
2956
2957 /// Modifies the number of unscheduled dependencies for this instruction,
2958 /// and returns the number of remaining dependencies for the containing
2959 /// bundle.
2960 int incrementUnscheduledDeps(int Incr) {
2961 assert(hasValidDependencies() &&
2962 "increment of unscheduled deps would be meaningless");
2963 UnscheduledDeps += Incr;
2964 return FirstInBundle->unscheduledDepsInBundle();
2965 }
2966
2967 /// Sets the number of unscheduled dependencies to the number of
2968 /// dependencies.
2969 void resetUnscheduledDeps() {
2970 UnscheduledDeps = Dependencies;
2971 }
2972
2973 /// Clears all dependency information.
2974 void clearDependencies() {
2975 Dependencies = InvalidDeps;
2976 resetUnscheduledDeps();
2977 MemoryDependencies.clear();
2978 ControlDependencies.clear();
2979 }
2980
2981 int unscheduledDepsInBundle() const {
2982 assert(isSchedulingEntity() && "only meaningful on the bundle");
2983 int Sum = 0;
2984 for (const ScheduleData *BundleMember = this; BundleMember;
2985 BundleMember = BundleMember->NextInBundle) {
2986 if (BundleMember->UnscheduledDeps == InvalidDeps)
2987 return InvalidDeps;
2988 Sum += BundleMember->UnscheduledDeps;
2989 }
2990 return Sum;
2991 }
2992
2993 void dump(raw_ostream &os) const {
2994 if (!isSchedulingEntity()) {
2995 os << "/ " << *Inst;
2996 } else if (NextInBundle) {
2997 os << '[' << *Inst;
2998 ScheduleData *SD = NextInBundle;
2999 while (SD) {
3000 os << ';' << *SD->Inst;
3001 SD = SD->NextInBundle;
3002 }
3003 os << ']';
3004 } else {
3005 os << *Inst;
3006 }
3007 }
3008
3009 Instruction *Inst = nullptr;
3010
3011 /// Opcode of the current instruction in the schedule data.
3012 Value *OpValue = nullptr;
3013
3014 /// The TreeEntry that this instruction corresponds to.
3015 TreeEntry *TE = nullptr;
3016
3017 /// Points to the head in an instruction bundle (and always to this for
3018 /// single instructions).
3019 ScheduleData *FirstInBundle = nullptr;
3020
3021 /// Single linked list of all instructions in a bundle. Null if it is a
3022 /// single instruction.
3023 ScheduleData *NextInBundle = nullptr;
3024
3025 /// Single linked list of all memory instructions (e.g. load, store, call)
3026 /// in the block - until the end of the scheduling region.
3027 ScheduleData *NextLoadStore = nullptr;
3028
3029 /// The dependent memory instructions.
3030 /// This list is derived on demand in calculateDependencies().
3031 SmallVector<ScheduleData *, 4> MemoryDependencies;
3032
3033 /// List of instructions which this instruction could be control dependent
3034 /// on. Allowing such nodes to be scheduled below this one could introduce
3035 /// a runtime fault which didn't exist in the original program.
3036 /// ex: this is a load or udiv following a readonly call which inf loops
3037 SmallVector<ScheduleData *, 4> ControlDependencies;
3038
3039 /// This ScheduleData is in the current scheduling region if this matches
3040 /// the current SchedulingRegionID of BlockScheduling.
3041 int SchedulingRegionID = 0;
3042
3043 /// Used for getting a "good" final ordering of instructions.
3044 int SchedulingPriority = 0;
3045
3046 /// The number of dependencies. Constitutes of the number of users of the
3047 /// instruction plus the number of dependent memory instructions (if any).
3048 /// This value is calculated on demand.
3049 /// If InvalidDeps, the number of dependencies is not calculated yet.
3050 int Dependencies = InvalidDeps;
3051
3052 /// The number of dependencies minus the number of dependencies of scheduled
3053 /// instructions. As soon as this is zero, the instruction/bundle gets ready
3054 /// for scheduling.
3055 /// Note that this is negative as long as Dependencies is not calculated.
3056 int UnscheduledDeps = InvalidDeps;
3057
3058 /// True if this instruction is scheduled (or considered as scheduled in the
3059 /// dry-run).
3060 bool IsScheduled = false;
3061 };
3062
3063#ifndef NDEBUG
3065 const BoUpSLP::ScheduleData &SD) {
3066 SD.dump(os);
3067 return os;
3068 }
3069#endif
3070
3071 friend struct GraphTraits<BoUpSLP *>;
3072 friend struct DOTGraphTraits<BoUpSLP *>;
3073
3074 /// Contains all scheduling data for a basic block.
3075 /// It does not schedules instructions, which are not memory read/write
3076 /// instructions and their operands are either constants, or arguments, or
3077 /// phis, or instructions from others blocks, or their users are phis or from
3078 /// the other blocks. The resulting vector instructions can be placed at the
3079 /// beginning of the basic block without scheduling (if operands does not need
3080 /// to be scheduled) or at the end of the block (if users are outside of the
3081 /// block). It allows to save some compile time and memory used by the
3082 /// compiler.
3083 /// ScheduleData is assigned for each instruction in between the boundaries of
3084 /// the tree entry, even for those, which are not part of the graph. It is
3085 /// required to correctly follow the dependencies between the instructions and
3086 /// their correct scheduling. The ScheduleData is not allocated for the
3087 /// instructions, which do not require scheduling, like phis, nodes with
3088 /// extractelements/insertelements only or nodes with instructions, with
3089 /// uses/operands outside of the block.
3090 struct BlockScheduling {
3091 BlockScheduling(BasicBlock *BB)
3092 : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
3093
3094 void clear() {
3095 ReadyInsts.clear();
3096 ScheduleStart = nullptr;
3097 ScheduleEnd = nullptr;
3098 FirstLoadStoreInRegion = nullptr;
3099 LastLoadStoreInRegion = nullptr;
3100 RegionHasStackSave = false;
3101
3102 // Reduce the maximum schedule region size by the size of the
3103 // previous scheduling run.
3104 ScheduleRegionSizeLimit -= ScheduleRegionSize;
3105 if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
3106 ScheduleRegionSizeLimit = MinScheduleRegionSize;
3107 ScheduleRegionSize = 0;
3108
3109 // Make a new scheduling region, i.e. all existing ScheduleData is not
3110 // in the new region yet.
3111 ++SchedulingRegionID;
3112 }
3113
3114 ScheduleData *getScheduleData(Instruction *I) {
3115 if (BB != I->getParent())
3116 // Avoid lookup if can't possibly be in map.
3117 return nullptr;
3118 ScheduleData *SD = ScheduleDataMap.lookup(I);
3119 if (SD && isInSchedulingRegion(SD))
3120 return SD;
3121 return nullptr;
3122 }
3123
3124 ScheduleData *getScheduleData(Value *V) {
3125 if (auto *I = dyn_cast<Instruction>(V))
3126 return getScheduleData(I);
3127 return nullptr;
3128 }
3129
3130 ScheduleData *getScheduleData(Value *V, Value *Key) {
3131 if (V == Key)
3132 return getScheduleData(V);
3133 auto I = ExtraScheduleDataMap.find(V);
3134 if (I != ExtraScheduleDataMap.end()) {
3135 ScheduleData *SD = I->second.lookup(Key);
3136 if (SD && isInSchedulingRegion(SD))
3137 return SD;
3138 }
3139 return nullptr;
3140 }
3141
3142 bool isInSchedulingRegion(ScheduleData *SD) const {
3143 return SD->SchedulingRegionID == SchedulingRegionID;
3144 }
3145
3146 /// Marks an instruction as scheduled and puts all dependent ready
3147 /// instructions into the ready-list.
3148 template <typename ReadyListType>
3149 void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
3150 SD->IsScheduled = true;
3151 LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
3152
3153 for (ScheduleData *BundleMember = SD; BundleMember;
3154 BundleMember = BundleMember->NextInBundle) {
3155 if (BundleMember->Inst != BundleMember->OpValue)
3156 continue;
3157
3158 // Handle the def-use chain dependencies.
3159
3160 // Decrement the unscheduled counter and insert to ready list if ready.
3161 auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
3162 doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
3163 if (OpDef && OpDef->hasValidDependencies() &&
3164 OpDef->incrementUnscheduledDeps(-1) == 0) {
3165 // There are no more unscheduled dependencies after
3166 // decrementing, so we can put the dependent instruction
3167 // into the ready list.
3168 ScheduleData *DepBundle = OpDef->FirstInBundle;
3169 assert(!DepBundle->IsScheduled &&
3170 "already scheduled bundle gets ready");
3171 ReadyList.insert(DepBundle);
3172 LLVM_DEBUG(dbgs()
3173 << "SLP: gets ready (def): " << *DepBundle << "\n");
3174 }
3175 });
3176 };
3177
3178 // If BundleMember is a vector bundle, its operands may have been
3179 // reordered during buildTree(). We therefore need to get its operands
3180 // through the TreeEntry.
3181 if (TreeEntry *TE = BundleMember->TE) {
3182 // Need to search for the lane since the tree entry can be reordered.
3183 int Lane = std::distance(TE->Scalars.begin(),
3184 find(TE->Scalars, BundleMember->Inst));
3185 assert(Lane >= 0 && "Lane not set");
3186
3187 // Since vectorization tree is being built recursively this assertion
3188 // ensures that the tree entry has all operands set before reaching
3189 // this code. Couple of exceptions known at the moment are extracts
3190 // where their second (immediate) operand is not added. Since
3191 // immediates do not affect scheduler behavior this is considered
3192 // okay.
3193 auto *In = BundleMember->Inst;
3194 assert(In &&
3195 (isa<ExtractValueInst, ExtractElementInst>(In) ||
3196 In->getNumOperands() == TE->getNumOperands()) &&
3197 "Missed TreeEntry operands?");
3198 (void)In; // fake use to avoid build failure when assertions disabled
3199
3200 for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
3201 OpIdx != NumOperands; ++OpIdx)
3202 if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
3203 DecrUnsched(I);
3204 } else {
3205 // If BundleMember is a stand-alone instruction, no operand reordering
3206 // has taken place, so we directly access its operands.
3207 for (Use &U : BundleMember->Inst->operands())
3208 if (auto *I = dyn_cast<Instruction>(U.get()))
3209 DecrUnsched(I);
3210 }
3211 // Handle the memory dependencies.
3212 for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
3213 if (MemoryDepSD->hasValidDependencies() &&
3214 MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
3215 // There are no more unscheduled dependencies after decrementing,
3216 // so we can put the dependent instruction into the ready list.
3217 ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
3218 assert(!DepBundle->IsScheduled &&
3219 "already scheduled bundle gets ready");
3220 ReadyList.insert(DepBundle);
3222 << "SLP: gets ready (mem): " << *DepBundle << "\n");
3223 }
3224 }
3225 // Handle the control dependencies.
3226 for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
3227 if (DepSD->incrementUnscheduledDeps(-1) == 0) {
3228 // There are no more unscheduled dependencies after decrementing,
3229 // so we can put the dependent instruction into the ready list.
3230 ScheduleData *DepBundle = DepSD->FirstInBundle;
3231 assert(!DepBundle->IsScheduled &&
3232 "already scheduled bundle gets ready");
3233 ReadyList.insert(DepBundle);
3235 << "SLP: gets ready (ctl): " << *DepBundle << "\n");
3236 }
3237 }
3238
3239 }
3240 }
3241
3242 /// Verify basic self consistency properties of the data structure.
3243 void verify() {
3244 if (!ScheduleStart)
3245 return;
3246
3247 assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
3248 ScheduleStart->comesBefore(ScheduleEnd) &&
3249 "Not a valid scheduling region?");
3250
3251 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3252 auto *SD = getScheduleData(I);
3253 if (!SD)
3254 continue;
3255 assert(isInSchedulingRegion(SD) &&
3256 "primary schedule data not in window?");
3257 assert(isInSchedulingRegion(SD->FirstInBundle) &&
3258 "entire bundle in window!");
3259 (void)SD;
3260 doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
3261 }
3262
3263 for (auto *SD : ReadyInsts) {
3264 assert(SD->isSchedulingEntity() && SD->isReady() &&
3265 "item in ready list not ready?");
3266 (void)SD;
3267 }
3268 }
3269
3270 void doForAllOpcodes(Value *V,
3271 function_ref<void(ScheduleData *SD)> Action) {
3272 if (ScheduleData *SD = getScheduleData(V))
3273 Action(SD);
3274 auto I = ExtraScheduleDataMap.find(V);
3275 if (I != ExtraScheduleDataMap.end())
3276 for (auto &P : I->second)
3277 if (isInSchedulingRegion(P.second))
3278 Action(P.second);
3279 }
3280
3281 /// Put all instructions into the ReadyList which are ready for scheduling.
3282 template <typename ReadyListType>
3283 void initialFillReadyList(ReadyListType &ReadyList) {
3284 for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
3285 doForAllOpcodes(I, [&](ScheduleData *SD) {
3286 if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
3287 SD->isReady()) {
3288 ReadyList.insert(SD);
3289 LLVM_DEBUG(dbgs()
3290 << "SLP: initially in ready list: " << *SD << "\n");
3291 }
3292 });
3293 }
3294 }
3295
3296 /// Build a bundle from the ScheduleData nodes corresponding to the
3297 /// scalar instruction for each lane.
3298 ScheduleData *buildBundle(ArrayRef<Value *> VL);
3299
3300 /// Checks if a bundle of instructions can be scheduled, i.e. has no
3301 /// cyclic dependencies. This is only a dry-run, no instructions are
3302 /// actually moved at this stage.
3303 /// \returns the scheduling bundle. The returned Optional value is not
3304 /// std::nullopt if \p VL is allowed to be scheduled.
3305 std::optional<ScheduleData *>
3306 tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
3307 const InstructionsState &S);
3308
3309 /// Un-bundles a group of instructions.
3310 void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
3311
3312 /// Allocates schedule data chunk.
3313 ScheduleData *allocateScheduleDataChunks();
3314
3315 /// Extends the scheduling region so that V is inside the region.
3316 /// \returns true if the region size is within the limit.
3317 bool extendSchedulingRegion(Value *V, const InstructionsState &S);
3318
3319 /// Initialize the ScheduleData structures for new instructions in the
3320 /// scheduling region.
3321 void initScheduleData(Instruction *FromI, Instruction *ToI,
3322 ScheduleData *PrevLoadStore,
3323 ScheduleData *NextLoadStore);
3324
3325 /// Updates the dependency information of a bundle and of all instructions/
3326 /// bundles which depend on the original bundle.
3327 void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
3328 BoUpSLP *SLP);
3329
3330 /// Sets all instruction in the scheduling region to un-scheduled.
3331 void resetSchedule();
3332
3333 BasicBlock *BB;
3334
3335 /// Simple memory allocation for ScheduleData.
3336 std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
3337
3338 /// The size of a ScheduleData array in ScheduleDataChunks.
3339 int ChunkSize;
3340
3341 /// The allocator position in the current chunk, which is the last entry
3342 /// of ScheduleDataChunks.
3343 int ChunkPos;
3344
3345 /// Attaches ScheduleData to Instruction.
3346 /// Note that the mapping survives during all vectorization iterations, i.e.
3347 /// ScheduleData structures are recycled.
3349
3350 /// Attaches ScheduleData to Instruction with the leading key.
3352 ExtraScheduleDataMap;
3353
3354 /// The ready-list for scheduling (only used for the dry-run).
3355 SetVector<ScheduleData *> ReadyInsts;
3356
3357 /// The first instruction of the scheduling region.
3358 Instruction *ScheduleStart = nullptr;
3359
3360 /// The first instruction _after_ the scheduling region.
3361 Instruction *ScheduleEnd = nullptr;
3362
3363 /// The first memory accessing instruction in the scheduling region
3364 /// (can be null).
3365 ScheduleData *FirstLoadStoreInRegion = nullptr;
3366
3367 /// The last memory accessing instruction in the scheduling region
3368 /// (can be null).
3369 ScheduleData *LastLoadStoreInRegion = nullptr;
3370
3371 /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
3372 /// region? Used to optimize the dependence calculation for the
3373 /// common case where there isn't.
3374 bool RegionHasStackSave = false;
3375
3376 /// The current size of the scheduling region.
3377 int ScheduleRegionSize = 0;
3378
3379 /// The maximum size allowed for the scheduling region.
3380 int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
3381
3382 /// The ID of the scheduling region. For a new vectorization iteration this
3383 /// is incremented which "removes" all ScheduleData from the region.
3384 /// Make sure that the initial SchedulingRegionID is greater than the
3385 /// initial SchedulingRegionID in ScheduleData (which is 0).
3386 int SchedulingRegionID = 1;
3387 };
3388
3389 /// Attaches the BlockScheduling structures to basic blocks.
3391
3392 /// Performs the "real" scheduling. Done before vectorization is actually
3393 /// performed in a basic block.
3394 void scheduleBlock(BlockScheduling *BS);
3395
3396 /// List of users to ignore during scheduling and that don't need extracting.
3397 const SmallDenseSet<Value *> *UserIgnoreList = nullptr;
3398
3399 /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
3400 /// sorted SmallVectors of unsigned.
3401 struct OrdersTypeDenseMapInfo {
3402 static OrdersType getEmptyKey() {
3403 OrdersType V;
3404 V.push_back(~1U);
3405 return V;
3406 }
3407
3408 static OrdersType getTombstoneKey() {
3409 OrdersType V;
3410 V.push_back(~2U);
3411 return V;
3412 }
3413
3414 static unsigned getHashValue(const OrdersType &V) {
3415 return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
3416 }
3417
3418 static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
3419 return LHS == RHS;
3420 }
3421 };
3422
3423 // Analysis and block reference.
3424 Function *F;
3425 ScalarEvolution *SE;
3427 TargetLibraryInfo *TLI;
3428 LoopInfo *LI;
3429 DominatorTree *DT;
3430 AssumptionCache *AC;
3431 DemandedBits *DB;
3432 const DataLayout *DL;
3434
3435 unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
3436 unsigned MinVecRegSize; // Set by cl::opt (default: 128).
3437
3438 /// Instruction builder to construct the vectorized tree.
3439 IRBuilder<> Builder;
3440
3441 /// A map of scalar integer values to the smallest bit width with which they
3442 /// can legally be represented. The values map to (width, signed) pairs,
3443 /// where "width" indicates the minimum bit width and "signed" is True if the
3444 /// value must be signed-extended, rather than zero-extended, back to its
3445 /// original width.
3447};
3448
3449} // end namespace slpvectorizer
3450
3451template <> struct GraphTraits<BoUpSLP *> {
3452 using TreeEntry = BoUpSLP::TreeEntry;
3453
3454 /// NodeRef has to be a pointer per the GraphWriter.
3456
3458
3459 /// Add the VectorizableTree to the index iterator to be able to return
3460 /// TreeEntry pointers.
3461 struct ChildIteratorType
3462 : public iterator_adaptor_base<
3463 ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
3465
3467 ContainerTy &VT)
3468 : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
3469
3470 NodeRef operator*() { return I->UserTE; }
3471 };
3472
3474 return R.VectorizableTree[0].get();
3475 }
3476
3477 static ChildIteratorType child_begin(NodeRef N) {
3478 return {N->UserTreeIndices.begin(), N->Container};
3479 }
3480
3481 static ChildIteratorType child_end(NodeRef N) {
3482 return {N->UserTreeIndices.end(), N->Container};
3483 }
3484
3485 /// For the node iterator we just need to turn the TreeEntry iterator into a
3486 /// TreeEntry* iterator so that it dereferences to NodeRef.
3487 class nodes_iterator {
3489 ItTy It;
3490
3491 public:
3492 nodes_iterator(const ItTy &It2) : It(It2) {}
3493 NodeRef operator*() { return It->get(); }
3494 nodes_iterator operator++() {
3495 ++It;
3496 return *this;
3497 }
3498 bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
3499 };
3500
3501 static nodes_iterator nodes_begin(BoUpSLP *R) {
3502 return nodes_iterator(R->VectorizableTree.begin());
3503 }
3504
3505 static nodes_iterator nodes_end(BoUpSLP *R) {
3506 return nodes_iterator(R->VectorizableTree.end());
3507 }
3508
3509 static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
3510};
3511
3512template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
3513 using TreeEntry = BoUpSLP::TreeEntry;
3514
3516
3517 std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
3518 std::string Str;
3519 raw_string_ostream OS(Str);
3520 OS << Entry->Idx << ".\n";
3521 if (isSplat(Entry->Scalars))
3522 OS << "<splat> ";
3523 for (auto *V : Entry->Scalars) {
3524 OS << *V;
3525 if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
3526 return EU.Scalar == V;
3527 }))
3528 OS << " <extract>";
3529 OS << "\n";
3530 }
3531 return Str;
3532 }
3533
3534 static std::string getNodeAttributes(const TreeEntry *Entry,
3535 const BoUpSLP *) {
3536 if (Entry->State == TreeEntry::NeedToGather)
3537 return "color=red";
3538 if (Entry->State == TreeEntry::ScatterVectorize)
3539 return "color=blue";
3540 return "";
3541 }
3542};
3543
3544} // end namespace llvm
3545
3548 for (auto *I : DeletedInstructions) {
3549 for (Use &U : I->operands()) {
3550 auto *Op = dyn_cast<Instruction>(U.get());
3551 if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
3553 DeadInsts.emplace_back(Op);
3554 }
3555 I->dropAllReferences();
3556 }
3557 for (auto *I : DeletedInstructions) {
3558 assert(I->use_empty() &&
3559 "trying to erase instruction with users.");
3560 I->eraseFromParent();
3561 }
3562
3563 // Cleanup any dead scalar code feeding the vectorized instructions
3565
3566#ifdef EXPENSIVE_CHECKS
3567 // If we could guarantee that this call is not extremely slow, we could
3568 // remove the ifdef limitation (see PR47712).
3569 assert(!verifyFunction(*F, &dbgs()));
3570#endif
3571}
3572
3573/// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
3574/// contains original mask for the scalars reused in the node. Procedure
3575/// transform this mask in accordance with the given \p Mask.
3577 assert(!Mask.empty() && Reuses.size() == Mask.size() &&
3578 "Expected non-empty mask.");
3579 SmallVector<int> Prev(Reuses.begin(), Reuses.end());
3580 Prev.swap(Reuses);
3581 for (unsigned I = 0, E = Prev.size(); I < E; ++I)
3582 if (Mask[I] != UndefMaskElem)
3583 Reuses[Mask[I]] = Prev[I];
3584}
3585
3586/// Reorders the given \p Order according to the given \p Mask. \p Order - is
3587/// the original order of the scalars. Procedure transforms the provided order
3588/// in accordance with the given \p Mask. If the resulting \p Order is just an
3589/// identity order, \p Order is cleared.
3591 assert(!Mask.empty() && "Expected non-empty mask.");
3592 SmallVector<int> MaskOrder;
3593 if (Order.empty()) {
3594 MaskOrder.resize(Mask.size());
3595 std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
3596 } else {
3597 inversePermutation(Order, MaskOrder);
3598 }
3599 reorderReuses(MaskOrder, Mask);
3600 if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
3601 Order.clear();
3602 return;
3603 }
3604 Order.assign(Mask.size(), Mask.size());
3605 for (unsigned I = 0, E = Mask.size(); I < E; ++I)
3606 if (MaskOrder[I] != UndefMaskElem)
3607 Order[MaskOrder[I]] = I;
3608 fixupOrderingIndices(Order);
3609}
3610
3611std::optional<BoUpSLP::OrdersType>
3612BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
3613 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3614 unsigned NumScalars = TE.Scalars.size();
3615 OrdersType CurrentOrder(NumScalars, NumScalars);
3616 SmallVector<int> Positions;
3617 SmallBitVector UsedPositions(NumScalars);
3618 const TreeEntry *STE = nullptr;
3619 // Try to find all gathered scalars that are gets vectorized in other
3620 // vectorize node. Here we can have only one single tree vector node to
3621 // correctly identify order of the gathered scalars.
3622 for (unsigned I = 0; I < NumScalars; ++I) {
3623 Value *V = TE.Scalars[I];
3624 if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
3625 continue;
3626 if (const auto *LocalSTE = getTreeEntry(V)) {
3627 if (!STE)
3628 STE = LocalSTE;
3629 else if (STE != LocalSTE)
3630 // Take the order only from the single vector node.
3631 return std::nullopt;
3632 unsigned Lane =
3633 std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
3634 if (Lane >= NumScalars)
3635 return std::nullopt;
3636 if (CurrentOrder[Lane] != NumScalars) {
3637 if (Lane != I)
3638 continue;
3639 UsedPositions.reset(CurrentOrder[Lane]);
3640 }
3641 // The partial identity (where only some elements of the gather node are
3642 // in the identity order) is good.
3643 CurrentOrder[Lane] = I;
3644 UsedPositions.set(I);
3645 }
3646 }
3647 // Need to keep the order if we have a vector entry and at least 2 scalars or
3648 // the vectorized entry has just 2 scalars.
3649 if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
3650 auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
3651 for (unsigned I = 0; I < NumScalars; ++I)
3652 if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
3653 return false;
3654 return true;
3655 };
3656 if (IsIdentityOrder(CurrentOrder)) {
3657 CurrentOrder.clear();
3658 return CurrentOrder;
3659 }
3660 auto *It = CurrentOrder.begin();
3661 for (unsigned I = 0; I < NumScalars;) {
3662 if (UsedPositions.test(I)) {
3663 ++I;
3664 continue;
3665 }
3666 if (*It == NumScalars) {
3667 *It = I;
3668 ++I;
3669 }
3670 ++It;
3671 }
3672 return CurrentOrder;
3673 }
3674 return std::nullopt;
3675}
3676
3677namespace {
3678/// Tracks the state we can represent the loads in the given sequence.
3679enum class LoadsState { Gather, Vectorize, ScatterVectorize };
3680} // anonymous namespace
3681
3682static bool arePointersCompatible(Value *Ptr1, Value *Ptr2,
3683 const TargetLibraryInfo &TLI,
3684 bool CompareOpcodes = true) {
3685 if (getUnderlyingObject(Ptr1) != getUnderlyingObject(Ptr2))
3686 return false;
3687 auto *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
3688 if (!GEP1)
3689 return false;
3690 auto *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
3691 if (!GEP2)
3692 return false;
3693 return GEP1->getNumOperands() == 2 && GEP2->getNumOperands() == 2 &&
3694 ((isConstant(GEP1->getOperand(1)) &&
3695 isConstant(GEP2->getOperand(1))) ||
3696 !CompareOpcodes ||
3697 getSameOpcode({GEP1->getOperand(1), GEP2->getOperand(1)}, TLI)
3698 .getOpcode());
3699}
3700
3701/// Checks if the given array of loads can be represented as a vectorized,
3702/// scatter or just simple gather.
3703static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
3704 const TargetTransformInfo &TTI,
3705 const DataLayout &DL, ScalarEvolution &SE,
3706 LoopInfo &LI, const TargetLibraryInfo &TLI,
3708 SmallVectorImpl<Value *> &PointerOps) {
3709 // Check that a vectorized load would load the same memory as a scalar
3710 // load. For example, we don't want to vectorize loads that are smaller
3711 // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
3712 // treats loading/storing it as an i8 struct. If we vectorize loads/stores
3713 // from such a struct, we read/write packed bits disagreeing with the
3714 // unvectorized version.
3715 Type *ScalarTy = VL0->getType();
3716
3717 if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
3718 return LoadsState::Gather;
3719
3720 // Make sure all loads in the bundle are simple - we can't vectorize
3721 // atomic or volatile loads.
3722 PointerOps.clear();
3723 PointerOps.resize(VL.size());
3724 auto *POIter = PointerOps.begin();
3725 for (Value *V : VL) {
3726 auto *L = cast<LoadInst>(V);
3727 if (!L->isSimple())
3728 return LoadsState::Gather;
3729 *POIter = L->getPointerOperand();
3730 ++POIter;
3731 }
3732
3733 Order.clear();
3734 // Check the order of pointer operands or that all pointers are the same.
3735 bool IsSorted = sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order);
3736 if (IsSorted || all_of(PointerOps, [&](Value *P) {
3737 return arePointersCompatible(P, PointerOps.front(), TLI);
3738 })) {
3739 if (IsSorted) {
3740 Value *Ptr0;
3741 Value *PtrN;
3742 if (Order.empty()) {
3743 Ptr0 = PointerOps.front();
3744 PtrN = PointerOps.back();
3745 } else {
3746 Ptr0 = PointerOps[Order.front()];
3747 PtrN = PointerOps[Order.back()];
3748 }
3749 std::optional<int> Diff =
3750 getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
3751 // Check that the sorted loads are consecutive.
3752 if (static_cast<unsigned>(*Diff) == VL.size() - 1)
3753 return LoadsState::Vectorize;
3754 }
3755 // TODO: need to improve analysis of the pointers, if not all of them are
3756 // GEPs or have > 2 operands, we end up with a gather node, which just
3757 // increases the cost.
3758 Loop *L = LI.getLoopFor(cast<LoadInst>(VL0)->getParent());
3759 bool ProfitableGatherPointers =
3760 static_cast<unsigned>(count_if(PointerOps, [L](Value *V) {
3761 return L && L->isLoopInvariant(V);
3762 })) <= VL.size() / 2 && VL.size() > 2;
3763 if (ProfitableGatherPointers || all_of(PointerOps, [IsSorted](Value *P) {
3764 auto *GEP = dyn_cast<GetElementPtrInst>(P);
3765 return (IsSorted && !GEP && doesNotNeedToBeScheduled(P)) ||
3766 (GEP && GEP->getNumOperands() == 2);
3767 })) {
3768 Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
3769 for (Value *V : VL)
3770 CommonAlignment =
3771 std::min(CommonAlignment, cast<LoadInst>(V)->getAlign());
3772 auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
3773 if (TTI.isLegalMaskedGather(VecTy, CommonAlignment) &&
3774 !TTI.forceScalarizeMaskedGather(VecTy, CommonAlignment))
3775 return LoadsState::ScatterVectorize;
3776 }
3777 }
3778
3779 return LoadsState::Gather;
3780}
3781
3783 const DataLayout &DL, ScalarEvolution &SE,
3784 SmallVectorImpl<unsigned> &SortedIndices) {
3786 VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
3787 "Expected list of pointer operands.");
3788 // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
3789 // Ptr into, sort and return the sorted indices with values next to one
3790 // another.
3792 Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U));
3793
3794 unsigned Cnt = 1;
3795 for (Value *Ptr : VL.drop_front()) {
3796 bool Found = any_of(Bases, [&](auto &Base) {
3797 std::optional<int> Diff =
3798 getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE,
3799 /*StrictCheck=*/true);
3800 if (!Diff)
3801 return false;
3802
3803 Base.second.emplace_back(Ptr, *Diff, Cnt++);
3804 return true;
3805 });
3806
3807 if (!Found) {
3808 // If we haven't found enough to usefully cluster, return early.
3809 if (Bases.size() > VL.size() / 2 - 1)
3810 return false;
3811
3812 // Not found already - add a new Base
3813 Bases[Ptr].emplace_back(Ptr, 0, Cnt++);
3814 }
3815 }
3816
3817 // For each of the bases sort the pointers by Offset and check if any of the
3818 // base become consecutively allocated.
3819 bool AnyConsecutive = false;
3820 for (auto &Base : Bases) {
3821 auto &Vec = Base.second;
3822 if (Vec.size() > 1) {
3823 llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X,
3824 const std::tuple<Value *, int, unsigned> &Y) {
3825 return std::get<1>(X) < std::get<1>(Y);
3826 });
3827 int InitialOffset = std::get<1>(Vec[0]);
3828 AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) {
3829 return std::get<1>(P.value()) == int(P.index()) + InitialOffset;
3830 });
3831 }
3832 }
3833
3834 // Fill SortedIndices array only if it looks worth-while to sort the ptrs.
3835 SortedIndices.clear();
3836 if (!AnyConsecutive)
3837 return false;
3838
3839 for (auto &Base : Bases) {
3840 for (auto &T : Base.second)
3841 SortedIndices.push_back(std::get<2>(T));
3842 }
3843
3844 assert(SortedIndices.size() == VL.size() &&
3845 "Expected SortedIndices to be the size of VL");
3846 return true;
3847}
3848
3849std::optional<BoUpSLP::OrdersType>
3850BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
3851 assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
3852 Type *ScalarTy = TE.Scalars[0]->getType();
3853
3855 Ptrs.reserve(TE.Scalars.size());
3856 for (Value *V : TE.Scalars) {
3857 auto *L = dyn_cast<LoadInst>(V);
3858 if (!L || !L->isSimple())
3859 return std::nullopt;
3860 Ptrs.push_back(L->getPointerOperand());
3861 }
3862
3863 BoUpSLP::OrdersType Order;
3864 if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order))
3865 return Order;
3866 return std::nullopt;
3867}
3868
3869/// Check if two insertelement instructions are from the same buildvector.
3872 function_ref<Value *(InsertElementInst *)> GetBaseOperand) {
3873 // Instructions must be from the same basic blocks.
3874 if (VU->getParent() != V->getParent())
3875 return false;
3876 // Checks if 2 insertelements are from the same buildvector.
3877 if (VU->getType() != V->getType())
3878 return false;
3879 // Multiple used inserts are separate nodes.
3880 if (!VU->hasOneUse() && !V->hasOneUse())
3881 return false;
3882 auto *IE1 = VU;
3883 auto *IE2 = V;
3884 std::optional<unsigned> Idx1 = getInsertIndex(IE1);
3885 std::optional<unsigned> Idx2 = getInsertIndex(IE2);
3886 if (Idx1 == std::nullopt || Idx2 == std::nullopt)
3887 return false;
3888 // Go through the vector operand of insertelement instructions trying to find
3889 // either VU as the original vector for IE2 or V as the original vector for
3890 // IE1.
3891 do {
3892 if (IE2 == VU)
3893 return VU->hasOneUse();
3894 if (IE1 == V)
3895 return V->hasOneUse();
3896 if (IE1) {
3897 if ((IE1 != VU && !IE1->hasOneUse()) ||
3898 getInsertIndex(IE1).value_or(*Idx2) == *Idx2)
3899 IE1 = nullptr;
3900 else
3901 IE1 = dyn_cast_or_null<InsertElementInst>(GetBaseOperand(IE1));
3902 }
3903 if (IE2) {
3904 if ((IE2 != V && !IE2->hasOneUse()) ||
3905 getInsertIndex(IE2).value_or(*Idx1) == *Idx1)
3906 IE2 = nullptr;
3907 else
3908 IE2 = dyn_cast_or_null<InsertElementInst>(GetBaseOperand(IE2));
3909 }
3910 } while (IE1 || IE2);
3911 return false;
3912}
3913
3914std::optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
3915 bool TopToBottom) {
3916 // No need to reorder if need to shuffle reuses, still need to shuffle the
3917 // node.
3918 if (!TE.ReuseShuffleIndices.empty()) {
3919 // Check if reuse shuffle indices can be improved by reordering.
3920 // For this, check that reuse mask is "clustered", i.e. each scalar values
3921 // is used once in each submask of size <number_of_scalars>.
3922 // Example: 4 scalar values.
3923 // ReuseShuffleIndices mask: 0, 1, 2, 3, 3, 2, 0, 1 - clustered.
3924 // 0, 1, 2, 3, 3, 3, 1, 0 - not clustered, because
3925 // element 3 is used twice in the second submask.
3926 unsigned Sz = TE.Scalars.size();
3927 if (!ShuffleVectorInst::isOneUseSingleSourceMask(TE.ReuseShuffleIndices,
3928 Sz))
3929 return std::nullopt;
3930 unsigned VF = TE.getVectorFactor();
3931 // Try build correct order for extractelement instructions.
3932 SmallVector<int> ReusedMask(TE.ReuseShuffleIndices.begin(),
3933 TE.ReuseShuffleIndices.end());
3934 if (TE.getOpcode() == Instruction::ExtractElement && !TE.isAltShuffle() &&
3935 all_of(TE.Scalars, [Sz](Value *V) {
3936 std::optional<unsigned> Idx = getExtractIndex(cast<Instruction>(V));
3937 return Idx && *Idx < Sz;
3938 })) {
3939 SmallVector<int> ReorderMask(Sz, UndefMaskElem);
3940 if (TE.ReorderIndices.empty())
3941 std::iota(ReorderMask.begin(), ReorderMask.end(), 0);
3942 else
3943 inversePermutation(TE.ReorderIndices, ReorderMask);
3944 for (unsigned I = 0; I < VF; ++I) {
3945 int &Idx = ReusedMask[I];
3946 if (Idx == UndefMaskElem)
3947 continue;
3948 Value *V = TE.Scalars[ReorderMask[Idx]];
3949 std::optional<unsigned> EI = getExtractIndex(cast<Instruction>(V));
3950 Idx = std::distance(ReorderMask.begin(), find(ReorderMask, *EI));
3951 }
3952 }
3953 // Build the order of the VF size, need to reorder reuses shuffles, they are
3954 // always of VF size.
3955 OrdersType ResOrder(VF);
3956 std::iota(ResOrder.begin(), ResOrder.end(), 0);
3957 auto *It = ResOrder.begin();
3958 for (unsigned K = 0; K < VF; K += Sz) {
3959 OrdersType CurrentOrder(TE.ReorderIndices);
3960 SmallVector<int> SubMask{ArrayRef(ReusedMask).slice(K, Sz)};
3961 if (SubMask.front() == UndefMaskElem)
3962 std::iota(SubMask.begin(), SubMask.end(), 0);
3963 reorderOrder(CurrentOrder, SubMask);
3964 transform(CurrentOrder, It, [K](unsigned Pos) { return Pos + K; });
3965 std::advance(It, Sz);
3966 }
3967 if (all_of(enumerate(ResOrder),
3968 [](const auto &Data) { return Data.index() == Data.value(); }))
3969 return {}; // Use identity order.
3970 return ResOrder;
3971 }
3972 if (TE.State == TreeEntry::Vectorize &&
3973 (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
3974 (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
3975 !TE.isAltShuffle())
3976 return TE.ReorderIndices;
3977 if (TE.State == TreeEntry::Vectorize && TE.getOpcode() == Instruction::PHI) {
3978 auto PHICompare = [](llvm::Value *V1, llvm::Value *V2) {
3979 if (!V1->hasOneUse() || !V2->hasOneUse())
3980 return false;
3981 auto *FirstUserOfPhi1 = cast<Instruction>(*V1->user_begin());
3982 auto *FirstUserOfPhi2 = cast<Instruction>(*V2->user_begin());
3983 if (auto *IE1 = dyn_cast<InsertElementInst>(FirstUserOfPhi1))
3984 if (auto *IE2 = dyn_cast<InsertElementInst>(FirstUserOfPhi2)) {
3986 IE1, IE2,
3987 [](InsertElementInst *II) { return II->getOperand(0); }))
3988 return false;
3989 std::optional<unsigned> Idx1 = getInsertIndex(IE1);
3990 std::optional<unsigned> Idx2 = getInsertIndex(IE2);
3991 if (Idx1 == std::nullopt || Idx2 == std::nullopt)
3992 return false;
3993 return *Idx1 < *Idx2;
3994 }
3995 if (auto *EE1 = dyn_cast<ExtractElementInst>(FirstUserOfPhi1))
3996 if (auto *EE2 = dyn_cast<ExtractElementInst>(FirstUserOfPhi2)) {
3997 if (EE1->getOperand(0) != EE2->getOperand(0))
3998 return false;
3999 std::optional<unsigned> Idx1 = getExtractIndex(EE1);
4000 std::optional<unsigned> Idx2 = getExtractIndex(EE2);
4001 if (Idx1 == std::nullopt || Idx2 == std::nullopt)
4002 return false;
4003 return *Idx1 < *Idx2;
4004 }
4005 return false;
4006 };
4007 auto IsIdentityOrder = [](const OrdersType &Order) {
4008 for (unsigned Idx : seq<unsigned>(0, Order.size()))
4009 if (Idx != Order[Idx])
4010 return false;
4011 return true;
4012 };
4013 if (!TE.ReorderIndices.empty())
4014 return TE.ReorderIndices;
4017 OrdersType ResOrder(TE.Scalars.size());
4018 for (unsigned Id = 0, Sz = TE.Scalars.size(); Id < Sz; ++Id) {
4019 PhiToId[TE.Scalars[Id]] = Id;
4020 Phis.push_back(TE.Scalars[Id]);
4021 }
4022 llvm::stable_sort(Phis, PHICompare);
4023 for (unsigned Id = 0, Sz = Phis.size(); Id < Sz; ++Id)
4024 ResOrder[Id] = PhiToId[Phis[Id]];
4025 if (IsIdentityOrder(ResOrder))
4026 return {};
4027 return ResOrder;
4028 }
4029 if (TE.State == TreeEntry::NeedToGather) {
4030 // TODO: add analysis of other gather nodes with extractelement
4031 // instructions and other values/instructions, not only undefs.
4032 if (((TE.getOpcode() == Instruction::ExtractElement &&
4033 !TE.isAltShuffle()) ||
4034 (all_of(TE.Scalars,
4035 [](Value *V) {
4036 return isa<UndefValue, ExtractElementInst>(V);
4037 }) &&
4038 any_of(TE.Scalars,
4039 [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
4040 all_of(TE.Scalars,
4041 [](Value *V) {
4042 auto *EE = dyn_cast<ExtractElementInst>(V);
4043 return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
4044 }) &&
4045 allSameType(TE.Scalars)) {
4046 // Check that gather of extractelements can be represented as
4047 // just a shuffle of a single vector.
4048 OrdersType CurrentOrder;
4049 bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
4050 if (Reuse || !CurrentOrder.empty()) {
4051 if (!CurrentOrder.empty())
4052 fixupOrderingIndices(CurrentOrder);
4053 return CurrentOrder;
4054 }
4055 }
4056 if (std::optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
4057 return CurrentOrder;
4058 if (TE.Scalars.size() >= 4)
4059 if (std::optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
4060 return Order;
4061 }
4062 return std::nullopt;
4063}
4064
4065/// Checks if the given mask is a "clustered" mask with the same clusters of
4066/// size \p Sz, which are not identity submasks.
4068 unsigned Sz) {
4069 ArrayRef<int> FirstCluster = Mask.slice(0, Sz);
4070 if (ShuffleVectorInst::isIdentityMask(FirstCluster))
4071 return false;
4072 for (unsigned I = Sz, E = Mask.size(); I < E; I += Sz) {
4073 ArrayRef<int> Cluster = Mask.slice(I, Sz);
4074 if (Cluster != FirstCluster)
4075 return false;
4076 }
4077 return true;
4078}
4079
4080void BoUpSLP::reorderNodeWithReuses(TreeEntry &TE, ArrayRef<int> Mask) const {
4081 // Reorder reuses mask.
4082 reorderReuses(TE.ReuseShuffleIndices, Mask);
4083 const unsigned Sz = TE.Scalars.size();
4084 // For vectorized and non-clustered reused no need to do anything else.
4085 if (TE.State != TreeEntry::NeedToGather ||
4087 Sz) ||
4088 !isRepeatedNonIdentityClusteredMask(TE.ReuseShuffleIndices, Sz))
4089 return;
4090 SmallVector<int> NewMask;
4091 inversePermutation(TE.ReorderIndices, NewMask);
4092 addMask(NewMask, TE.ReuseShuffleIndices);
4093 // Clear reorder since it is going to be applied to the new mask.
4094 TE.ReorderIndices.clear();
4095 // Try to improve gathered nodes with clustered reuses, if possible.
4096 ArrayRef<int> Slice = ArrayRef(NewMask).slice(0, Sz);
4097 SmallVector<unsigned> NewOrder(Slice.begin(), Slice.end());
4098 inversePermutation(NewOrder, NewMask);
4099 reorderScalars(TE.Scalars, NewMask);
4100 // Fill the reuses mask with the identity submasks.
4101 for (auto *It = TE.ReuseShuffleIndices.begin(),
4102 *End = TE.ReuseShuffleIndices.end();
4103 It != End; std::advance(It, Sz))
4104 std::iota(It, std::next(It, Sz), 0);
4105}
4106
4108 // Maps VF to the graph nodes.
4110 // ExtractElement gather nodes which can be vectorized and need to handle
4111 // their ordering.
4113
4114 // Phi nodes can have preferred ordering based on their result users
4116
4117 // AltShuffles can also have a preferred ordering that leads to fewer
4118 // instructions, e.g., the addsub instruction in x86.
4119 DenseMap<const TreeEntry *, OrdersType> AltShufflesToOrders;
4120
4121 // Maps a TreeEntry to the reorder indices of external users.
4123 ExternalUserReorderMap;
4124 // FIXME: Workaround for syntax error reported by MSVC buildbots.
4125 TargetTransformInfo &TTIRef = *TTI;
4126 // Find all reorderable nodes with the given VF.
4127 // Currently the are vectorized stores,loads,extracts + some gathering of
4128 // extracts.
4129 for_each(VectorizableTree, [this, &TTIRef, &VFToOrderedEntries,
4130 &GathersToOrders, &ExternalUserReorderMap,
4131 &AltShufflesToOrders, &PhisToOrders](
4132 const std::unique_ptr<TreeEntry> &TE) {
4133 // Look for external users that will probably be vectorized.
4134 SmallVector<OrdersType, 1> ExternalUserReorderIndices =
4135 findExternalStoreUsersReorderIndices(TE.get());
4136 if (!ExternalUserReorderIndices.empty()) {
4137 VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
4138 ExternalUserReorderMap.try_emplace(TE.get(),
4139 std::move(ExternalUserReorderIndices));
4140 }
4141
4142 // Patterns like [fadd,fsub] can be combined into a single instruction in
4143 // x86. Reordering them into [fsub,fadd] blocks this pattern. So we need
4144 // to take into account their order when looking for the most used order.
4145 if (TE->isAltShuffle()) {
4146 VectorType *VecTy =
4147 FixedVectorType::get(TE->Scalars[0]->getType(), TE->Scalars.size());
4148 unsigned Opcode0 = TE->getOpcode();
4149 unsigned Opcode1 = TE->getAltOpcode();
4150 // The opcode mask selects between the two opcodes.
4151 SmallBitVector OpcodeMask(TE->Scalars.size(), false);
4152 for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size()))
4153 if (cast<Instruction>(TE->Scalars[Lane])->getOpcode() == Opcode1)
4154 OpcodeMask.set(Lane);
4155 // If this pattern is supported by the target then we consider the order.
4156 if (TTIRef.isLegalAltInstr(VecTy, Opcode0, Opcode1, OpcodeMask)) {
4157 VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
4158 AltShufflesToOrders.try_emplace(TE.get(), OrdersType());
4159 }
4160 // TODO: Check the reverse order too.
4161 }
4162
4163 if (std::optional<OrdersType> CurrentOrder =
4164 getReorderingData(*TE, /*TopToBottom=*/true)) {
4165 // Do not include ordering for nodes used in the alt opcode vectorization,
4166 // better to reorder them during bottom-to-top stage. If follow the order
4167 // here, it causes reordering of the whole graph though actually it is
4168 // profitable just to reorder the subgraph that starts from the alternate
4169 // opcode vectorization node. Such nodes already end-up with the shuffle
4170 // instruction and it is just enough to change this shuffle rather than
4171 // rotate the scalars for the whole graph.
4172 unsigned Cnt = 0;
4173 const TreeEntry *UserTE = TE.get();
4174 while (UserTE && Cnt < RecursionMaxDepth) {
4175 if (UserTE->UserTreeIndices.size() != 1)
4176 break;
4177 if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
4178 return EI.UserTE->State == TreeEntry::Vectorize &&
4179 EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
4180 }))
4181 return;
4182 UserTE = UserTE->UserTreeIndices.back().UserTE;
4183 ++Cnt;
4184 }
4185 VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
4186 if (TE->State != TreeEntry::Vectorize || !TE->ReuseShuffleIndices.empty())
4187 GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
4188 if (TE->State == TreeEntry::Vectorize &&
4189 TE->getOpcode() == Instruction::PHI)
4190 PhisToOrders.try_emplace(TE.get(), *CurrentOrder);
4191 }
4192 });
4193
4194 // Reorder the graph nodes according to their vectorization factor.
4195 for (unsigned VF = VectorizableTree.front()->getVectorFactor(); VF > 1;
4196 VF /= 2) {
4197 auto It = VFToOrderedEntries.find(VF);
4198 if (It == VFToOrderedEntries.end())
4199 continue;
4200 // Try to find the most profitable order. We just are looking for the most
4201 // used order and reorder scalar elements in the nodes according to this
4202 // mostly used order.
4203 ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
4204 // All operands are reordered and used only in this node - propagate the
4205 // most used order to the user node.
4208 OrdersUses;
4210 for (const TreeEntry *OpTE : OrderedEntries) {
4211 // No need to reorder this nodes, still need to extend and to use shuffle,
4212 // just need to merge reordering shuffle and the reuse shuffle.
4213 if (!OpTE->ReuseShuffleIndices.empty() && !GathersToOrders.count(OpTE))
4214 continue;
4215 // Count number of orders uses.
4216 const auto &Order = [OpTE, &GathersToOrders, &AltShufflesToOrders,
4217 &PhisToOrders]() -> const OrdersType & {
4218 if (OpTE->State == TreeEntry::NeedToGather ||
4219 !OpTE->ReuseShuffleIndices.empty()) {
4220 auto It = GathersToOrders.find(OpTE);
4221 if (It != GathersToOrders.end())
4222 return It->second;
4223 }
4224 if (OpTE->isAltShuffle()) {
4225 auto It = AltShufflesToOrders.find(OpTE);
4226 if (It != AltShufflesToOrders.end())
4227 return It->second;
4228 }
4229 if (OpTE->State == TreeEntry::Vectorize &&
4230 OpTE->getOpcode() == Instruction::PHI) {
4231 auto It = PhisToOrders.find(OpTE);
4232 if (It != PhisToOrders.end())
4233 return It->second;
4234 }
4235 return OpTE->ReorderIndices;
4236 }();
4237 // First consider the order of the external scalar users.
4238 auto It = ExternalUserReorderMap.find(OpTE);
4239 if (It != ExternalUserReorderMap.end()) {
4240 const auto &ExternalUserReorderIndices = It->second;
4241 // If the OpTE vector factor != number of scalars - use natural order,
4242 // it is an attempt to reorder node with reused scalars but with
4243 // external uses.
4244 if (OpTE->getVectorFactor() != OpTE->Scalars.size()) {
4245 OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
4246 ExternalUserReorderIndices.size();
4247 } else {
4248 for (const OrdersType &ExtOrder : ExternalUserReorderIndices)
4249 ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second;
4250 }
4251 // No other useful reorder data in this entry.
4252 if (Order.empty())
4253 continue;
4254 }
4255 // Stores actually store the mask, not the order, need to invert.
4256 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
4257 OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
4258 SmallVector<int> Mask;
4259 inversePermutation(Order, Mask);
4260 unsigned E = Order.size();
4261 OrdersType CurrentOrder(E, E);
4262 transform(Mask, CurrentOrder.begin(), [E](int Idx) {
4263 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
4264 });
4265 fixupOrderingIndices(CurrentOrder);
4266 ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
4267 } else {
4268 ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
4269 }
4270 }
4271 // Set order of the user node.
4272 if (OrdersUses.empty())
4273 continue;
4274 // Choose the most used order.
4275 ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
4276 unsigned Cnt = OrdersUses.front().second;
4277 for (const auto &Pair : drop_begin(OrdersUses)) {
4278 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
4279 BestOrder = Pair.first;
4280 Cnt = Pair.second;
4281 }
4282 }
4283 // Set order of the user node.
4284 if (BestOrder.empty())
4285 continue;
4286 SmallVector<int> Mask;
4287 inversePermutation(BestOrder, Mask);
4288 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
4289 unsigned E = BestOrder.size();
4290 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
4291 return I < E ? static_cast<int>(I) : UndefMaskElem;
4292 });
4293 // Do an actual reordering, if profitable.
4294 for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
4295 // Just do the reordering for the nodes with the given VF.
4296 if (TE->Scalars.size() != VF) {
4297 if (TE->ReuseShuffleIndices.size() == VF) {
4298 // Need to reorder the reuses masks of the operands with smaller VF to
4299 // be able to find the match between the graph nodes and scalar
4300 // operands of the given node during vectorization/cost estimation.
4301 assert(all_of(TE->UserTreeIndices,
4302 [VF, &TE](const EdgeInfo &EI) {
4303 return EI.UserTE->Scalars.size() == VF ||
4304 EI.UserTE->Scalars.size() ==
4305 TE->Scalars.size();
4306 }) &&
4307 "All users must be of VF size.");
4308 // Update ordering of the operands with the smaller VF than the given
4309 // one.
4310 reorderNodeWithReuses(*TE, Mask);
4311 }
4312 continue;
4313 }
4314 if (TE->State == TreeEntry::Vectorize &&
4316 InsertElementInst>(TE->getMainOp()) &&
4317 !TE->isAltShuffle()) {
4318 // Build correct orders for extract{element,value}, loads and
4319 // stores.
4320 reorderOrder(TE->ReorderIndices, Mask);
4321 if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
4322 TE->reorderOperands(Mask);
4323 } else {
4324 // Reorder the node and its operands.
4325 TE->reorderOperands(Mask);
4326 assert(TE->ReorderIndices.empty() &&
4327 "Expected empty reorder sequence.");
4328 reorderScalars(TE->Scalars, Mask);
4329 }
4330 if (!TE->ReuseShuffleIndices.empty()) {
4331 // Apply reversed order to keep the original ordering of the reused
4332 // elements to avoid extra reorder indices shuffling.
4333 OrdersType CurrentOrder;
4334 reorderOrder(CurrentOrder, MaskOrder);
4335 SmallVector<int> NewReuses;
4336 inversePermutation(CurrentOrder, NewReuses);
4337 addMask(NewReuses, TE->ReuseShuffleIndices);
4338 TE->ReuseShuffleIndices.swap(NewReuses);
4339 }
4340 }
4341 }
4342}
4343
4344bool BoUpSLP::canReorderOperands(
4345 TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
4346 ArrayRef<TreeEntry *> ReorderableGathers,
4347 SmallVectorImpl<TreeEntry *> &GatherOps) {
4348 for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
4349 if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
4350 return OpData.first == I &&
4351 OpData.second->State == TreeEntry::Vectorize;
4352 }))
4353 continue;
4354 if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
4355 // Do not reorder if operand node is used by many user nodes.
4356 if (any_of(TE->UserTreeIndices,
4357 [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
4358 return false;
4359 // Add the node to the list of the ordered nodes with the identity
4360 // order.
4361 Edges.emplace_back(I, TE);
4362 // Add ScatterVectorize nodes to the list of operands, where just
4363 // reordering of the scalars is required. Similar to the gathers, so
4364 // simply add to the list of gathered ops.
4365 // If there are reused scalars, process this node as a regular vectorize
4366 // node, just reorder reuses mask.
4367 if (TE->State != TreeEntry::Vectorize && TE->ReuseShuffleIndices.empty())
4368 GatherOps.push_back(TE);
4369 continue;
4370 }
4371 TreeEntry *Gather = nullptr;
4372 if (count_if(ReorderableGathers,
4373 [&Gather, UserTE, I](TreeEntry *TE) {
4374 assert(TE->State != TreeEntry::Vectorize &&
4375 "Only non-vectorized nodes are expected.");
4376 if (any_of(TE->UserTreeIndices,
4377 [UserTE, I](const EdgeInfo &EI) {
4378 return EI.UserTE == UserTE && EI.EdgeIdx == I;
4379 })) {
4380 assert(TE->isSame(UserTE->getOperand(I)) &&
4381 "Operand entry does not match operands.");
4382 Gather = TE;
4383 return true;
4384 }
4385 return false;
4386 }) > 1 &&
4387 !all_of(UserTE->getOperand(I), isConstant))
4388 return false;
4389 if (Gather)
4390 GatherOps.push_back(Gather);
4391 }
4392 return true;
4393}
4394
4395void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
4396 SetVector<TreeEntry *> OrderedEntries;
4398 // Find all reorderable leaf nodes with the given VF.
4399 // Currently the are vectorized loads,extracts without alternate operands +
4400 // some gathering of extracts.
4401 SmallVector<TreeEntry *> NonVectorized;
4402 for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
4403 &NonVectorized](
4404 const std::unique_ptr<TreeEntry> &TE) {
4405 if (TE->State != TreeEntry::Vectorize)
4406 NonVectorized.push_back(TE.get());
4407 if (std::optional<OrdersType> CurrentOrder =
4408 getReorderingData(*TE, /*TopToBottom=*/false)) {
4409 OrderedEntries.insert(TE.get());
4410 if (TE->State != TreeEntry::Vectorize || !TE->ReuseShuffleIndices.empty())
4411 GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
4412 }
4413 });
4414
4415 // 1. Propagate order to the graph nodes, which use only reordered nodes.
4416 // I.e., if the node has operands, that are reordered, try to make at least
4417 // one operand order in the natural order and reorder others + reorder the
4418 // user node itself.
4420 while (!OrderedEntries.empty()) {
4421 // 1. Filter out only reordered nodes.
4422 // 2. If the entry has multiple uses - skip it and jump to the next node.
4424 SmallVector<TreeEntry *> Filtered;
4425 for (TreeEntry *TE : OrderedEntries) {
4426 if (!(TE->State == TreeEntry::Vectorize ||
4427 (TE->State == TreeEntry::NeedToGather &&
4428 GathersToOrders.count(TE))) ||
4429 TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
4430 !all_of(drop_begin(TE->UserTreeIndices),
4431 [TE](const EdgeInfo &EI) {
4432 return EI.UserTE == TE->UserTreeIndices.front().UserTE;
4433 }) ||
4434 !Visited.insert(TE).second) {
4435 Filtered.push_back(TE);
4436 continue;
4437 }
4438 // Build a map between user nodes and their operands order to speedup
4439 // search. The graph currently does not provide this dependency directly.
4440 for (EdgeInfo &EI : TE->UserTreeIndices) {
4441 TreeEntry *UserTE = EI.UserTE;
4442 auto It = Users.find(UserTE);
4443 if (It == Users.end())
4444 It = Users.insert({UserTE, {}}).first;
4445 It->second.emplace_back(EI.EdgeIdx, TE);
4446 }
4447 }
4448 // Erase filtered entries.
4449 for_each(Filtered,
4450 [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
4452 std::pair<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>>>
4453 UsersVec(Users.begin(), Users.end());
4454 sort(UsersVec, [](const auto &Data1, const auto &Data2) {
4455 return Data1.first->Idx > Data2.first->Idx;
4456 });
4457 for (auto &Data : UsersVec) {
4458 // Check that operands are used only in the User node.
4459 SmallVector<TreeEntry *> GatherOps;
4460 if (!canReorderOperands(Data.first, Data.second, NonVectorized,
4461 GatherOps)) {
4462 for_each(Data.second,
4463 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4464 OrderedEntries.remove(Op.second);
4465 });
4466 continue;
4467 }
4468 // All operands are reordered and used only in this node - propagate the
4469 // most used order to the user node.
4472 OrdersUses;
4473 // Do the analysis for each tree entry only once, otherwise the order of
4474 // the same node my be considered several times, though might be not
4475 // profitable.
4478 for (const auto &Op : Data.second) {
4479 TreeEntry *OpTE = Op.second;
4480 if (!VisitedOps.insert(OpTE).second)
4481 continue;
4482 if (!OpTE->ReuseShuffleIndices.empty() && !GathersToOrders.count(OpTE))
4483 continue;
4484 const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
4485 if (OpTE->State == TreeEntry::NeedToGather ||
4486 !OpTE->ReuseShuffleIndices.empty())
4487 return GathersToOrders.find(OpTE)->second;
4488 return OpTE->ReorderIndices;
4489 }();
4490 unsigned NumOps = count_if(
4491 Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
4492 return P.second == OpTE;
4493 });
4494 // Stores actually store the mask, not the order, need to invert.
4495 if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
4496 OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
4497 SmallVector<int> Mask;
4498 inversePermutation(Order, Mask);
4499 unsigned E = Order.size();
4500 OrdersType CurrentOrder(E, E);
4501 transform(Mask, CurrentOrder.begin(), [E](int Idx) {
4502 return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
4503 });
4504 fixupOrderingIndices(CurrentOrder);
4505 OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
4506 NumOps;
4507 } else {
4508 OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
4509 }
4510 auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
4511 const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
4512 const TreeEntry *TE) {
4513 if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
4514 (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
4515 (IgnoreReorder && TE->Idx == 0))
4516 return true;
4517 if (TE->State == TreeEntry::NeedToGather) {
4518 auto It = GathersToOrders.find(TE);
4519 if (It != GathersToOrders.end())
4520 return !It->second.empty();
4521 return true;
4522 }
4523 return false;
4524 };
4525 for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
4526 TreeEntry *UserTE = EI.UserTE;
4527 if (!VisitedUsers.insert(UserTE).second)
4528 continue;
4529 // May reorder user node if it requires reordering, has reused
4530 // scalars, is an alternate op vectorize node or its op nodes require
4531 // reordering.
4532 if (AllowsReordering(UserTE))
4533 continue;
4534 // Check if users allow reordering.
4535 // Currently look up just 1 level of operands to avoid increase of
4536 // the compile time.
4537 // Profitable to reorder if definitely more operands allow
4538 // reordering rather than those with natural order.
4540 if (static_cast<unsigned>(count_if(
4541 Ops, [UserTE, &AllowsReordering](
4542 const std::pair<unsigned, TreeEntry *> &Op) {
4543 return AllowsReordering(Op.second) &&
4544 all_of(Op.second->UserTreeIndices,
4545 [UserTE](const EdgeInfo &EI) {
4546 return EI.UserTE == UserTE;
4547 });
4548 })) <= Ops.size() / 2)
4549 ++Res.first->second;
4550 }
4551 }
4552 // If no orders - skip current nodes and jump to the next one, if any.
4553 if (OrdersUses.empty()) {
4554 for_each(Data.second,
4555 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4556 OrderedEntries.remove(Op.second);
4557 });
4558 continue;
4559 }
4560 // Choose the best order.
4561 ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
4562 unsigned Cnt = OrdersUses.front().second;
4563 for (const auto &Pair : drop_begin(OrdersUses)) {
4564 if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
4565 BestOrder = Pair.first;
4566 Cnt = Pair.second;
4567 }
4568 }
4569 // Set order of the user node (reordering of operands and user nodes).
4570 if (BestOrder.empty()) {
4571 for_each(Data.second,
4572 [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
4573 OrderedEntries.remove(Op.second);
4574 });
4575 continue;
4576 }
4577 // Erase operands from OrderedEntries list and adjust their orders.
4578 VisitedOps.clear();
4579 SmallVector<int> Mask;
4580 inversePermutation(BestOrder, Mask);
4581 SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
4582 unsigned E = BestOrder.size();
4583 transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
4584 return I < E ? static_cast<int>(I) : UndefMaskElem;
4585 });
4586 for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
4587 TreeEntry *TE = Op.second;
4588 OrderedEntries.remove(TE);
4589 if (!VisitedOps.insert(TE).second)
4590 continue;
4591 if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
4592 reorderNodeWithReuses(*TE, Mask);
4593 continue;
4594 }
4595 // Gathers are processed separately.
4596 if (TE->State != TreeEntry::Vectorize)
4597 continue;
4598 assert((BestOrder.size() == TE->ReorderIndices.size() ||
4599 TE->ReorderIndices.empty()) &&
4600 "Non-matching sizes of user/operand entries.");
4601 reorderOrder(TE->ReorderIndices, Mask);
4602 if (IgnoreReorder && TE == VectorizableTree.front().get())
4603 IgnoreReorder = false;
4604 }
4605 // For gathers just need to reorder its scalars.
4606 for (TreeEntry *Gather : GatherOps) {
4607 assert(Gather->ReorderIndices.empty() &&
4608 "Unexpected reordering of gathers.");
4609 if (!Gather->ReuseShuffleIndices.empty()) {
4610 // Just reorder reuses indices.
4611 reorderReuses(Gather->ReuseShuffleIndices, Mask);
4612 continue;
4613 }
4614 reorderScalars(Gather->Scalars, Mask);
4615 OrderedEntries.remove(Gather);
4616 }
4617 // Reorder operands of the user node and set the ordering for the user
4618 // node itself.
4619 if (Data.first->State != TreeEntry::Vectorize ||
4620 !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
4621 Data.first->getMainOp()) ||
4622 Data.first->isAltShuffle())
4623 Data.first->reorderOperands(Mask);
4624 if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
4625 Data.first->isAltShuffle()) {
4626 reorderScalars(Data.first->Scalars, Mask);
4627 reorderOrder(Data.first->ReorderIndices, MaskOrder);
4628 if (Data.first->ReuseShuffleIndices.empty() &&
4629 !Data.first->ReorderIndices.empty() &&
4630 !Data.first->isAltShuffle()) {
4631 // Insert user node to the list to try to sink reordering deeper in
4632 // the graph.
4633 OrderedEntries.insert(Data.first);
4634 }
4635 } else {
4636 reorderOrder(Data.first->ReorderIndices, Mask);
4637 }
4638 }
4639 }
4640 // If the reordering is unnecessary, just remove the reorder.
4641 if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
4642 VectorizableTree.front()->ReuseShuffleIndices.empty())
4643 VectorizableTree.front()->ReorderIndices.clear();
4644}
4645
4647 const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
4648 // Collect the values that we need to extract from the tree.
4649 for (auto &TEPtr : VectorizableTree) {
4650 TreeEntry *Entry = TEPtr.get();
4651
4652 // No need to handle users of gathered values.
4653 if (Entry->State == TreeEntry::NeedToGather)
4654 continue;
4655
4656 // For each lane:
4657 for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
4658 Value *Scalar = Entry->Scalars[Lane];
4659 int FoundLane = Entry->findLaneForValue(Scalar);
4660
4661 // Check if the scalar is externally used as an extra arg.
4662 auto ExtI = ExternallyUsedValues.find(Scalar);
4663 if (ExtI != ExternallyUsedValues.end()) {
4664 LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
4665 << Lane << " from " << *Scalar << ".\n");
4666 ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
4667 }
4668 for (User *U : Scalar->users()) {
4669 LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
4670
4671 Instruction *UserInst = dyn_cast<Instruction>(U);
4672 if (!UserInst)
4673 continue;
4674
4675 if (isDeleted(UserInst))
4676 continue;
4677
4678 // Skip in-tree scalars that become vectors
4679 if (TreeEntry *UseEntry = getTreeEntry(U)) {
4680 Value *UseScalar = UseEntry->Scalars[0];
4681 // Some in-tree scalars will remain as scalar in vectorized
4682 // instructions. If that is the case, the one in Lane 0 will
4683 // be used.
4684 if (UseScalar != U ||
4685 UseEntry->State == TreeEntry::ScatterVectorize ||
4686 !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
4687 LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
4688 << ".\n");
4689 assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
4690 continue;
4691 }
4692 }
4693
4694 // Ignore users in the user ignore list.
4695 if (UserIgnoreList && UserIgnoreList->contains(UserInst))
4696 continue;
4697
4698 LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
4699 << Lane << " from " << *Scalar << ".\n");
4700 ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
4701 }
4702 }
4703 }
4704}
4705
4707BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const {
4709 for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) {
4710 Value *V = TE->Scalars[Lane];
4711 // To save compilation time we don't visit if we have too many users.
4712 static constexpr unsigned UsersLimit = 4;
4713 if (V->hasNUsesOrMore(UsersLimit))
4714 break;
4715
4716 // Collect stores per pointer object.
4717 for (User *U : V->users()) {
4718 auto *SI = dyn_cast<StoreInst>(U);
4719 if (SI == nullptr || !SI->isSimple() ||
4720 !isValidElementType(SI->getValueOperand()->getType()))
4721 continue;
4722 // Skip entry if already
4723 if (getTreeEntry(U))
4724 continue;
4725
4726 Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
4727 auto &StoresVec = PtrToStoresMap[Ptr];
4728 // For now just keep one store per pointer object per lane.
4729 // TODO: Extend this to support multiple stores per pointer per lane
4730 if (StoresVec.size() > Lane)
4731 continue;
4732 // Skip if in different BBs.
4733 if (!StoresVec.empty() &&
4734 SI->getParent() != StoresVec.back()->getParent())
4735 continue;
4736 // Make sure that the stores are of the same type.
4737 if (!StoresVec.empty() &&
4738 SI->getValueOperand()->getType() !=
4739 StoresVec.back()->getValueOperand()->getType())
4740 continue;
4741 StoresVec.push_back(SI);
4742 }
4743 }
4744 return PtrToStoresMap;
4745}
4746
4747bool BoUpSLP::canFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
4748 OrdersType &ReorderIndices) const {
4749 // We check whether the stores in StoreVec can form a vector by sorting them
4750 // and checking whether they are consecutive.
4751
4752 // To avoid calling getPointersDiff() while sorting we create a vector of
4753 // pairs {store, offset from first} and sort this instead.
4754 SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size());
4755 StoreInst *S0 = StoresVec[0];
4756 StoreOffsetVec[0] = {S0, 0};
4757 Type *S0Ty = S0->getValueOperand()->getType();
4758 Value *S0Ptr = S0->getPointerOperand();
4759 for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) {
4760 StoreInst *SI = StoresVec[Idx];
4761 std::optional<int> Diff =
4762 getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(),
4763 SI->getPointerOperand(), *DL, *SE,
4764 /*StrictCheck=*/true);
4765 // We failed to compare the pointers so just abandon this StoresVec.
4766 if (!Diff)
4767 return false;
4768 StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff};
4769 }
4770
4771 // Sort the vector based on the pointers. We create a copy because we may
4772 // need the original later for calculating the reorder (shuffle) indices.
4773 stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1,
4774 const std::pair<StoreInst *, int> &Pair2) {
4775 int Offset1 = Pair1.second;
4776 int Offset2 = Pair2.second;
4777 return Offset1 < Offset2;
4778 });
4779
4780 // Check if the stores are consecutive by checking if their difference is 1.
4781 for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size()))
4782 if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1)
4783 return false;
4784
4785 // Calculate the shuffle indices according to their offset against the sorted
4786 // StoreOffsetVec.
4787 ReorderIndices.reserve(StoresVec.size());
4788 for (StoreInst *SI : StoresVec) {
4789 unsigned Idx = find_if(StoreOffsetVec,
4790 [SI](const std::pair<StoreInst *, int> &Pair) {
4791 return Pair.first == SI;
4792 }) -
4793 StoreOffsetVec.begin();
4794 ReorderIndices.push_back(Idx);
4795 }
4796 // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in
4797 // reorderTopToBottom() and reorderBottomToTop(), so we are following the
4798 // same convention here.
4799 auto IsIdentityOrder = [](const OrdersType &Order) {
4800 for (unsigned Idx : seq<unsigned>(0, Order.size()))
4801 if (Idx != Order[Idx])
4802 return false;
4803 return true;
4804 };
4805 if (IsIdentityOrder(ReorderIndices))
4806 ReorderIndices.clear();
4807
4808 return true;
4809}
4810
4811#ifndef NDEBUG
4813 for (unsigned Idx : Order)
4814 dbgs() << Idx << ", ";
4815 dbgs() << "\n";
4816}
4817#endif
4818
4820BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const {
4821 unsigned NumLanes = TE->Scalars.size();
4822
4824 collectUserStores(TE);
4825
4826 // Holds the reorder indices for each candidate store vector that is a user of
4827 // the current TreeEntry.
4828 SmallVector<OrdersType, 1> ExternalReorderIndices;
4829
4830 // Now inspect the stores collected per pointer and look for vectorization
4831 // candidates. For each candidate calculate the reorder index vector and push
4832 // it into `ExternalReorderIndices`
4833 for (const auto &Pair : PtrToStoresMap) {
4834 auto &StoresVec = Pair.second;
4835 // If we have fewer than NumLanes stores, then we can't form a vector.
4836 if (StoresVec.size() != NumLanes)
4837 continue;
4838
4839 // If the stores are not consecutive then abandon this StoresVec.
4840 OrdersType ReorderIndices;
4841 if (!canFormVector(StoresVec, ReorderIndices))
4842 continue;
4843
4844 // We now know that the scalars in StoresVec can form a vector instruction,
4845 // so set the reorder indices.
4846 ExternalReorderIndices.push_back(ReorderIndices);
4847 }
4848 return ExternalReorderIndices;
4849}
4850
4852 const SmallDenseSet<Value *> &UserIgnoreLst) {
4853 deleteTree();
4854 UserIgnoreList = &UserIgnoreLst;
4855 if (!allSameType(Roots))
4856 return;
4857 buildTree_rec(Roots, 0, EdgeInfo());
4858}
4859
4861 deleteTree();
4862 if (!allSameType(Roots))
4863 return;
4864 buildTree_rec(Roots, 0, EdgeInfo());
4865}
4866
4867/// \return true if the specified list of values has only one instruction that
4868/// requires scheduling, false otherwise.
4869#ifndef NDEBUG
4871 Value *NeedsScheduling = nullptr;
4872 for (Value *V : VL) {
4874 continue;
4875 if (!NeedsScheduling) {
4876 NeedsScheduling = V;
4877 continue;
4878 }
4879 return false;
4880 }
4881 return NeedsScheduling;
4882}
4883#endif
4884
4885/// Generates key/subkey pair for the given value to provide effective sorting
4886/// of the values and better detection of the vectorizable values sequences. The
4887/// keys/subkeys can be used for better sorting of the values themselves (keys)
4888/// and in values subgroups (subkeys).
4889static std::pair<size_t, size_t> generateKeySubkey(
4890 Value *V, const TargetLibraryInfo *TLI,
4891 function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
4892 bool AllowAlternate) {
4893 hash_code Key = hash_value(V->getValueID() + 2);
4894 hash_code SubKey = hash_value(0);
4895 // Sort the loads by the distance between the pointers.
4896 if (auto *LI = dyn_cast<LoadInst>(V)) {
4897 Key = hash_combine(LI->getType(), hash_value(Instruction::Load), Key);
4898 if (LI->isSimple())
4899 SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
4900 else
4901 Key = SubKey = hash_value(LI);
4902 } else if (isVectorLikeInstWithConstOps(V)) {
4903 // Sort extracts by the vector operands.
4904 if (isa<ExtractElementInst, UndefValue>(V))
4905 Key = hash_value(Value::UndefValueVal + 1);
4906 if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
4907 if (!isUndefVector(EI->getVectorOperand()).all() &&
4908 !isa<UndefValue>(EI->getIndexOperand()))
4909 SubKey = hash_value(EI->getVectorOperand());
4910 }
4911 } else if (auto *I = dyn_cast<Instruction>(V)) {
4912 // Sort other instructions just by the opcodes except for CMPInst.
4913 // For CMP also sort by the predicate kind.
4914 if ((isa<BinaryOperator, CastInst>(I)) &&
4915 isValidForAlternation(I->getOpcode())) {
4916 if (AllowAlternate)
4917 Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
4918 else
4919 Key = hash_combine(hash_value(I->getOpcode()), Key);
4920 SubKey = hash_combine(
4921 hash_value(I->getOpcode()), hash_value(I->getType()),
4922 hash_value(isa<BinaryOperator>(I)
4923 ? I->getType()
4924 : cast<CastInst>(I)->getOperand(0)->getType()));
4925 // For casts, look through the only operand to improve compile time.
4926 if (isa<CastInst>(I)) {
4927 std::pair<size_t, size_t> OpVals =
4928 generateKeySubkey(I->getOperand(0), TLI, LoadsSubkeyGenerator,
4929 /*AllowAlternate=*/true);
4930 Key = hash_combine(OpVals.first, Key);
4931 SubKey = hash_combine(OpVals.first, SubKey);
4932 }
4933 } else if (auto *CI = dyn_cast<CmpInst>(I)) {
4934 CmpInst::Predicate Pred = CI->getPredicate();
4935 if (CI->isCommutative())
4936 Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
4938 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
4939 hash_value(SwapPred),
4940 hash_value(CI->getOperand(0)->getType()));
4941 } else if (auto *Call = dyn_cast<CallInst>(I)) {
4944 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
4945 } else if (!VFDatabase(*Call).getMappings(*Call).empty()) {
4946 SubKey = hash_combine(hash_value(I->getOpcode()),
4947 hash_value(Call->getCalledFunction()));
4948 } else {
4949 Key = hash_combine(hash_value(Call), Key);
4950 SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
4951 }
4952 for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
4953 SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
4954 hash_value(Op.Tag), SubKey);
4955 } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
4956 if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
4957 SubKey = hash_value(Gep->getPointerOperand());
4958 else
4959 SubKey = hash_value(Gep);
4960 } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
4961 !isa<ConstantInt>(I->getOperand(1))) {
4962 // Do not try to vectorize instructions with potentially high cost.
4963 SubKey = hash_value(I);
4964 } else {
4965 SubKey = hash_value(I->getOpcode());
4966 }
4967 Key = hash_combine(hash_value(I->getParent()), Key);
4968 }
4969 return std::make_pair(Key, SubKey);
4970}
4971
4972/// Checks if the specified instruction \p I is an alternate operation for
4973/// the given \p MainOp and \p AltOp instructions.
4974static bool isAlternateInstruction(const Instruction *I,
4975 const Instruction *MainOp,
4976 const Instruction *AltOp,
4977 const TargetLibraryInfo &TLI);
4978
4979void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
4980 const EdgeInfo &UserTreeIdx) {
4981 assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
4982
4983 SmallVector<int> ReuseShuffleIndicies;
4984 SmallVector<Value *> UniqueValues;
4985 auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
4986 &UserTreeIdx,
4987 this](const InstructionsState &S) {
4988 // Check that every instruction appears once in this bundle.
4989 DenseMap<Value *, unsigned> UniquePositions(VL.size());
4990 for (Value *V : VL) {
4991 if (isConstant(V)) {
4992 ReuseShuffleIndicies.emplace_back(
4993 isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
4994 UniqueValues.emplace_back(V);
4995 continue;
4996 }
4997 auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
4998 ReuseShuffleIndicies.emplace_back(Res.first->second);
4999 if (Res.second)
5000 UniqueValues.emplace_back(V);
5001 }
5002 size_t NumUniqueScalarValues = UniqueValues.size();
5003 if (NumUniqueScalarValues == VL.size()) {
5004 ReuseShuffleIndicies.clear();
5005 } else {
5006 LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
5007 if (NumUniqueScalarValues <= 1 ||
5008 (UniquePositions.size() == 1 && all_of(UniqueValues,
5009 [](Value *V) {
5010 return isa<UndefValue>(V) ||
5011 !isConstant(V);
5012 })) ||
5013 !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
5014 LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
5015 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
5016 return false;
5017 }
5018 VL = UniqueValues;
5019 }
5020 return true;
5021 };
5022
5023 InstructionsState S = getSameOpcode(VL, *TLI);
5024
5025 // Gather if we hit the RecursionMaxDepth, unless this is a load (or z/sext of
5026 // a load), in which case peek through to include it in the tree, without
5027 // ballooning over-budget.
5028 if (Depth >= RecursionMaxDepth &&
5029 !(S.MainOp && isa<Instruction>(S.MainOp) && S.MainOp == S.AltOp &&
5030 VL.size() >= 4 &&
5031 (match(S.MainOp, m_Load(m_Value())) || all_of(VL, [&S](const Value *I) {
5032 return match(I,
5034 cast<Instruction>(I)->getOpcode() ==
5035 cast<Instruction>(S.MainOp)->getOpcode();
5036 })))) {
5037 LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
5038 if (TryToFindDuplicates(S))
5039 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5040 ReuseShuffleIndicies);
5041 return;
5042 }
5043
5044 // Don't handle scalable vectors
5045 if (S.getOpcode() == Instruction::ExtractElement &&
5046 isa<ScalableVectorType>(
5047 cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
5048 LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
5049 if (TryToFindDuplicates(S))
5050 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
5051 ReuseShuffleIndicies);
5052 return;
5053 }
5054
5055 // Don't handle vectors.
5056 if (S.OpValue->getType()->isVectorTy() &&
5057 !isa<InsertElementInst>(S.OpValue)) {
5058 LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
5059 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
5060 return;
5061 }
5062
5063 if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
5064 if (SI->getValueOperand()->getType()->isVectorTy()) {
5065 LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
5066 newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
5067 return;
5068 }
5069
5070 // If all of the operands are identical or constant we have a simple solution.
5071 // If we deal with insert/extract instructions, they all must have constant
5072 // indices, otherwise we should gather them, not try to vectorize.
5073 // If alternate op node with 2 elements